From kyosohma at gmail.com Wed Jun 11 07:47:29 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 11 Jun 2008 04:47:29 -0700 (PDT) Subject: Python doesn't understand %userprofile% References: Message-ID: On Jun 11, 1:58?am, Tim Roberts wrote: > bsag... at gmail.com wrote: > > >In xp when I try os.path.getmtime("%userprofile/dir/file%") Python > >bites back with "cannot find the path specified" Since my script has > >to run on machines where the username is unspecified I need a fix. > > For the record, the %PERCENT% syntax for looking up an environment variable > is just a feature of the XP command shell. ?It has no meaning to any other > part of Windows. > > os.environ is the right answer. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. You can use it at the Run command or in Explorer too. If I type %username% in either place, it opens the following on my XP machine: C: \Documents and Settings\Mike Mike From fc14301589 at icqmail.com Tue Jun 10 19:51:17 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Wed, 11 Jun 2008 07:51:17 +0800 Subject: Python doesn't understand %userprofile% References: Message-ID: <484f1375_1@news.tm.net.my> On 00:11, mercoled? 11 giugno 2008 Tim Golden wrote: > "%USERPROFILE%/dir/file". os.environ('USERPROFILE') should return an info regarding that environment variable. I guess that, not yet tried. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From omer at no-log.org Sun Jun 15 07:47:28 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Sun, 15 Jun 2008 13:47:28 +0200 Subject: NoneType Error In-Reply-To: References: Message-ID: <200806151347.28948.omer@no-log.org> Hi, Le Sunday 15 June 2008 10:35:18 Maryam Saeedi, vous avez ?crit?: > I am using a python program on a lot of different documents and for few of > them I will get NoneType error. I just want to skip those files and > continue for others, I do this without a problem for > IndexError,TypeError,ValueError,NameError : > > try: > .... > except (IndexError,TypeError,ValueError,NameError): > .... > > but when I add NoneType it gives the following error: > except (NoneType,IndexError,TypeError,ValueError,NameError): > NameError: name 'NoneType' is not defined > > and if I do not use the NoneType then it does not go through either and > stops the program when I get to such a file. Is there another name that > captures this error? > > Thanks for your help, > > Maryam you can get the none type with None.__class__ or with the 'types' module, but it won't work as the except handler only accepts Exception classes. It sounds like you're confusing with some other error, what is the exact message of your 'NoneType error' ? The exception type you want to catch should be at the beginning of it (as in 'TypeError: blah blah...') -- C?dric Lucantis From richardlev at gmail.com Tue Jun 3 14:02:38 2008 From: richardlev at gmail.com (Richard Levasseur) Date: Tue, 3 Jun 2008 11:02:38 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> Message-ID: On Jun 3, 3:07 am, "BJ?rn Lindqvist" wrote: > On Mon, Jun 2, 2008 at 10:50 PM, Russ P. wrote: > > On Jun 2, 6:41 am, Carl Banks wrote: > > >> You are not realizing that only useful(**) thing about data hiding is > >> that some code has access to the data, other code does not. If you > >> "hide" data equally from everyone it's just a useless spelling change. > > > I think you're missing the point. > > > As I see it, the primary value of data hiding is that it provides > > useful information on which data and methods are intended for the > > client and which are intended for internal use. It's like putting a > > front panel on a TV set with the main controls intended for the > > viewer. > > Here's my two cents. First of all, a TV is a bad analogy compared to > reusable software libraries. Really bad analogy. A TV is a horribly > complicated device which has to be dumbed down because otherwise it > would be to hard to use for ordinary people. > > A software developers relation to a third party library is more > similar to a TV repair man trying to repair a TV than to a random > person watching TV. For a repair man, the front panel is just useless > and in the way. > > Oh, and to continue on the TV analogy, one of the reason why a TV is > complicated is because its interface is totally different from its > implementation. Channels are just a bad abstraction for tuning the > receiver to different frequencies and for switching inputs. Merely > using a TV doesn't teach you anything about how it actually works. > > KISS: Keep It Simple Stupid. And it is always simpler to not implement > the gunk needed for data hiding than to do it. By keeping things > simple you keep your code easy to implement, easy to understand and > easy to reuse. > > Data hiding sacrifices implementation simplicity supposedly to make > the interface simpler and to keep backwards compatibility. It allows > you to change implementation details without affecting the > interface. But do you really want to do that? Consider this silly Java > example: > > class Foo { > private int bar; > public int getBar() { > return bar; > } > }; > > Then for some reason you decide that hm, "bar" is not a good attribute > name so you change it to "babar". And you can do that without changing > the public interface! Woho! So now you have a public getter named > "getBar" that returns an attribute named "babar". That's in reality > just bad and whoever is maintaining the implementation is going to be > annoyed that the getters name doesn't match the attribute name. > > What would have happened without data hiding? Renaming the public > attribute "bar" to "babar" probably cause some grief for someone > reusing your library, but you would keep your implementation pure. > > What about semantic changes? Data hiding doesn't protect you against > that, so you'll have to change your interface anyway. The interface > for a car hasn't changed much in the last 100 years, but the > implementation has. How easy is it to repair a car nowadays compared > to 30 years ago? > > And data hiding as a documentation aid is just a sham. "These methods > are public so you can call them, these aren't so hands off!" A reuser > of your library *will* want to know what happens on the inside, by > trying to make stuff impossible to reach you are just making that kind > of information much harder to come by. > > The better method is to just write proper docstrings that tell the > user what the methods do and when they can be called. > > Another good way to see how useless data hiding is, is to try and unit > test a very encapsulated library. You'll see that it is almost > impossible to write good unit tests unless you publicly export > almost everything in the code. At which point you come to realize that > all the data hiding was for naught. > > -- > mvh Bj?rn I really like this message and find it very true. Writing unit tests for private data is nigh impossible. You end up either creating accessors, or passing in parameters via the constructor (resulting in a huge constructor). Personally, I'd rather have better test coverage than data hiding. Second, private vars with third party libs suck, and are nothing but an infuriating frustration. I'm currently dealing with about 3 or 4 different libs, one of them uses private variables and its a huge headache. I have to access some of those private vars occasionally to make my thing work. The other libs i'm using don't have any private vars (__) (only a couple protected ones, _), and its a breeze. The docs say "this does x" or there's a comment that says "don't use this unless you really know what you're doing," and I respect their warnings. When I was fooling around with sqlalchemy, it made heavy use of protected vars but had a straight forward public api. Unfortunately, writing plugins for it required access to some of those protected vars. It wouldn't be possible if they were strictly controlled and restricted by the language itself. Whenever I'd use those protected vars, I expected an odd behavior or two. When using private vars, I don't expect it to work at all, and really, refrain from using them unless i've grokked the source. My point is that I currently like the private/protected/public scheme python has going on. It lets me fix or alter things if I have to, but also provides a warning that I shouldn't be doing this. As for customers using the internals and worrying about an upgrade breaking them, it seems likes a silly issue, at least in python. If there are internals that the customer would be playing with, then it should be exposed publically, since they want it that way to begin with. If they're using defunct variables or methods, you use properties and __getattr__ to maintain backwards compatibility for a version or two. From bearophileHUGS at lycos.com Tue Jun 24 11:06:09 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 24 Jun 2008 08:06:09 -0700 (PDT) Subject: Bit substring search References: <5043fee7-444b-41dd-a419-77550595d273@79g2000hsk.googlegroups.com> Message-ID: <5135a9f6-d8a5-4812-88b5-bc5fa28ece71@25g2000hsx.googlegroups.com> Kris Kennaway: > Unfortunately I didnt find anything else useful here yet :( I see, I'm sorry, I have found hachoir quite nice in the past. Maybe there's no really efficient way to do it with Python, but you can create a compiled extension, so you can see if it's fast enough for your purposes. To create such extension you can: - One thing that requires very little time is to create an extension with ShedSkin, once installed it just needs Python code. - Cython (ex-Pyrex) too may be okay, but it's a bit trikier on Windows machines. - Using Pyd to create a D extension for Python is often the faster way I have found to create extensions. I need just few minutes to create them this way. But you need to know a bit of D. - Then, if you want you can write a C extension, but if you have not done it before you may need some hours to make it work. Bye, bearophile From vlastimil.brom at gmail.com Mon Jun 23 18:12:56 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Tue, 24 Jun 2008 00:12:56 +0200 Subject: regexp: match only if previous matched? In-Reply-To: <95ccceb7-c628-49f8-95bc-17f3740b1b27@m3g2000hsc.googlegroups.com> References: <95ccceb7-c628-49f8-95bc-17f3740b1b27@m3g2000hsc.googlegroups.com> Message-ID: <9fdb569a0806231512v6124356eo5a076645decddb3e@mail.gmail.com> 2008/6/24, cirfu : > > I need to extract prices froma html-document. > > [0-9]*\$ matches 112$ 45$ etc but also just a $. why that shouldnt > really matter and it is unlikely anyway to appear a $sign with no > price attahced to it I still want to prevent it. > > How do I avoid matching "$"? It has to be "nbr$". > > -- > http://mail.python.org/mailman/listinfo/python-list > In this simple case you can simple use something like: [0-9]+\$ ie. at least one digit immediately folowed by a dollar-sign If you really needed to check for a preceding text, look into look-behind assertions of the form (?<=...) or (? From sjmachin at lexicon.net Thu Jun 12 19:35:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 12 Jun 2008 16:35:37 -0700 (PDT) Subject: Exception : Unknown Run-Time error : 210 References: Message-ID: <6b910e53-3b3f-47c7-aef7-8b0bdfc99142@l64g2000hse.googlegroups.com> On Jun 13, 4:31 am, "Sa?a Bistrovi?" wrote: > "Sa?a Bistrovi?" wrote in message > > news:g2rftn$ghv$1 at ss408.t-com.hr... > > > > > Sa?a Bistrovi? > > Antuna Mihanvi?a 13 > > 40000 ?akovec > > Croatia > > sasa.bistro... at ck.t-com.hr > > > FPC: Exception : Unknown Run-Time error : 210 > > > Hi, I'm Sa?a from Croatia. > > > And I have : > > > Windows XP PRO SP3. > > Pentium II MMX 400MHz. > > 256 MB of RAM. > > > I tried to compile fp.pas. > > > But I get this error message : > > > 'Running "c:\fpc\fpcbuild-2.2.0\fpcsrc\ide\fp.exe "' > > 'Starting value of ConsoleMode is $0000001F' > > 'Compiler Verison f p c b u i l d - 2 . 2 . 0 \ f p c s r c \ i d e \ f p > > . e x e ' + same unknown exe characters as for GBD Verison > > 'GBD Verison f p c b u i l d - 2 . 2 . 0 \ f p c s r c \ i d e \ f p . e > > x e ' + same unknown exe characters as for Compiler Verison > > 'Cygwin "C:\FPC\222A5D~1.0\BIN\I386-W~1\cygwin1.dll" version 1005.18.0.0' > > 'An unhandled exception occurred at $004A74E6' > > 'Exception : Unknown Run-Time error : 210' > > ' $004A74E6 TSWITCHES__ADDBOOLEANITEM, line 602 of > > c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/FPSwitch.pas' > > ' $004A92F4 INITSWITCHES, line 1150 of > > c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/FPSwitch.pas' > > ' $004020DF main, line 382 of c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/fp.pas' > > What is right newsgroup for Free Pascal Compiler ? Perhaps you were looking for comp.lang.pascal ... but you have arrived at comp.lang.python. Why bother with a newsgroup, when there seems to be a well-organised website for FPC with a forum for answering questions? My googler led me to http://community.freepascal.org:10000/ ... have a look for yourself. On the other hand, if you are interested in a better language, please do stay on here :-) HTH, John From news at prodata.co.uk Mon Jun 23 11:38:43 2008 From: news at prodata.co.uk (John Dann) Date: Mon, 23 Jun 2008 16:38:43 +0100 Subject: Passing arguments to subclasses Message-ID: <7pgv54l0pfaa2l05c4l8f3bld1rskd4dtf@4ax.com> May I ask a simple newbie question, which I presume is true, but for which I can't readily find confirmation: Let's say I have a parent class with an __init__ method explicitly defined: class ParentClass(object): def __init__(self, keyword1, keyword2): etc and I subclass this: class ChildClass(ParentClass): # No __init__ method explicitly defined Now I presume that I can instantiate a child object as: child = ChildClass(arg1, arg2) and arg1, arg2 will be passed through to the 'constructor' of the antecedent ParentClass (there being no overrriding __init__ method defined for ChildClass) and mapping to keyword1, keyword2 etc. Have I understood this correctly? From goldnery at gmail.com Sat Jun 7 20:08:23 2008 From: goldnery at gmail.com (Gandalf) Date: Sat, 7 Jun 2008 17:08:23 -0700 (PDT) Subject: SQlite none english char Message-ID: I works with python 2.5 on windows, And I use sqlite3 Now, I have problem searching string in Hebrew in my database I have table called "test" with field num and test firs row i insert "1" and "?????" (that is "Hebrew" in Hebrew) second row i insert "2" and "English" now this code will print me >>> English as it should: i="Englisht" cur.execute("select * from `test` where text like '%"+i+"%' ") for row in cur: print row[1] but this one print me nothing >>> instead of ????? i="?????" cur.execute("select * from `test` where text like '%"+i+"%' ") for row in cur: print row[1] does any one have an idea how can i solve it? From dholth at gmail.com Wed Jun 11 14:23:43 2008 From: dholth at gmail.com (Daniel Holth) Date: Wed, 11 Jun 2008 14:23:43 -0400 Subject: PKG-INFO encoding? Message-ID: What should the encoding be for PKG-INFO? PEP 241, 301, 314, and 345 do not specify. I notice PKG-INFO must comply with an RFC that predates Unicode, and I notice I get a traceback if I try to put a non-ascii character into my Python 2.4.3 setup.py description. (I eventually decided to just .encode('utf-8') in setup.py) Thanks, Daniel Holth -------------- next part -------------- An HTML attachment was scrubbed... URL: From workitharder at gmail.com Thu Jun 5 21:16:39 2008 From: workitharder at gmail.com (bukzor) Date: Thu, 5 Jun 2008 18:16:39 -0700 (PDT) Subject: Guide to organizing modules? References: <1611a070-35f9-4072-b95f-ab592820f516@c65g2000hsa.googlegroups.com> <5b68316f-b2d6-4cec-bb8e-c9ed55202842@v26g2000prm.googlegroups.com> Message-ID: <306b95b3-66f5-4b46-87af-474b6c75b07b@27g2000hsf.googlegroups.com> On Jun 5, 5:58 pm, alex23 wrote: > On Jun 6, 10:32 am, bukzor wrote: > > > In summary: are there any good (or official) guidelines for how to > > organize and separate python functions and classes into modules? > > Hey bukzor, > > Are you familiar with the concept of packages in Python? > > http://docs.python.org/tut/node8.html#SECTION008400000000000000000 > > That should allow you to keep all of your scriptlets as separate files > while still having the advantage of keeping them in a single namespace > for importing. > > (But if you know this already, don't mind me....) Yes, in the above post I meant to say package where I said module. Right now all my functions are in the __init__.py script, and I would consider separating them out into sub-packages, if it had any rhyme or reason, but right now that escapes me. That's mostly what I'm trying to ask for. Thanks, --Buck From robert.kern at gmail.com Fri Jun 27 20:10:56 2008 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 27 Jun 2008 19:10:56 -0500 Subject: Do I need "self" and "other"? In-Reply-To: References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> <04e2afb7-b96c-446a-816a-ffac0ea81d5b@p25g2000hsf.googlegroups.com> Message-ID: Terry Reedy wrote: > > Kurda Yon wrote: >> >> OK, I see. In the given example "self" is just a name which can be >> replace by whichever (valid) name. Is that always like that? I mean, >> does "slef" have a special meaning in some cases or it is always "just >> a name like any other"? > > Yes. > > A method is a function bound to a class or instance thereof. > Def statements create functions. Parameter names are arbitrary, as long > as they do not conflict with any global names you want to access from > within the function. > > Self (and other) are simply community conventions. They do have they > advantage that if they are only used as function/method parameter names, > then they will not conflict with any module globals. It's worth noting that 'self' for the first parameter of a method is an extremely strong convention. I highly encourage you to follow it. In particular, classmethods and staticmethods don't take an instance of the class as the first argument, so using 'self' for instance methods, 'cls' for classmethods, and nothing in particular for staticmethods (since the first argument isn't special at all), helps distinguish them when reading. You risk annoying your reader by using something other than 'self' in an instance method. By contrast, using 'other' for the other argument to a binary __mathoperation__ method is not a particularly strong convention. No one will be annoyed if you use something else. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From tjreedy at udel.edu Sat Jun 14 14:49:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 14 Jun 2008 14:49:15 -0400 Subject: numpy: handling float('NaN') different in XP vs. Linux References: <17835502.post@talk.nabble.com> Message-ID: "Christian Heimes" wrote in message news:g30h90$dsj$1 at ger.gmane.org... || I've fixed the issue for Python 2.6 and 3.0 a while ago. Mark and I have | spent a lot of time on fixing several edge cases regarding inf, nan and | numerical unsound functions in Python's math und cmath module. I just tested 'NaN' on XP. Works. Thanks. From max at alcyone.com Mon Jun 16 23:41:49 2008 From: max at alcyone.com (Erik Max Francis) Date: Mon, 16 Jun 2008 20:41:49 -0700 Subject: Does '!=' equivelent to 'is not' In-Reply-To: References: Message-ID: pirata wrote: > I'm a bit confusing about whether "is not" equivelent to "!=" > > if a != b: > ... > > if a is not b: > ... > > > What's the difference between "is not" and "!=" or they are the same thing? The `==` operator tests equality. The `is` operator tests identity. If you don't specifically intend to test for identity, use `==`. If you don't know what identity tests are for (with the exception of testing for None-ness), then you don't need it. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Do we ask what profit the little bird hopes for in singing? -- Johannes Kepler, 1571-1630 From geonomica at gmail.com Tue Jun 3 09:28:57 2008 From: geonomica at gmail.com (gianluca) Date: Tue, 3 Jun 2008 06:28:57 -0700 (PDT) Subject: printf in python References: <261cbf38-6f0d-4525-9b4a-11ddbb910b66@d45g2000hsc.googlegroups.com> <183dfd01-68a5-4ae8-a04a-c3689d77003e@m3g2000hsc.googlegroups.com> Message-ID: <0f7b7836-ed92-4a02-9eba-4ff7fe4a94cd@m36g2000hse.googlegroups.com> On 3 Giu, 12:48, gianluca wrote: > On 2 Giu, 20:51, gianluca wrote: > > > > > On 2 Giu, 17:54, Dennis Lee Bieber wrote: > > > > On Mon, 2 Jun 2008 00:32:33 -0700 (PDT), gianluca > > > declaimed the following in comp.lang.python: > > > > > Hy, I've a problem with may python library generated with swig from C > > > > code. I works and I can access all function but a sim?ple function > > > > that print a string don't work's. > > > > The function is like this: > > > > int PrintTEST() > > > > { > > > > printf("TEST "); > > > > return 1; > > > > } > > > > > If I call the function (myDLL.PrintTEST() ) the function print only > > > > the returned value, not the string "TEST". Could anybody help me? > > > > Are you running from a command shell? > > > > If you are testing from inside something like IDLE (or PythonWin, or > > > pretty much any other GUI development system) you may not have a stdout > > > for display by C code... > > > > The return value would be printed by the Python interpreter in > > > interactive mode... > > > -- > > > Wulfraed Dennis Lee Bieber KD6MOG > > > wlfr... at ix.netcom.com wulfr... at bestiaria.com > > > HTTP://wlfraed.home.netcom.com/ > > > (Bestiaria Support Staff: web-a... at bestiaria.com) > > > HTTP://www.bestiaria.com/ > > > Hy, > > the problem exists both in command shell and in IDLE. The value is > > correct returned in both envirnment. > > > gianluca > > Anybody help me? I know!! I'm bore!! But I need help indeed!! I'm looking inside lib_wrap.c generated by swig. In the wrap function there is no printf function. If is this the problem how can I do to resolve it? thanks Gianluca From bignose+hates-spam at benfinney.id.au Sun Jun 15 21:43:43 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 16 Jun 2008 11:43:43 +1000 Subject: The best way to package a Python module? References: Message-ID: <8763sa9msw.fsf@benfinney.id.au> Jean-Paul Calderone writes: > >What has changed is that the tools in common use for Debian > >packaging of Python libraries have taken on the role of generating > >those per-version copies at install time. > > exarkun at boson:~$ ls -l /usr/lib/python2.{4,5}/site-packages/sqlite/main.py > lrwxrwxrwx 1 root root 63 2007-12-27 15:29 /usr/lib/python2.4/site-packages/sqlite/main.py -> /usr/share/pycentral/python-sqlite/site-packages/sqlite/main.py > lrwxrwxrwx 1 root root 63 2007-12-27 15:29 /usr/lib/python2.5/site-packages/sqlite/main.py -> /usr/share/pycentral/python-sqlite/site-packages/sqlite/main.py > exarkun at boson:~$ > > That doesn't seem to agree with your statement. Am I missing something? You are missing an inspection of the contents of the actual package file. The package file itself contains only a single copy of the Python module (at /usr/share/pycentral/site-packages/sqlite/main.py). What you see there on your filesystem was created at install time; the installation tool figures out, at install time, which Python versions need to be supported on this particular system, and creates those symlinks. Thus, the change that's occurred is that the user doesn't need to choose between "Python SQLite library for Python 2.4" and "Python SQLite library for Python 2.5". There is no longer a separation at the package level by Python version, so the user merely needs to choose (given your example) the single "Python SQLite library", and the install process takes care of setting it up for all supported versions of Python on the system. -- \ ?[Freedom of speech] isn't something somebody else gives you. | `\ That's something you give to yourself.? ?_Hocus Pocus_, | _o__) Kurt Vonnegut | Ben Finney From gagsl-py2 at yahoo.com.ar Mon Jun 16 01:24:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 16 Jun 2008 02:24:32 -0300 Subject: Hard to understand 'eval' References: <485381e7_2@news.tm.net.my> Message-ID: En Sat, 14 Jun 2008 05:31:35 -0300, TheSaint escribi?: > It seems to be strange that give me syntax error inside an eval statement. > I'm looking at it carefully but I can't see any flaw. > > Here it's part of the code: > > for nn in stn_items: > value= eval('cp.%s' %nn) > if value and (nn in 'log, trash, multithread, verbose, download'): > cfl[wchkey][nn]= chkbool(value) > continue > if value: > cnfg= 'cfl[wchkey][nn]= _%s(value)' %nn > eval(cnfg) > > And the output on pdb: > > (Pdb) p cnfg > 'cfl[wchkey][nn]=_append(value)' > (Pdb) p cfl[wchkey][nn] > False > (Pdb) eval('cfl[wchkey][nn]= _append(value)') > *** SyntaxError: invalid syntax (, line 1) Others have already remarked that your general approach is bad ("don't use eval!", in short). But none has pointed out the actual error in your code: eval can accept only an *expression*, not a statement. eval("x=1") gives the same SyntaxError. (`exec` is the way to execute statements, but the same caveats apply, so: don't use exec either, use getattr/setattr instead) -- Gabriel Genellina From deets at nospam.web.de Mon Jun 9 11:33:14 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 09 Jun 2008 17:33:14 +0200 Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> <41de7980-749a-4f46-add1-12010b6e95d9@b1g2000hsg.googlegroups.com> <8f9b0c13-9b90-4352-acbc-ec15a9e2f8bc@f63g2000hsf.googlegroups.com> Message-ID: <6b50r2F3a49r4U1@mid.uni-berlin.de> Frank Millman wrote: > On Jun 9, 4:06?pm, Frank Millman wrote: >> >> Thanks for the reply, Mel. I don't quite understand what you mean. > > As so often happens, after I sent my reply I re-read your post and I > think I understand what you are getting at. > > One problem with my approach is that I am truncating the result down > to the desired scale factor every time I create a new instance. This > could result in a loss of precision if I chain a series of instances > together in a calculation. I think that what you are suggesting avoids > this problem. > > I will read your message again carefully. I think it will lead to a > rethink of my approach. > > Thanks again > > Frank > > P.S. Despite my earlier reply to Paul, I have not abandoned the idea > of using my Number class as opposed to the standard Decimal class. > > I did a simple test of creating two instances and adding them > together, using both methods, and timing them. Decimal came out 6 > times slower than Number. > > Is that important? Don't know, but it might be. It is because it uses arbitrary precision integer literals instead of ieee floats. It pays this price so you get decimal rounding errors instead of binary. Yet rounding errors you get... If you are in money calculations with your Number-class - you certainly want Decimal instead. If all you want is auto-rounding... then you might not care. Diez From paolopantaleo at gmail.com Wed Jun 4 11:31:33 2008 From: paolopantaleo at gmail.com (PAolo) Date: Wed, 4 Jun 2008 08:31:33 -0700 (PDT) Subject: Embedding python a la erb Message-ID: <08bb34d1-07b2-411f-a38d-77c7798df3ba@j22g2000hsf.googlegroups.com> hello, is there any other tool for embedding python as erb (for ruby) or empy do. In particular I am not too happy about the way loops are made @[for i in range(10)]@ xxx @(i) @[end for] which is different form the way other code is delimited @{print 1+1} I think in PHP there is not this difference and maybe in JSP too. Is there any simple way to use PSP for that purpose? Thanks Paolo From faheem at email.unc.edu Wed Jun 18 18:13:01 2008 From: faheem at email.unc.edu (Faheem Mitha) Date: Wed, 18 Jun 2008 22:13:01 +0000 (UTC) Subject: python string comparison oddity References: <3ebd170e-8686-4bb4-9e47-0fba2179feb3@p39g2000prm.googlegroups.com> Message-ID: On Wed, 18 Jun 2008 12:57:44 -0700 (PDT), Lie wrote: > On Jun 19, 2:26?am, Faheem Mitha wrote: >> Hi everybody, >> >> I was wondering if anyone can explain this. My understanding is that 'is' >> checks if the object is the same. However, in that case, why this >> inconsistency for short strings? I would expect a 'False' for all three >> comparisons. This is reproducible across two different machines, so it is >> not just a local quirk. I'm running Debian etch with Python 2.4.4 (the >> default). >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Thanks, Faheem. >> >> In [1]: a = '--' >> >> In [2]: a is '--' >> Out[2]: False >> >> In [4]: a = '-' >> >> In [5]: a is '-' >> Out[5]: True >> >> In [6]: a = 'foo' >> >> In [7]: a is 'foo' >> Out[7]: True > > Yes, this happens because of small objects caching. When small > integers or short strings are created, there are possibility that they > might refer to the same objects behind-the-scene. Don't rely on this > behavior. Yes, but why is '-' and 'foo' cached, and not '--'? Do you know what the basis of the choice is? Faheem. From yiwei900 at gmail.com Sun Jun 22 01:14:32 2008 From: yiwei900 at gmail.com (nokia) Date: Sat, 21 Jun 2008 22:14:32 -0700 (PDT) Subject: you can see lots of beautiful girl here, also you can see...... Message-ID: <4d765d61-17b7-4b77-826b-206563eccf2d@w1g2000prd.googlegroups.com> http://www.flixya.com/photo/360355/beautiful_ From bruno.desthuilliers at gmail.com Mon Jun 9 17:39:44 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 9 Jun 2008 14:39:44 -0700 (PDT) Subject: Separators inside a var name References: Message-ID: <3be4a686-16fc-4b20-8c51-df1addc5cefc@m3g2000hsc.googlegroups.com> On 9 juin, 20:05, "Sebastian \"lunar\" Wiesner" wrote: > Rainy at Montag 09 Juni 2008 19:29: > (snip) > > From what I understand, scheme can have variables like var-name. I'm > > curious about reasons that python chose to disallow this. > > "-" is an operator in Python. How should the parser know, > whether "var-name" means "the object bound to var_dash_name" or "subtract > the object bound to name from the object bound to var"? > > Scheme can allows such names, because its a functional programming language. Nope. Scheme and most lisps AFAICT allow such names because of lisp's syntax, period. Scheme being (more or less) a functional language is mostly unrelated. FWIW, there are pure functional languages that use an infix operator syntax just like Python (and FWIW, Python itselfs uses functions to implement operators) and don't accept dashes in identifiers for the same reasons as Python : parsing ambiguity. (snip) From cokofreedom at gmail.com Wed Jun 4 07:50:47 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 4 Jun 2008 04:50:47 -0700 (PDT) Subject: defaultdict.fromkeys returns a surprising defaultdict References: <5cf9282c-73f3-4df6-9cff-f0cca717e91e@w34g2000prm.googlegroups.com> Message-ID: <77ac5bcf-08b2-41fc-b307-19013131b432@e53g2000hsa.googlegroups.com> > > No need. The patch would be rejected. It would break existing code > that uses default.fromkeys() as designed and documented. > Perhaps that could be useful, so that future questions or posts on the matter could instantly be directed to the rejected patch? From pavlovevidence at gmail.com Wed Jun 4 06:57:50 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 4 Jun 2008 03:57:50 -0700 (PDT) Subject: Best way to modify code without breaking stuff. References: Message-ID: <56b4e4ef-0046-46ad-bda9-ef1629f41d41@s50g2000hsb.googlegroups.com> On Jun 4, 3:25 am, Jesse Aldridge wrote: > I've got a module that I use regularly. I want to make some extensive > changes to this module but I want all of the programs that depend on > the module to keep working while I'm making my changes. What's the > best way to accomplish this? If I'm understanding you correctly: you want to load the old module when running code normally, but want to use a new module when developing, but is has to have the same name? Here's what you could do: 1. Rename "whatever.py" to "oldwhatever.py". 2. Copy "oldwhatever.py" to "newwhatever.py", and make your extensive changes there. 3. Create a new "whatever.py" with code that imports all the symbols from the old or new module depending on which module you want to use. For instance, you could use an environment variable to choose which one: if os.environ.get("USENEWMODULE") == "yes": from newwhatever import * else: from oldwhatever import * Or, you could set a flag in some sort of configuration module and check that: import config if config.use_new_module: from newwhatever import * else from oldwhatever import * Carl Banks From markjturner at gmail.com Thu Jun 12 10:15:35 2008 From: markjturner at gmail.com (Mark) Date: Thu, 12 Jun 2008 07:15:35 -0700 (PDT) Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <6bcokhF3b2mo7U1@mid.uni-berlin.de> Message-ID: On Jun 12, 3:02?pm, "Diez B. Roggisch" wrote: > Mark wrote: > > Hi all, > > > I have a scenario where I have a list like this: > > > User ? ? ? ? ? ?Score > > 1 ? ? ? ? ? ? ? ? 0 > > 1 ? ? ? ? ? ? ? ? 1 > > 1 ? ? ? ? ? ? ? ? 5 > > 2 ? ? ? ? ? ? ? ? 3 > > 2 ? ? ? ? ? ? ? ? 1 > > 3 ? ? ? ? ? ? ? ? 2 > > 4 ? ? ? ? ? ? ? ? 3 > > 4 ? ? ? ? ? ? ? ? 3 > > 4 ? ? ? ? ? ? ? ? 2 > > > And I need to add up the score for each user to get something like > > this: > > > User ? ? ? ? ? ?Score > > 1 ? ? ? ? ? ? ? ? 6 > > 2 ? ? ? ? ? ? ? ? 4 > > 3 ? ? ? ? ? ? ? ? 2 > > 4 ? ? ? ? ? ? ? ? 8 > > > Is this possible? If so, how can I do it? I've tried looping through > > the arrays and not had much luck so far. > > > Any help much appreciated, > > Show us your efforts in code so far. Especially what the actual data looks > like. Then we can suggest a solution. > > Diez Hi Diez, thanks for the quick reply. To be honest I'm relatively new to Python, so I don't know too much about how all the loop constructs work and how they differ to other languages. I'm building an app in Django and this data is coming out of a database and it looks like what I put up there! This was my (failed) attempt: predictions = Prediction.objects.all() scores = [] for prediction in predictions: i = [prediction.predictor.id, 0] if prediction.predictionscore: i[1] += int(prediction.predictionscore) scores.append(i) I did have another loop in there (I'm fairly sure I need one) but that didn't work either. I don't imagine that snippet is very helpful, sorry! Any tips would be gratefully recieved! Thanks, Mark From cokofreedom at gmail.com Wed Jun 11 03:44:21 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 11 Jun 2008 00:44:21 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <4847d39d$0$7614$426a74cc@news.free.fr> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> <484cf5f6$0$15495$426a74cc@news.free.fr> <127975a3-b3d9-4799-9673-b292ec8d37e3@x19g2000prg.googlegroups.com> <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> <484e3526$0$30894$426a74cc@news.free.fr> <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> <783c55ec-a294-4600-91d9-4a0d78632c49@t12g2000prg.googlegroups.com> <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> Message-ID: On Jun 11, 8:11 am, "Russ P." wrote: > On Jun 10, 11:58 am, Jonathan Gardner > > > Who cares what the type of an object is? Only the machine. Being able > > to tell, in advance, what the type of a variable is is a premature > > optimization. Tools like psyco prove that computers (really, > > programmers) nowadays are smart enough to figure things out the right > > way without any hints from the developer. Static typing is no longer > > necessary in today's world. > > You couldn't be more wrong. Even Guido recognizes the potential value > of static typing, which is why he is easing it into Python as on > optional feature. He recognizes, correctly, that it can detect errors > earlier and facilitate more efficient execution. But there's another, > more significant potential benefit for safety-critical and mission- > critical applications: static typing facilitates advanced static > analysis of software. Can you provide me with any example of Guide wanting static typing to be optional? I haven't. Any why is it you keep going so abstract in this discussion. > > You may be right to an extent for small or medium-sized non-critical > projects, but you are certainly not right in general. I read something > a while back about the flight software for the Boeing 777. I think it > was something like 3,000,000 lines of Ada code. Normally, for a > project of that magnitude the final integration would be expected to > take something like three months. However, the precise interface specs > and encapsulation methods in Ada allowed the integration to be > completed in just three days. > Well, that isn't just because they used encapsulation, the likelihood is well thoughtout planning, constant system testing (that DOES require accessing of those more private methods to ensure there are no problems throughout), and re-testing. Again since I'm not sure how much I trust you and your statistics anymore, have you a link to anything discussing this? > > I realize that Python is not designed for such large projects, but > don't you think certain general principles can be learned anyway? > Perhaps the benefits of interface specs and encapsulation are not as > obvious for smaller projects, but certainly they are not zero. Python is designed to be an efficient high level language for writing clear readable code at any level. Considering the amount of use it gets from Google, and the scope and size of many of their projects, I find it foolish to say it is not designed for large projects. However I do not myself have an example of a large python project, because I don't program python at work. I think the issue here is your want to have python perform exactly like OO built languages such as Java, but it isn't Java, and that, is a good thing. From hongfeng13 at gmail.com Fri Jun 6 14:16:05 2008 From: hongfeng13 at gmail.com (hongfeng13 at gmail.com) Date: Fri, 6 Jun 2008 11:16:05 -0700 (PDT) Subject: My company provide most popular of the shoes model, bag, clothes, Bikini swimwear, sunglasses and watch of etc.. Message-ID: hello ! ! !welcome to visit our website http://www.nikeadishoes.com Our main products : shoes Hoodies T-Shirt Jeans Jacket bags Electronic and so on we can supply many popular shoes model,bag,clothes ,bikini,sunglass and watch and so on.?We can give you products with good quality and reasonable price! We are looking forward to do business with you. Do not hesitate and contact with us! MAILER-shoesec at yahoo.com.cn products 100% authentic MSN: shoes-ec at hotmail.com From felciano at gmail.com Tue Jun 24 18:39:14 2008 From: felciano at gmail.com (felciano) Date: Tue, 24 Jun 2008 15:39:14 -0700 (PDT) Subject: Python libraries for log mining and event abstraction? (possibly OT) Message-ID: <0ee3a027-c374-4117-b164-f2ca0f0fa664@i36g2000prf.googlegroups.com> Hi -- I am trying to do some event abstraction to mine a set of HTTP logs. We have a pretty clean stateless architecture with user IDs that allows us to understand what is retrieved on each session, and should allow us to detect the higher-order user activity from the logs. Ideally I'd love a python toolkit that has abstracted this out into a basic set of API calls or even a query language. An simple example is: find all instances of a search request, followed by a 2+ search requests with additional words in the search string, and group these into a higher-order "Iterative Search Refinement" event (i.e. the user got too many search results to start with, and is adding additional words to narrow down the results). So what I need is the ability to select temporally-related events out of the event stream (e.g. find searches by the same user within 10 second of each other), further filter based on additional criteria across these event (e.g. select only search events where there are additional search criteria relative to the previous search), and a way to annotate, roll- up or otherwise group matching patterns into a higher-level event. Some of these patterns may require non-trivial criteria / logic not supported by COTS log analytics, which is why I'm trying a toolkit approach that allows customization. I've been hunting around Google and the usual open source sites for something like this and haven't found anything (in python or otherwise). This is surprising to me, as I would think many people would benefit from something like this, so maybe I'm just describing the problem wrong or using the wrong keywords. I'm posting this to this group because it feels somewhat AI-ish (temporal event abstraction, etc) and that therefore pythonistas may have experience with (there seems to be a reasonably high correlation there). Further, if I can't find anything I'm going to have to build it myself, and it will be in python, so any pointers on elegant design patterns for how to do this using pythonic functional programming would be appreciated. Barring anything else I will start from itertools and work from there. That said, I'm hoping to use an existing library rather than re-invent the wheel. Any suggestions on where to look for something like this? Thanks! Ramon From dullrich at sprynet.com Mon Jun 30 15:51:34 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Mon, 30 Jun 2008 14:51:34 -0500 Subject: complex numbers should respect the "I" representation References: <6c674bf8-f16b-40f1-81ef-72c009c08465@w1g2000prd.googlegroups.com> Message-ID: In article <6c674bf8-f16b-40f1-81ef-72c009c08465 at w1g2000prd.googlegroups.com>, "narutocanada at gmail.com" wrote: > hi > > I think complex numbers should respect the "i" or "I" representation, > instead of "j". > No reason being cute and using a different character instead of the > traditional representation? At least have the decency of supporting > the orginal representation? > Programmers use j as frequently as i as indexing variable, I see no > reason choosing "j" over "i". Have some respect for majority's rules. Yeah, I tried Python once, found it used "j" this way and decided that Perl made a lot more sense. > This is childish. erm, yes it is, for various values of "this"... -- David C. Ullrich From jeff at jmcneil.net Sun Jun 29 12:56:33 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Sun, 29 Jun 2008 09:56:33 -0700 (PDT) Subject: using urllib2 References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> <25d97d35-6d28-43ef-9e54-d8ae7a03bc8f@b1g2000hsg.googlegroups.com> Message-ID: <27fbd1c7-6735-4fb0-9758-726b2fd8b86e@m3g2000hsc.googlegroups.com> On Jun 29, 12:50?pm, Alexnb wrote: > No I figured it out. I guess I never knew that you aren't supposed to split a > url like "http://www.goo\ > gle.com" But I did and it gave me all those errors. Anyway, I had a > question. On the original code you had this for loop: > > for tabs in soup.findAll('table', {'class': 'luna-Ent'}): > ? ? ? ? yield tabs.findAll('td')[-1].contents[-1].string > > I hate to be a pain, but I was looking at the BeautifulSoup docs, and found > the findAll thing. But I want to know why you put "for tabs," also why you > need the "'table', {'class': 'luna-Ent'}):" Like why the curly braces and > whatnot? > > Jeff McNeil-2 wrote: > > > On Jun 27, 10:26?pm, Alexnb wrote: > >> Okay, so I copied your code(and just so you know I am on a mac right now > >> and > >> i am using pydev in eclipse), and I got these errors, any idea what is > >> up? > > >> Traceback (most recent call last): > >> ? File > >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", > >> line 14, in > >> ? ? print list(get_defs("cheese")) > >> ? File > >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", > >> line 9, in get_defs > >> ? ? dictionary.reference.com/search?q=%s' % term)) > >> ? File > >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url lib.py", > >> line 82, in urlopen > >> ? ? return opener.open(url) > >> ? File > >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url lib.py", > >> line 190, in open > >> ? ? return getattr(self, name)(url) > >> ? File > >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url lib.py", > >> line 325, in open_http > >> ? ? h.endheaders() > >> ? File > >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt plib.py", > >> line 856, in endheaders > >> ? ? self._send_output() > >> ? File > >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt plib.py", > >> line 728, in _send_output > >> ? ? self.send(msg) > >> ? File > >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt plib.py", > >> line 695, in send > >> ? ? self.connect() > >> ? File > >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt plib.py", > >> line 663, in connect > >> ? ? socket.SOCK_STREAM): > >> IOError: [Errno socket error] (8, 'nodename nor servname provided, or not > >> known') > > >> Sorry if it is hard to read. > > >> Jeff McNeil-2 wrote: > > >> > Well, what about pulling that data out using Beautiful soup? If you > >> > know the table name and whatnot, try something like this: > > >> > #!/usr/bin/python > > >> > import urllib > >> > from BeautifulSoup import BeautifulSoup > > >> > def get_defs(term): > >> > ? ? soup = BeautifulSoup(urllib.urlopen('http:// > >> > dictionary.reference.com/search?q=%s' % term)) > > >> > ? ? for tabs in soup.findAll('table', {'class': 'luna-Ent'}): > >> > ? ? ? ? yield tabs.findAll('td')[-1].contents[-1].string > > >> > print list(get_defs("frog")) > > >> > jeff at martian:~$ python test.py > >> > [u'any tailless, stout-bodied amphibian of the order Anura, including > >> > the smooth, moist-skinned frog species that live in a damp or > >> > semiaquatic habitat and the warty, drier-skinned toad species that are > >> > mostly terrestrial as adults. ', u' ', u' ', u'a French person or a > >> > person of French descent. ', u'a small holder made of heavy material, > >> > placed in a bowl or vase to hold flower stems in position. ', u'a > >> > recessed panel on one of the larger faces of a brick or the like. ', > >> > u' ', u'to hunt and catch frogs. ', u'French or Frenchlike. ', u'an > >> > ornamental fastening for the front of a coat, consisting of a button > >> > and a loop through which it passes. ', u'a sheath suspended from a > >> > belt and supporting a scabbard. ', u'a device at the intersection of > >> > two tracks to permit the wheels and flanges on one track to cross or > >> > branch from the other. ', u'a triangular mass of elastic, horny > >> > substance in the middle of the sole of the foot of a horse or related > >> > animal. '] > > >> > HTH, > > >> > Jeff > > >> > On Jun 27, 7:28?pm, Alexnb wrote: > >> >> I have read that multiple times. It is hard to understand but it did > >> help > >> >> a > >> >> little. But I found a bit of a work-around for now which is not what I > >> >> ultimately want. However, even when I can get to the page I want lets > >> >> say, > >> >> "Http://dictionary.reference.com/browse/cheese", I look on firebug, > >> and > >> >> extension and see the definition in javascript, > > >> >> > >> >> > >> >> > >> >> > >> >> > > >> >> Jeff McNeil-2 wrote: > > >> >> > the problem being that if I use code like this to get the html of > >> that > > >> >> > page in python: > > >> >> > response = urllib2.urlopen("the webiste....") > >> >> > html = response.read() > >> >> > print html > > >> >> > then, I get a bunch of stuff, but it doesn't show me the code with > >> the > >> >> > table that the definition is in. So I am asking how do I access this > >> >> > javascript. Also, if someone could point me to a better reference > >> than > >> >> the > >> >> > last one, because that really doesn't tell me much, whether it be a > >> >> book > >> >> > or anything. > > >> >> > I stumbled across this a while back: > >> >> >http://www.voidspace.org.uk/python/articles/urllib2.shtml. > >> >> > It covers quite a bit. The urllib2 module is pretty straightforward > >> >> > once you've used it a few times. ?Some of the class naming and > >> whatnot > >> >> > takes a bit of getting used to (I found that to be the most > >> confusing > >> >> > bit). > > >> >> > On Jun 27, 1:41 pm, Alexnb wrote: > >> >> >> Okay, I tried to follow that, and it is kinda hard. But since you > >> >> >> obviously > >> >> >> know what you are doing, where did you learn this? Or where can I > >> >> learn > >> >> >> this? > > >> >> >> Maric Michaud wrote: > > >> >> >> > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit : > >> >> >> >> I have never used the urllib or the urllib2. I really have > >> looked > >> >> >> online > >> >> >> >> for help on this issue, and mailing lists, but I can't figure > >> out > >> >> my > >> >> >> >> problem because people haven't been helping me, which is why I > >> am > >> >> >> here! > >> >> >> >> :]. > >> >> >> >> Okay, so basically I want to be able to submit a word to > >> >> >> dictionary.com > >> >> >> >> and > >> >> >> >> then get the definitions. However, to start off learning > >> urllib2, I > >> >> >> just > >> >> >> >> want to do a simple google search. Before you get mad, what I > >> have > >> >> >> found > >> >> >> >> on > >> >> >> >> urllib2 hasn't helped me. Anyway, How would you go about doing > >> >> this. > >> >> >> No, > >> >> >> >> I > >> >> >> >> did not post the html, but I mean if you want, right click on > >> your > >> >> >> >> browser > >> >> >> >> and hit view source of the google homepage. Basically what I > >> want > >> >> to > >> >> >> know > >> >> >> >> is how to submit the values(the search term) and then search for > >> >> that > >> >> >> >> value. Heres what I know: > > >> >> >> >> import urllib2 > >> >> >> >> response = urllib2.urlopen("http://www.google.com/") > >> >> >> >> html = response.read() > >> >> >> >> print html > > >> >> >> >> Now I know that all this does is print the source, but thats > >> about > >> >> all > >> >> >> I > >> >> >> >> know. I know it may be a lot to ask to have someone show/help > >> me, > >> >> but > >> >> >> I > >> >> >> >> really would appreciate it. > > >> >> >> > This example is for google, of course using pygoogle is easier in > >> >> this > >> >> >> > case, > >> >> >> > but this is a valid example for the general case : > > >> >> >> >>>>[207]: import urllib, urllib2 > > >> >> >> > You need to trick the server with an imaginary User-Agent. > > >> >> >> >>>>[208]: def google_search(terms) : > >> >> >> > ? ? return > >> >> >> urllib2.urlopen(urllib2.Request("http://www.google.com/search?" > >> >> >> > + > >> >> >> > urllib.urlencode({'hl':'fr', 'q':terms}), > >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? > >> >> ?headers={'User-Agent':'MyNav > >> >> >> > 1.0 > >> >> >> > (compatible; MSIE 6.0; Linux'}) > >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ).read() > >> >> >> > ? ?.....: > > >> >> >> >>>>[212]: res = google_search("python & co") > > >> >> >> > Now you got the whole html response, you'll have to parse it to > >> >> recover > >> >> >> > datas, > >> >> >> > a quick & dirty try on google response page : > > >> >> >> >>>>[213]: import re > > >> >> >> >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

>> >> >> class=r>.*?

', > >> >> >> > res) ] > >> >> >> > ...[229]: > >> >> >> > ['Python Gallery', > >> >> >> > ?'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des > >> Monty > >> >> >> ...', > >> >> >> > ?'Re: os x, panther, python & co: msg#00041', > >> >> >> > ?'Re: os x, panther, python & co: msg#00040', > >> >> >> > ?'Cardiff Web Site Design, Professional web site design services > >> >> ...', > >> >> >> > ?'Python Properties', > >> >> >> > ?'Frees < Programs < Python < Bin-Co', > >> >> >> > ?'Torb: an interface between Tcl and CORBA', > >> >> >> > ?'Royal Python Morphs', > >> >> >> > ?'Python & Co'] > > >> >> >> > -- > >> >> >> > _____________ > > >> >> >> > Maric Michaud > >> >> >> > -- > >> >> >> >http://mail.python.org/mailman/listinfo/python-list > > >> >> >> -- > >> >> >> View this message in > > >> context:http://www.nabble.com/using-urllib2-tp18150669p18160312.html > >> >> >> Sent from the Python - python-list mailing list archive at > >> Nabble.com. > > >> >> > -- > >> >> >http://mail.python.org/mailman/listinfo/python-list > > >> >> -- > >> >> View this message in > >> >> context:http://www.nabble.com/using-urllib2-tp18150669p18165634.html > >> >> Sent from the Python - python-list mailing list archive at Nabble.com. > > >> > -- > >> >http://mail.python.org/mailman/listinfo/python-list > > >> -- > >> View this message in... > > read more ? The definitions were embedded in tables with a 'luna-Ent' class. I pulled all of the tables with that class out, and then returned the string value of td containing the actual definition. The findAll method takes an optional dictionary, thus the {}. From dullrich at sprynet.com Thu Jun 12 10:11:05 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 12 Jun 2008 09:11:05 -0500 Subject: re quiz References: Message-ID: <6gb254dembnlj6h742g5jj2ku1apddt4sn@4ax.com> On Thu, 12 Jun 2008 05:12:55 -0700 (PDT), John Machin wrote: >On Jun 12, 8:57 pm, David C. Ullrich wrote: >> True or False? (no fair looking it up) >> >> (*) If repl is a string then re.sub(pattern, repl, s) >> returns s with non-overlapping occurences of pattern >> replaced by repl. >> >> I assumed it was true - spent a few hours trying to >> figure out what was going on with a certain re.sub, >> then noticed that (*) is false: >> > >Well, the docs do say "Return the string obtained by replacing the >leftmost non-overlapping occurrences of pattern in string by the >replacement repl." That's the _first sentence_, yes. I _quoted_ another sentence (from an old version, istr it phrased slightly differently in recent versions) in my post. > -- care to tell us what "a certain re.sub" is, and >false in what way? Read the OP. David C. Ullrich From gherron at islandtraining.com Fri Jun 27 11:38:50 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 27 Jun 2008 08:38:50 -0700 Subject: Use of the "is" statement In-Reply-To: References: Message-ID: <4865098A.3070502@islandtraining.com> Joel Corbin wrote: > Hello, > > I'm trying to clarify what exactly the behaviour of the is statement > is (or should be). Naturally, this has been nearly impossible to > google for, even using quotations... It is my impression that the is > statement should be equivalent to "==", at least on some level. > However, this equivalency seems to be inconsistent for reasons I can't > decipher. Out of the following 3 cases, only 2 return True. What is > the difference (and why is there one) in the third case? Comparing two numbers or strings with "is" is equivalent to asking if the two numbers or strings are stored in the same location in memory. But since you have no control where values are stored when you bind them to a name, this is completely pointless. In a=15 b=15 it is implementation dependent whether the value 15 is stored once and refereed to twice, or stored twice. In short: *never* use "is". (A longer answer can find some uses cases for "is", but stick with the short answer for now.) Gary Herron > > Python 2.5.2 > >>> 'string' is 'string' #simple assignment works > True > >>> s = 'string' > >>> s is 'string' > True > >>> def make_string(): return 'test' #but function behaviour varies > >>> def arg_to_str(arg): return str(arg) > >>> make_string() is 'test' > True > >>> arg_to_string('works') is 'works' # this works > True > >>> arg_to_string(15) is '15' # but this doesnt > >>> arg_to_string(15) is arg_to_string(15) # nor this! > >>> arg_to_string(15) > '15' > >>> arg_to_string(15) == arg_to_string(15) > True > > This became a problem when I was using file.tell() and again when > using a custom function. If I am using is in the wrong context, what > is the right one? > Joel > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From larry.bates at websafe.com` Wed Jun 25 23:30:35 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 25 Jun 2008 22:30:35 -0500 Subject: Working with the Windows Registry In-Reply-To: <49beca2a-9d6c-40a2-a7c3-bf1cf376df0a@l28g2000prd.googlegroups.com> References: <49beca2a-9d6c-40a2-a7c3-bf1cf376df0a@l28g2000prd.googlegroups.com> Message-ID: teh_sAbEr wrote: > Hi everybody. I'm trying to write a script that'll change desktop > wallpaper every time its run. Heres what I've gotten so far: > > #random wallpaper changer! > import _winreg > from os import walk > from os.path import exists > from random import randint > > #first grab a registry handle. > handle = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,'Control Panel > \Desktop',_winreg.KEY_SET_VALUE) > > def GenerateListOfWallpapers(): > targetDir = 'C:\Documents and Settings\Enrico Jr\My Documents\Jr > \'s Wallpapers' > fileNames = [] > filePaths = [] > if exists(targetDir): > #proceed to make the list of files > for x,y,z in walk(targetDir): > for name in z: > fileNames.append(name) > for item in fileNames: > filePaths.append(targetDir + '\\' + item) > return filePaths > > def RandomlySelectWallpaper(filePaths): > index = randint(0,len(filePaths)-1) > RandomlySelectedWallpaper = filePaths[index] > return RandomlySelectedWallpaper #it should be a string... > > #now to edit the wallpaper registry key > newWallpaper = RandomlySelectWallpaper(GenerateListOfWallpapers()) > print "Registry Handle Created." > print "Random wallpaper selected." > _winreg.SetValueEx(handle,'ConvertedWallpaper', > 0,_winreg.REG_SZ,newWallpaper) > print "New wallpaper value set." > > The problem is, every time I run it, I get an "Access Denied" error > when it tries to execute > _winreg.SetValueEx(), even though i've opened the key with the > KEY_SET_VALUE mask like it said in the help docs. Could there be > another problem or a better way to do this? Common error. You have to open the key so that it can be written as follows: reg = _winreg.HKEY_CURRENT_USER key = r'Control Panel\Desktop' handle = _winreg.OpenKey(reg, key, 0, _winreg.KEY_WRITE) Note: be careful with backslashes (\) in non-raw strings they will be interpreted as escaped sequences. You were lucky because \D doesn't represent anything escaped. You should either use r's\gg\gg' or use double backslashes 's\\gg\\gg'. -Larry From Lie.1296 at gmail.com Wed Jun 11 09:59:53 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 11 Jun 2008 06:59:53 -0700 (PDT) Subject: Dynamic HTML from Python Script References: <484f151c$0$5009$607ed4bc@cv.net> <484f21aa$1@dnews.tpgi.com.au> <484f24e9$0$5020$607ed4bc@cv.net> <484f2870$1@dnews.tpgi.com.au> <484f3574$0$4998$607ed4bc@cv.net> Message-ID: <5493ff9f-7ed0-41db-9837-94b11f757d3f@j1g2000prb.googlegroups.com> On Jun 11, 9:16?am, asdf wrote: > On Wed, 11 Jun 2008 11:20:48 +1000, Aidan wrote: > > asdf wrote: > >>> Well, there's a few ways you could approach it. > > >>> You could create a cgi program from your script - this is probably the > >>> solution you're looking for. > > >> Output from the script does come up very often. There is a new output > >> every 10 secs and it's possible that the script might be run > >> indefinitely. Basically I want all that output displayed in a web > >> browser > > > Well, in that case you could simply append the new output to a static > > file every 10 seconds, or whenever there is new output. ?That way, you > > just need to refresh the static file in your browser to see updates... > > Given what I understand of your situation, that's how I'd do it. > > The problem with this is that browser would have to be refreshed manually > every 10 seconds. Unless there is a way to set this in the script itself. Surely you don't think you can do that without Javascript don't you? You can't make the browser refresh automatically in the server side, it has to be done in the client side scripting or like Opera browser that have an option to make it refresh a page every few seconds. > > A constantly running CGI app is probably not the best idea, given > > timeouts and other such constraints you might run into. > > >>> You could have the script run periodically and create a static html > >>> file in the webroot... this would be acceptable, maybe preferable, if > >>> the output from your script doesn't change frequently. > > From musiccomposition at gmail.com Wed Jun 25 22:50:10 2008 From: musiccomposition at gmail.com (Benjamin) Date: Wed, 25 Jun 2008 19:50:10 -0700 (PDT) Subject: Problem found in tutorial References: <001001c8d669$36b06860$6401a8c0@28ghz> Message-ID: <440eb224-e49f-47a5-bfc3-45e1820af7ba@k37g2000hsf.googlegroups.com> On Jun 25, 2:09?pm, Terry Reedy wrote: > John W. Hamill wrote: > > C:\__jh\ftp\python\2_5_2\doc\tutorial\node11.html > > When reporting doc bugs, it is a good idea to check the most recent > version. ?The 3.0 version has the same problems (no changes have been > made -- page and graduates are still undefined), so report that too. Changes to the 2.6 docs will be propagated to 3.0, so it's usually not an issue. From mdw at distorted.org.uk Sat Jun 21 10:55:40 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Sat, 21 Jun 2008 14:55:40 +0000 (UTC) Subject: advanced listcomprehenions? References: <717129b5-d92f-4be2-ae6a-037870bfa407@2g2000hsn.googlegroups.com> Message-ID: Terry Reedy wrote: > The lookup table is a constant. If made a tuple, it will be compiled as > a constant (as least in 2.6, maybe 2.5). Force of habit. I tend to work on lists by indexing and/or iterating, and on tuples by destructuring, and choose types based on the kinds of things I'll be doing. But I did intentionally ensure that the tables were constant so that readers could apply the obvious optimization if they wanted. (Also, unnecessarily computing str(i) seemed bad.) > In any case, it could (and to me should) be lifted out of the string > comp. For performance, yes. But doing a modexp is going to kill performance anyway, so I decided to save screen lines. After all, applying even fairly basic number theory to a problem like this isn't really what one might call a readable solution. ;-) -- [mdw] From dullrich at sprynet.com Thu Jun 12 13:50:00 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 12 Jun 2008 12:50:00 -0500 Subject: re quiz References: <6gb254dembnlj6h742g5jj2ku1apddt4sn@4ax.com> Message-ID: In article , Johannes Bauer wrote: > David C. Ullrich schrieb: > > >> -- care to tell us what "a certain re.sub" is, and > >> false in what way? > > > > Read the OP. > > Well, aren't you funny. Maybe you should have referenced the other > thread so one can find the OP? What other thread? OP is sometimes Original Poster and sometimes Original Post. In the original post in this very thread I gave an quote from the docs and an example illustrating the answer to the question I was asked. Ok, I guess it's hard to find the top of the thread. I wanted to replace a certain pattern with r"\remark{Hint}". I didn't understand why that didn't work until I read the bit of the docs that I quoted in my original post: (**) "If repl is a string, any backslash escapes in it are processed. That is, "\n" is converted to a single newline character, "\r" is converted to a linefeed, and so forth." > Regards, > Johannes -- David C. Ullrich From circularfunc at yahoo.se Thu Jun 19 11:32:10 2008 From: circularfunc at yahoo.se (cirfu) Date: Thu, 19 Jun 2008 08:32:10 -0700 (PDT) Subject: Installing Python 3.0 no probs running 2.5 at the same time? Message-ID: <4eb587db-ccd2-4d98-bfc0-abfda4edc4fc@i76g2000hsf.googlegroups.com> Can I install 3.0 without breaking 2.5? Meaning does it overwrite some bindings or something or it just installs 3.0 in a different folder as a completely separate program? From paul.hankin at gmail.com Mon Jun 16 02:17:04 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sun, 15 Jun 2008 23:17:04 -0700 (PDT) Subject: newbie question: for loop within for loop confusion References: Message-ID: <821db59d-c9b6-4aa8-b08a-b8f46d230eb1@p25g2000pri.googlegroups.com> On Jun 16, 2:35?pm, takayuki wrote: > def hasnolet2(avoid): > ? ? ? ? fin = open('animals.txt') > ? ? ? ? for line in fin: > ? ? ? ? ? ? ? ? word = line.strip() > > ? ? ? ? length = len(avoid) > ? ? ? ? x = 0 > ? ? ? ? noprint = 0 > > ? ? ? ? while length -1 >= x: > ? ? ? ? ? ? ? ? if avoid[x] in word: > ? ? ? ? ? ? ? ? ? ? ? ? noprint = noprint + 1 > ? ? ? ? ? ? ? ? x = x + 1 > > ? ? ? ? if noprint == 0: > ? ? ? ? ? ? ? ? print word There seems to be an indendation problem (presumably the code from length = len(avoid) onwards should be inside the loop). But apart from that, we can try to make this more 'pythonic'. First, python has a 'for' statement that's usually better than using while. We use the 'range' function that produces the numbers 0, 1, ... length - 1, and x takes the value of these in turn. Here's the last bit of your code rewritten like this: noprint = 0 for x in range(length): if avoid[x] in word: noprint += 1 if noprint == 0: print word But better, rather than using 'x' as an index, we can loop over letters in avoid directly. I've changed 'noprint' to be a boolean 'should_print' too here. should_print = True for letter in avoid: if letter in word: should_print = False if should_print: print word We can eliminate 'should_print' completely, by using 'break' and 'else'. A break statement in a loop causes the loop to end. If the loop doesn't break, the 'else' code is run when the loop's over. for letter in avoid: if letter in word: break else: print word This is almost the same as your original code, but the 'else' is attached to the 'for' rather that the 'if'! Finally, in Python 2.5 you can write this: if not any(letter in word for letter in avoid): print word I think this is the best solution, as it's readable and short. -- Paul Hankin From giuott at gmail.com Fri Jun 20 04:38:37 2008 From: giuott at gmail.com (Giuseppe Ottaviano) Date: Fri, 20 Jun 2008 01:38:37 -0700 Subject: Named tuples and projection Message-ID: <7C8F26FC-F4DD-4D2F-B7C5-120E05B1DC68@gmail.com> I found the namedtuple very convenient for rapid prototyping code, for functions that have to return a number of results that could grow as the code evolves. They are more elegant than dicts, and I don't have to create a new explicit class. Unfortunately in this situation they lose the convenience of tuple unpacking: changing tuple's parameters would break other functions unpacking the result. One solution, with 3.0 syntax, would be unpacking only the used parameters, using always a *rest a, b, *rest = f() so that if the tuple grows, the code keeps working. However I find this confusing (and not avaliable in python 2.5). I don't know if similar solutions have been proposed, I came up with this one: Add a method "project" that given a string of arguments (in a similar fashion as namedtuple construction) returns a tuple with only that items. I monkeypatched the namedtuple recipe as a proof of concept, replace "return result" with these lines: def _project(self, fields): return tuple(getattr(self, field) for field in fields.split()) def _getitem(self, item): if isinstance(item, str): return self.project(item) return super(result, self).__getitem__(item) result.project = _project result.__getitem__ = _getitem return result This is the result: In [2]: X = namedtuple('X', 'a b c d') In [3]: x = X(1, 2, 3, 4) In [4]: a, c = x.project('a c') In [5]: a, c Out[5]: (1, 3) In [6]: a, d = x['a d'] In [7]: a, d Out[7]: (1, 4) In [8]: x[2] Out[8]: 3 I implemented also __getitem__ just to show another possible syntax (maybe a bit ugly). project may be not a self-evident name, probably something like "select" (for SQL addicts) would be more appropriate. Other possible solutions? Thanks, Giuseppe From xi at gamma.dn.ua Fri Jun 6 08:20:16 2008 From: xi at gamma.dn.ua (Kirill Simonov) Date: Fri, 06 Jun 2008 15:20:16 +0300 Subject: creating yaml without tags using pyyaml In-Reply-To: References: Message-ID: <48492B80.8060608@gamma.dn.ua> Stephen Moore wrote: > I have come to the conclusion that this is the fault of the tags (for > example, !!python/tuple) as getting rid of them gets rid of the > errors. > > So I'm wondering if there is an option to YAML.decode that will create > a yaml document without the tags? Try yaml.safe_dump(). >>> import yaml >>> print yaml.dump(()) !!python/tuple [] >>> print yaml.safe_dump(()) [] Thanks, Kirill From musiccomposition at gmail.com Sat Jun 28 22:40:07 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sat, 28 Jun 2008 19:40:07 -0700 (PDT) Subject: HTML Parsing References: <2760a17a-63f9-4700-b31a-b1b60108a26e@m44g2000hsc.googlegroups.com> Message-ID: <2bc032cf-7469-4e13-a759-57a3a1ed878c@w7g2000hsa.googlegroups.com> On Jun 28, 9:03?pm, disappeare... at gmail.com wrote: > Hi everyone > I am trying to build my own web crawler for an experiement and I don't > know how to access HTTP protocol with python. Look at the httplib module. > > Also, Are there any Opensource Parsing engine for HTML documents > available in Python too? That would be great. From cwitts at gmail.com Tue Jun 17 02:49:08 2008 From: cwitts at gmail.com (Chris) Date: Mon, 16 Jun 2008 23:49:08 -0700 (PDT) Subject: How to catch StopIteration? References: <5f27181e-f558-4760-b6a8-4fb7ef4c5848@a9g2000prl.googlegroups.com> <8ccb6d98-421c-4715-8d9a-837392cb1775@l42g2000hsc.googlegroups.com> Message-ID: <6a2c06fd-932a-4096-a5ed-312e5a9e7bf6@m73g2000hsh.googlegroups.com> On Jun 17, 8:43?am, Chris wrote: > On Jun 17, 5:50?am, ccy56... at gmail.com wrote: > > > > > I'm writing to see calcuration process. > > And so, I can't catch StopIteration... > > > What is mistake? > > > def collatz(n): > > ? r=[] > > ? while n>1: > > ? ? r.append(n) > > ? ? n = 3*n+1 if n%2 else n/2 > > ? ? yield r > > > for i, x in enumerate(collatz(13)): > > ? try: > > ? ? last = x[:i+1] > > ? ? print x[:i+1] > > ? except StopIteration: > > ? ? print last.appnd(1) > > > Output: > > [13] > > [13, 40] > > [13, 40, 20] > > [13, 40, 20, 10] > > [13, 40, 20, 10, 5] > > [13, 40, 20, 10, 5, 16] > > [13, 40, 20, 10, 5, 16, 8] > > [13, 40, 20, 10, 5, 16, 8, 4] > > [13, 40, 20, 10, 5, 16, 8, 4, 2] > > last.appnd(1) <= [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] ?# i want this > > list > > def collatz(n): > ? r=[] > ? while n>1: > ? ? r.append(n) > ? ? n = 3*n+1 if n%2 else n/2 > ? ? yield r > > i = 1 > while 1: > ? ? try: > ? ? ? ? last = x[:i] > ? ? ? ? print x[:i] > ? ? ? ? i += 1 > ? ? except StopIteration > ? ? ? ? last.append(1) > ? ? ? ? break > > You will have to control the for loop yourself otherwise the > StopIteration is handled for you. forgot to put x = collatz(13) before the while loop starts and a x.next() inside the while, but hopefully you get the point :p From torriem at gmail.com Tue Jun 3 20:37:15 2008 From: torriem at gmail.com (Michael Torrie) Date: Tue, 03 Jun 2008 18:37:15 -0600 Subject: "Faster" I/O in a script In-Reply-To: References: Message-ID: <4845E3BB.3080901@gmail.com> kalakouentin wrote: > I use python in order to analyze my data which are in a text form. The > script is fairly simple. It reads a line form the input file, computes > what it must compute and then write it it to a buffer/list. When the > whole reading file is processed (essential all lines) then the > algorithms goes ahead and writes them one by one on the output file. > It works fine. But because of the continuous I/O it takes a lot of > time to execute. Sounds like perhaps generators would help. They let you process your data a chunk at a time, rather than reading them all in at once. For some powerful tips and examples, see: http://www.dabeaz.com/generators/Generators.pdf To me this principle was very enlightening. Especially where you can then apply optimizations to your data processing flow by altering when the generators take place. Much as how pushing selects down the tree in relational algebra reduces runtime dramatically, using generators to filter and process data can be made very fast. From gagsl-py2 at yahoo.com.ar Wed Jun 18 18:55:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Jun 2008 19:55:16 -0300 Subject: advanced listcomprehenions? References: <717129b5-d92f-4be2-ae6a-037870bfa407@2g2000hsn.googlegroups.com> Message-ID: En Wed, 18 Jun 2008 18:42:00 -0300, cirfu escribi?: > I am wondering if it is possible to write advanced listcomprehensions. > > For example: > """Write a program that prints the numbers from 1 to 100. But for > multiples of three print "Fizz" instead of the number and for the > multiples of five print "Buzz". For numbers which are multiples of > both three and five print "FizzBuzz".""" > Obv it doesnt have to be a list according tot hat definition but > suppose i want to generate that list. Go to http://groups.google.com/group/comp.lang.python and search for "fizz buzz"... > or to generate a lisrt but not by listcomprehsnion: > map(lambda x: (not x%3 and not x%5 and "FizzBuzz") or (not x%3 and > "Fizz") > or (not x%5 and "Buzz") or x, xrange(1,101)) You can translate that into a list comprehension - in general, map(f, items) is the same as [f(x) for x in items]. We have then: [(not x%3 and not x%5 and "FizzBuzz") or (not x%3 and "Fizz") or (not x%5 and "Buzz") or x for x in xrange(1,101)] Quite unreadable IMHO. Just to add another variant to the zillion ones already posted: def fb(x): mult3 = x%3 == 0 mult5 = x%5 == 0 if mult3 and mult5: return "FizzBuzz" elif mult3: return "Fizz" elif mult5: return "Buzz" return str(x) [fb(x) for x in range(1,101)] -- Gabriel Genellina From ricaraoz at gmail.com Mon Jun 9 10:06:43 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 09 Jun 2008 11:06:43 -0300 Subject: Do this as a list comprehension? In-Reply-To: References: <4848b213$0$25711$607ed4bc@cv.net> Message-ID: <484D38F3.5080106@bigfoot.com> Mensanator wrote: > On Jun 6, 1:40 pm, The Pythonista wrote: >> On Thu, 05 Jun 2008 23:42:07 -0400, John Salerno wrote: >>> Is it possible to write a list comprehension for this so as to produce a >>> list of two-item tuples? >>> base_scores = range(8, 19) >>> score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] print zip(base_scores, >>> score_costs) >> score_costs = [(base_scores[i], score_costs[i]) for i in range (len >> (base_scores))] > > What happens if your iterables aren't the same length? > >> But, I'd rather just use zip. :-) > > And with zip() you won't get an error, but it won't be correct, > either. > Wouldn't it be nice to have leftZip(), rightZip(), and fullZip() for when the lists have different lengths? The final tuples for a leftZip could be in the form (value, ) and for right zip (, value) (though I think this last tuple is not allowed in python's syntax, we might define a "Null" or "Empty" name to act as a place holder in the resulting tuples). From google at mrabarnett.plus.com Tue Jun 3 10:40:38 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 3 Jun 2008 07:40:38 -0700 (PDT) Subject: ctypes, function pointers and a lot of trouble References: Message-ID: <832f57f4-7d26-44a5-8abe-567165cc532f@f36g2000hsa.googlegroups.com> On Jun 3, 11:22 am, Matt wrote: > Hello! > > ouch, I should have seen that c_char... :S Well, I guess I just prove > that it's useless to go to work and do some programming while having a > headache like I had yesterday... > > okay well, back to topic: > > The DLL function seems to accept my parameters now, but unfortunately > Python terminates after the DLL gets the result from the "open" callback > function (at least its printouts are the last I get before it > terminates). So without any kind of error message it's getting more > difficult now. > > Well, since I didn't invest much time into my callback functions I > suspect the error must be somewhere in there. > > This is my code: > > ------------------------------CODE----------------------------------------- > > class MemStreamData(Structure): > _fields_ = [("mode", c_byte), > ("lPos", c_uint), > ("dwVisibleSize", c_uint), > ("dwBufferSize", c_uint), > ("cpBuffer", POINTER(c_char))] > > class FilStreamData (Structure): > _fields_ = [("szFileName", c_char * 30), > ("hFile", c_uint)] > > def pystreamopen (contextH, mode, pErr=0): > print "opening..." > print contextH > print mode > print pErr > return 0 > > cstreamopen = CFUNCTYPE(c_uint, c_ushort, c_uint) > > def pystreamclose (contextH, pErr): > print "closing..." > return 0 > > cstreamclose = CFUNCTYPE(c_uint, c_uint) > > def pystreamread (contextH, pBuf, pBufsize, pErr): > print "reading..." > return 0 > > cstreamread = CFUNCTYPE(c_uint, c_void_p, c_uint, c_uint) > > def pystreamtell (contextH, pErr): > print "telling..." > return 0 > > cstreamtell = CFUNCTYPE(c_uint, c_uint) > > def pystreamseek (contextH, origin, offset, pErr): > print "seeking..." > return 0 > > cstreamseek = CFUNCTYPE(c_uint, c_uint, c_uint, c_uint) > > def pystreamwrite (contextH, origin, offset, pErr): > print "writing..." > return 0 > > cstreamwrite = CFUNCTYPE(c_uint, c_void_p, c_uint, c_uint) > > class cdStream(Structure): > _fields_ = [("contextH", POINTER(MemStreamData)), > ("open", cstreamopen), > ("close", cstreamclose), > ("read", cstreamread), > ("write", cstreamwrite), > ("seek", cstreamseek), > ("tell", cstreamtell)] > > -----------------------------/CODE----------------------------------------- > > This is the way I create the vars: > > ------------------------------CODE----------------------------------------- > > databuf = create_string_buffer(100000) > cbuffer=MemStreamData() > cbuffer.mode = c_byte(0) > cbuffer.lPos = c_uint(0) > cbuffer.dwVisibleSize = 100000 > cbuffer.dwBufferSize = 100000 > cbuffer.cpBuffer = databuf > > stream = cdStream() > stream.contextH = POINTER(MemStreamData)(cbuffer) > stream.open = cstreamopen(pystreamopen) > stream.close = cstreamclose(pystreamclose) > stream.write = cstreamwrite(pystreamwrite) > stream.tell = cstreamtell(pystreamtell) > stream.read = cstreamread(pystreamread) > > data = cdStgMedium() > data.Type = c_uint(1) # 0...FilStream 1...MemStream > data.u.pStream = POINTER(cdStream)(stream) > > errorcode = cdsdk.CDGetReleasedData(devicehandle, byref(cbfunct), > c_uint(0), c_uint(0), byref(datainfo), POINTER(cdStgMedium)(data)) > > ------------------------------/CODE----------------------------------------- > > Now I have two problems: > > 1st: since contextH is not a c_uint (and pErr is a pointer) as I thought > earlier, I tried to change my definition of the open function to: > > cstreamopen = CFUNCTYPE(POINTER(MemStreamData), c_ushort, POINTER(c_uint)) > > unfortunately that throws an error when I try to: > > stream.open = cstreamopen(pystreamopen) > > 2nd: as may saw, I defined "def pystreamopen (contextH, mode, pErr=0)". > The pErr variable should be a pointer to a c_uint where my function can > tell the DLL that opening the stream went well (or give some errorcode). > > When I do not define pErr=0 and simply say pErr, I get the following error: > > Traceback (most recent call last): > File "\loewis\25\python\Modules\_ctypes\callbacks.c", line 206, in > 'calling callback function' > TypeError: pystreamopen() takes exactly 3 arguments (2 given) > > At first I thought okay, maybe there's no pErr and there's some error in > the C-Code, but when I do "def pystreamopen (contextH, mode)" I get the > same Error with: > TypeError: pystreamopen() takes exactly 3 arguments (2 given) > > Any ideas? > > And another question: my callback functions are all defined as void... > in C. That means that there shouldn't be anything returned. I tried this > by using the pass statement, but got an error that returntype int was > expected. Also "return" or "return None" don't work. Why? > > Puh, long mail again... hope you're so kind again and take the time to > help me out. > The docs say CFUNCTYPE(restype, *argtypes), so: cstreamopen = CFUNCTYPE(c_uint, c_ushort, c_uint) is saying that the result type is c_uint, not void. I think you need: cstreamopen = CFUNCTYPE(None, c_uint, c_ushort, c_uint) instead. From johnjsal at NOSPAMgmail.com Fri Jun 27 12:19:19 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 27 Jun 2008 12:19:19 -0400 Subject: what is meaning of "@" in pyhon program. References: <88990b3d-1916-413f-83b9-796aabf43623@l28g2000prd.googlegroups.com> <19aa4978-242b-4732-b072-aa5ff16975b0@27g2000hsf.googlegroups.com> <486502bf$0$6426$426a74cc@news.free.fr> <4bfb891d-7a7b-45bc-b126-1d485c9206ee@m44g2000hsc.googlegroups.com> Message-ID: <48651327$0$3021$c3e8da3@news.astraweb.com> "Damon Getsman" wrote in message news:4bfb891d-7a7b-45bc-b126-1d485c9206ee at m44g2000hsc.googlegroups.com... > Okay, maybe I just didn't understand the websites that were given as > examples as to 'decoration'. I first came across the unusual '@' when > I was browsing through some extreme beginner's information on os.x > method descriptions. I asked some other people about it and they had > no idea what it meant. I don't _THINK_ that the decoration definition > fits, though, because the examples that I saw it in had it prefixing > an if conditional & a for loop. The OP's code sample makes sense for decorators, I think. Can you post an actual sample of what it is you saw? Sounds weird. From sjmachin at lexicon.net Tue Jun 17 06:58:14 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 17 Jun 2008 03:58:14 -0700 (PDT) Subject: go to specific line in text file References: <1xsmb1wlk1554$.gey53bzk6vfd$.dlg@40tude.net> Message-ID: <73f4df26-ef11-4d52-b39a-d4b34cd8d63b@r37g2000prm.googlegroups.com> On Jun 17, 8:10 pm, Patrick David wrote: > Hello NG, > > I am searching for a way to jump to a specific line in a text file, let's > say to line no. 9000. > Is there any method like file.seek() which leads me to a given line instead > of a given byte? If by "jump" you mean without reading the preceding 8999 lines, and by "text file" you mean variable length records without a separate index structure, that method hasn't been implemented yet. AFAIK it hasn't been implemented in any other language either :-) The linecache module may be what you want, depending on how closely your access patterns match those the module was designed for. Cheers, John From tjreedy at udel.edu Wed Jun 4 21:21:24 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 4 Jun 2008 21:21:24 -0400 Subject: Import, site packages, my modules, Windows vs. Linux References: <4993bd3d-22aa-4e0d-a593-38c0f5e2d69a@m44g2000hsc.googlegroups.com> Message-ID: "John Ladasky" wrote in message news:4993bd3d-22aa-4e0d-a593-38c0f5e2d69a at m44g2000hsc.googlegroups.com... | On Windows I found a solution that works, but which may be a kludge. | In the Python "site-packages" folder, I added a sub-folder called "my- | packages". Then I created a text file, "my-packages.pth", containing | the single line, "my-packages." Finally, I moved my common personal | modules into the my-packages folder and deleted all of my clumsy | duplicates. Import statements now work for all of my files on the | Windows box, great! | | I then tried to use this same strategy in Linux, and saw that I don't | automatically have the privileges needed to alter the site-packages | folder. On my Windows box, my default account has Administrator | privileges. If you do the Windows install for all users, all users can add packages to site-packages -- as long as adding the package directory comprises the whole installation process and no registry fiddling is required. From basti.wiesner at gmx.net Fri Jun 27 12:21:26 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Fri, 27 Jun 2008 18:21:26 +0200 Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> Message-ID: John Salerno : > But when you have a templating system that mixes HTML and Python code, how > is this helping to keep things separate? You don't. Normally you embed only the code, that is absolutely necessary, e.g. for iterating over a list. Consider an online shop, that needs to do display a list of articles. Inside the template, you would iterate over a list of and query attributes of "Article" object to render the information as HTML. You would _not_ create a database connection, parse search parameters, find matching articles and create a list of them. That's the job of the controller inside the web app. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From yardennis at gmail.com Fri Jun 27 10:11:37 2008 From: yardennis at gmail.com (yardennis) Date: Fri, 27 Jun 2008 07:11:37 -0700 (PDT) Subject: python interface to Firefox and Thunderbird References: <6c5dab9f-3521-4434-8100-65ad1fe207d0@i36g2000prf.googlegroups.com> Message-ID: <92d84dc8-8c2a-46b5-af71-143b3c6f4085@i18g2000prn.googlegroups.com> On Jun 27, 10:15?am, Larry Bates wrote: > yardennis wrote: > > Hi, > > > I need python moudles that can > > > auto install python 2.5 (web install or a EXE file) > > > auto download and install Firefox3 and Thunderbird 2 > > auto import from IE 6, 7 and OE 5,6 and Outlook > > > read contacts and emails from Thunderbird store > > read Firefox 3 bookmarks, history, cookies and password > > > Can anyone point to a open source solution ? > > > If you know of any freelancer that can help me develop the module > > please let me know. > > > Thanks > > > Dennis > > yardennis at gmail dot com > > The reason you haven't gotten any responses is that you didn't provide adequate > information> > > You didn't say what O/S, so I have to guess that since you said Outlook it must > be windows. > > - Auto download and install FF3/TB2. ?Why? ?Dowload the installers and put them > somewhere (CD/ROM, Flash Drive, etc) , then write a batch file that installs them. > > - Auto download and install Python. ?Same as FF/TB. ?Get setup.exe from > ActiveState Python. > > - Auto import from IE 6, 7 and OE 5,6 and Outlook. ?Auto import what into what? > Is OE Outlook Express? ?What do you want to import and what are you importing into? > > - Read contacts and emails from Thunderbird store. ?Why? ?Wouldn't it be easier > to read them from the POP3/IMAP server? > > - Read Firefox 3 bookmarks, history, cookies and password. ?There are plug-ins > that allow you to export these items (at least bookmarks and passwords). > History/cookies can be easily cleared by the users. ?If you want to monitor > sites visited, there are better ways. > > As you can see we will need to know more about what you are trying to accomplish > to help more. > > -Larry Larry, Thanks for your post. Sorry for not making myself clear. I am building for Windows first then porting to OSX and Linux later What I need is a webinstaller or a exe file then will start downloading Python 2.5, Firefox 3 and Thunderbird 2 and install them into a different dir from the default install. (To prevent version conflict) A python script will : using Firefox3 import feature - import all available settings from Internet Explorer 6, 7 into Firefox 3 (password, cookies, favorites, history) using Thunderbird 2 import feature - import from outlook express 5,6 and Outlook into Thunderbird 2 (emails, pop, smtp, imap settings, password, contacts) I need python modules to read the contacts and emails in Thunderbird 2 to create new contacts and send emails in Thunderbird 2 (just added this) to read the history, cookies, bookmarks, passwords stored in Firefox 3 with the cookie/password get selected web pages with urlib/urlib2 (just added this too) These python modules will be used by a CMS(KPAX) running under web2py. It will be good to use existing open source modules. I am also prepared to engage a freelancer to help me develop the modules Thanks Dennis From bob at mellowood.ca Thu Jun 5 22:19:33 2008 From: bob at mellowood.ca (bvdp) Date: Thu, 05 Jun 2008 19:19:33 -0700 Subject: Newb question: underscore References: <873anrl8p5.fsf@benfinney.id.au> Message-ID: > My guess would be someone has used the common convention of naming the > "get the corresponding localised version of this string from the > application's gettext database" function as '_' for convenience. > Funny that this comes up. I just noticed this in some code I was looking at the other day. A number of statements in the form: print _(something) My question is: Why would anyone decide to obfuscate something as easy to read as Python??? At first I thought that they were making a function out of print (which makes some sense), but I don't think that is the case. I tried (not very hard) to trace back the code to figure out where _() is being assigned, but gave up. Oh, this is in the gdesklets package if anyone is interested. **** Listen to my CD at http://www.mellowood.ca/music/cedars **** Bob van der Poel ** Wynndel, British Columbia, CANADA ** EMAIL: bob at mellowood.ca WWW: http://www.mellowood.ca From upton at virginia.edu Wed Jun 25 13:54:59 2008 From: upton at virginia.edu (Dan Upton) Date: Wed, 25 Jun 2008 13:54:59 -0400 Subject: Porn Addiction In-Reply-To: <0bc1d618-f140-4390-9dd0-4ade923ab054@w1g2000prd.googlegroups.com> References: <0bc1d618-f140-4390-9dd0-4ade923ab054@w1g2000prd.googlegroups.com> Message-ID: <5504f9ac0806251054h3c4c924djd8eedc19d0ed54fb@mail.gmail.com> On Tue, Jun 24, 2008 at 8:24 PM, wrote: > Help, I'm addicted to porn. I've been downloading porn online and > masturbating to it for a few years... Lately it's gotten even worse, I > spend hours and hours surfing and masturbating to it. It's taking over > my life and ruining everything.. I even missed days from work because > of this addiction. > > I'm going to the porn as a way to avoid unwanted feelings or > procrastination and then it just takes over. > > What can I do to end this horrible addiction? > > -Hugh > -- > http://mail.python.org/mailman/listinfo/python-list > for i in xrange(100): print "I will not watch porn" Now practice writing "I will not watch porn" 100 times until you're faster than the Python interpreter. From gagsl-py2 at yahoo.com.ar Tue Jun 3 23:09:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 04 Jun 2008 00:09:41 -0300 Subject: defaultdict.fromkeys returns a surprising defaultdict References: Message-ID: En Tue, 03 Jun 2008 17:11:06 -0300, Matthew Wilson escribi?: > I used defaultdict.fromkeys to make a new defaultdict instance, but I > was surprised by behavior: > > >>> b = defaultdict.fromkeys(['x', 'y'], list) > >>> b > defaultdict(None, {'y': , 'x': }) > >>> b['x'] > > >>> b['z'] > ------------------------------------------------------------ > Traceback (most recent call last): > File "", line 1, in > KeyError: 'z' > > I think that what is really going on is that fromdict makes a regular > dictionary, and then hands it off to the defaultdict class. > > I find this confusing, because now I have a defaultdict that raises a > KeyError. > > Do other people find this intuitive? > > Would it be better if defaultdict.fromkeys raised a > NotImplementedException? > > Or would it be better to redefine how defaultdict.fromkeys works, so > that it first creates the defaultdict, and then goes through the keys? That looks reasonable. It appears there is currently no way to do what you want (apart from using a for loop to set each key) -- Gabriel Genellina From joel.hedlund at gmail.com Tue Jun 17 05:42:06 2008 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Tue, 17 Jun 2008 11:42:06 +0200 Subject: gtk.gdk.Pixbuf.scale() unexpected behavior when offset != 0 Message-ID: Hi! I'm developing a pygtk application where I need to show images zoomed in so that the user can see individual pixels. gtk.gdk.Pixbuf.scale() seemed ideal for this, but if I set offset_x and offset_y to anything other than 0, the resulting image is heavily distorted and the offset is wrong. I've searched the internet for any snippet of code that uses this function with nonzero offset, but even after several hours of searching I've still come up blank. I think this may be a bug, but since it seems so fundamental I think it's way more likely that I've misunderstood something, so I thought I'd pass this by c.l.p first. Any help is greatly appreciated. I wrote a test program to show off this behavior. Please find attached an image of David Hasselhoff with some puppies to help facilitate this demonstration. (feel free to use any image, but who doesn't like Hasselhoff and puppies?) show_hasselhoff.py #------------------------------------------------------- import gtk original = gtk.gdk.pixbuf_new_from_file('hasselhoff.jpeg') w = original.get_width() h = original.get_height() interp = gtk.gdk.INTERP_NEAREST nice = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, w, h) ugly = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, w, h) original.scale(nice, 0, 0, w, h, 0, 0, 2, 2, interp) original.scale(ugly, 0, 0, w, h, w/2, h/2, 2, 2, interp) outtake = original.subpixbuf(w/4, h/4, w/2, w/2) expected = outtake.scale_simple(w, h, interp) w = gtk.Window() hbox = gtk.HBox() hbox.add(gtk.image_new_from_pixbuf(original)) hbox.add(gtk.image_new_from_pixbuf(nice)) hbox.add(gtk.image_new_from_pixbuf(ugly)) hbox.add(gtk.image_new_from_pixbuf(expected)) w.add(hbox) w.show_all() w.connect('destroy', gtk.main_quit) gtk.main() #------------------------------------------------------- When you run this, you should see 4 images in a window. From left to right: original, nice, ugly and expected. nice, ugly and expected are scaled/cropped copies of original, but ugly and expected are offset to show less mullet and more face. expected is what I expected ugly to turn out like judging from the pygtk docs. Things to note about ugly: * The topleft pixel of original has been stretched to the area of offset_x * offset_y. * The first offset_x - 1 top pixels of original have been scaled by a factor 2 horizontally and then stretched vertically to the height of offset_y. * Vice versa for the first offset_y - 1 leftmost pixels of original. * The remaining area of ugly is a scaled version of original(1,1,width/2-1,height/2-1). Things to note about the methods: * This behavior is constant for all interpolation methods. * This behavior is identical in gtk.gdk.Pixbuf.compose(). This can't possibly be how this is supposed to work! Have I misunderstood something, or is this a bug? Cheers! /Joel Hedlund -------------- next part -------------- A non-text attachment was scrubbed... Name: hasselhoff.jpeg Type: image/jpeg Size: 2937 bytes Desc: not available URL: From mu at problemlos.ch Tue Jun 24 10:44:51 2008 From: mu at problemlos.ch (Kurt Mueller) Date: Tue, 24 Jun 2008 16:44:51 +0200 Subject: String split with " and/or ' and/or \ In-Reply-To: References: Message-ID: <48610863.3040108@problemlos.ch> Peter Otten schrieb: > Kurt Mueller wrote: >> How to (super)split a string (literal) containing " and/or ' and/or >> \. >> example: >> >> ' a " b b " c\ c '.supersplit(' ') >> -> >> ['a', ' b b ', 'c c'] > >>>> import shlex >>>> shlex.split(' a " b b " c\ c ') > ['a', ' b b ', 'c c'] Thanks Peter Thanks Paul shlex is what I was looking for. Gr?essli -- Kurt M?ller, mu at problemlos.ch From exarkun at divmod.com Fri Jun 20 12:38:56 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 20 Jun 2008 12:38:56 -0400 Subject: Python "is" behavior In-Reply-To: <02d58c63-f8d8-44a8-ac09-d483a0fa8c0f@v1g2000pra.googlegroups.com> Message-ID: <20080620163856.4714.461927354.divmod.quotient.11239@ohm> On Fri, 20 Jun 2008 09:31:57 -0700 (PDT), michalis.avraam at gmail.com wrote: >I am not certain why this is the case, but... > >>>> a = 256 >>>> b = 256 >>>> a is b >True > >>>> a = 257 >>>> b = 257 >>>> a is b >False > >Can anyone explain this further? Why does it happen? 8-bit integer >differences? http://mail.python.org/pipermail/python-list/2001-November/113994.html Jean-Paul From roopesh.raj at gmail.com Thu Jun 26 01:13:10 2008 From: roopesh.raj at gmail.com (Roopesh) Date: Wed, 25 Jun 2008 22:13:10 -0700 (PDT) Subject: recursion in Class-methods? References: <975b0368-10fe-419c-82ef-50277d4ecd54@l42g2000hsc.googlegroups.com> Message-ID: Wrong: newpath = find_path(self.dictionary, node, end, path) newpaths = find_all_paths(self.dictionary, node, end, path) newpath = find_shortest_path(self.dictionary, node, end, path) Correct; newpath = self.find_path(self.dictionary, node, end, path) newpaths = self.find_all_paths(self.dictionary, node, end, path) newpath = self.find_shortest_path(self.dictionary, node, end, path) Regards Roopesh From miller.paul.w at gmail.com Mon Jun 2 16:58:18 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Mon, 2 Jun 2008 13:58:18 -0700 (PDT) Subject: Writing HTML References: <3760e9d1-d385-4e36-8ca6-e03e48ffdfbf@c58g2000hsc.googlegroups.com> <484447DA.6020708@behnel.de> Message-ID: <2a9027a2-f550-4eec-8f5c-11b723dc8063@c58g2000hsc.googlegroups.com> On Jun 2, 3:19?pm, Stefan Behnel wrote: > Or lxml, for that purpose, which also is a lot nicer for generating XML and > HTML in the first place. > > http://codespeak.net/lxml/ Awesome. lxml looks like exactly what I'm after... and it's in the Ubuntu repos. :-) Thanks! From dfnsonfsduifb at gmx.de Thu Jun 12 11:12:26 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Thu, 12 Jun 2008 17:12:26 +0200 Subject: re quiz In-Reply-To: <6gb254dembnlj6h742g5jj2ku1apddt4sn@4ax.com> References: <6gb254dembnlj6h742g5jj2ku1apddt4sn@4ax.com> Message-ID: David C. Ullrich schrieb: >> -- care to tell us what "a certain re.sub" is, and >> false in what way? > > Read the OP. Well, aren't you funny. Maybe you should have referenced the other thread so one can find the OP? Regards, Johannes -- "Wer etwas kritisiert muss es noch lange nicht selber besser k?nnen. Es reicht zu wissen, da? andere es besser k?nnen und andere es auch besser machen um einen Vergleich zu bringen." - Wolfgang Gerber in de.sci.electronics <47fa8447$0$11545$9b622d9e at news.freenet.de> From timr at probo.com Thu Jun 5 03:10:56 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 05 Jun 2008 07:10:56 GMT Subject: Image Processing (batch) References: <6akqd5F37rofnU1@mid.individual.net> Message-ID: Thomas Guettler wrote: > >I tried PIL for image batch processing. But somehow I don't like it > - Font-Selection: You need to give the name of the font file. > - Drawing on an image needs a different object that pasting and saving. > - The handbook is from Dec. 2006. I have repeatedly seen the attitude in your last point, and I simply do not understand it. What on Earth is wrong with having a product that actually becomes stable? We all complain about Microsoft's feature bloat, rolling out unnecessary new releases of their products year after year with features that no one really needs. But when an open source product FAILS to produce a new release every six weeks, we start seeing posts questioning whether the product is still viable or has become abandonware. Once a product does the job it was designed to do, IT'S DONE. Personally, I think PIL is a great solution for batch processing, but the beauty of the open source world is that the ARE alternatives. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From metallourlante at gmail.com Mon Jun 23 17:55:17 2008 From: metallourlante at gmail.com (Alex) Date: Mon, 23 Jun 2008 14:55:17 -0700 (PDT) Subject: learning unit testing in python References: Message-ID: <28b9286c-1237-4bb7-8b25-6f50382b3b0f@s50g2000hsb.googlegroups.com> On 23 Giu, 21:26, "Josip" wrote: > > Hi all. > > > I'd like learn some basic unit testing with python. > > I red some articles about different testing framework like unittest or > > nose, but I'm a bit confused: what is the best choice? I'm not a > > professional developer (I'm a SEO) but I belive that unit testing is a > > good and pragmatic way to produce working software, so I'd like to > > find something really simple ad straightforward because I don't have > > to manage big programming projects. > > > Thanks in advance, > > > Alex > > Have you checked out doctest?http://docs.python.org/lib/module-doctest.html > It's the best way to add few tests to function or class, you just add > them to docstring. > Unit tests are somewhat demanding as they usualy require creating another > file just for storing them, but are ofcourse more powerful as well. For > example, > unittest module alows you to execute a section of code before or after each > test > to initialize values and clean up. > > Nose module has few extra features, but it can also run test writen for > unittest, > so it's easy to switch if you find standard library module lacking for your > purpose. Tanks a lot. I'll the resources you suggest.. From fd.calabrese at gmail.com Fri Jun 27 09:01:13 2008 From: fd.calabrese at gmail.com (cesco) Date: Fri, 27 Jun 2008 06:01:13 -0700 (PDT) Subject: shorten path to files Message-ID: Hi, I need to retrieve the content of some files which are placed on a network drive so in order to open them I need the full path to the file. Unfortunately some times the path is longer than 256 characters and in Windows such a path is too long with the result that the file is not found (though it is there). Is there any way around this? Thanks Francesco From mdw at distorted.org.uk Sat Jun 21 11:02:47 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Sat, 21 Jun 2008 15:02:47 +0000 (UTC) Subject: optparse functionality missing References: Message-ID: Jeff Keasler wrote: > In a scripting environment, I often want to strip some of the command > line options off the argument list, and then pass the remaining > options to another module that is deeper in the tool chain. The difficulty is that you can't do an accurate parse without knowing which options take arguments. For example, what are the options here? foo -xyzzy -abcdef -ghi -ghi -g -hi Well, `-z', `-f' and `-g' take arguments; the `-g' argument is optional. So the correct options to pass along are -x -y -zzy -a -b -c -d -e -f-ghi -ghi -g -h -i Not so obvious, is it? ;-) -- [mdw] From sjmachin at lexicon.net Fri Jun 27 07:11:50 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 27 Jun 2008 04:11:50 -0700 (PDT) Subject: where is the error? References: <8f8e1bf7-78b0-4292-9d56-396527b9dfb1@z66g2000hsc.googlegroups.com> <15ea1cb1-76a3-4fd3-8e4c-521b9aefcca2@m3g2000hsc.googlegroups.com> Message-ID: On Jun 27, 7:54 pm, la... at caramail.com wrote: > Maybe I didn't explain correctly what i wanted to do. I have a > database and I just want to pick data under a certain criteria. So I > wanted to use a function like nonzero or find or where to find the > line for corresponding to the data following this criteria. So to find > the lines, I used nonzero and it corresponds to the command: > > diff_temp=(logical_and(values[:,5] > -2,values[:,5] < 2)).nonzero() > > so YES it has SOMETHING to do with the question below. > > diff_temp=(array([ 0, 6, 7, 10, 14, 15, 16, 17, 21, 22, > 24, 25, 26, > 27, 31, 32, 33, 36, 37, 38, 39, 40, 41, 42, 46, > 47, > 48, 49, 50, 51, 52, 53, 54, 59, 60, 61, 62, 71, > 72, > 73, 74, 75, 80, 81, 82, 83, 84, 85, 86, 87, 88, > 89, > 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, > 102, > 103, 104, 105, 106, 107, 111, 112, 113, 114, 115, 116]),) > > So now I just want to have the data corresponding to those lines. > Thinking that python was a powerful tool, I thought that it was just > possible to assign those line directly in a matrix. So I used the > command: You will need to explain what you mean by "assign those line directly in a matrix". We are not mind-readers, and neither is Python. > > values_matchup=values_Stumpf[diff_temp_Stumpf,:] > > But it didn't work. I'm sure that there is a specific reason. The specific reason is as Gary explained. What you have done is assign the name diff_temp to some expression. This has absolutely nothing to do with diff_temp_Stumpf which is an utterly different name, and as far as we can tell has no referent as all, hence the error message that you got. You may need one of the following solutions: (1) diff_temp_Stumpf = diff_temp (2) def make_diff_temp_thing(values): return (logical_and(v[:,5] > -2,v[:,5] < 2)).nonzero() # much later ... values_matchup = make_temp_thing(values_Stumpf) but it's rather hard to understand what you want ... > But my > concern was that this command works FINE if I use python on windows xp > but doesn't work if I use python on my linux Ubuntu machine. The usual cause of this kind of phenomenon is experimental error e.g. you didn't execute exactly the same statements (not "commands") on Windows as on Linux. > So I > wondered what was wrong and if there is a easy and simple way to get > directly a new array with the data corresponding to a certain > criteria. It might help if you use less abstract phrases than "corresponding to a certain criteria". Can you relate how you would solve this problem in a computer language other that Python? From JesseAldridge at gmail.com Fri Jun 13 01:00:26 2008 From: JesseAldridge at gmail.com (Jesse Aldridge) Date: Thu, 12 Jun 2008 22:00:26 -0700 (PDT) Subject: dynamic method question Message-ID: So in the code below, I'm binding some events to a text control in wxPython. The way I've been doing it is demonstrated with the Lame_Event_Widget class. I want to factor out the repeating patterns. Cool_Event_Widget is my attempt at this. It pretty much works, but I have a feeling there's a better way of doing this. Also, I couldn't get the Cool_Text_Control to override the on_text method. How would I do that? ------------- import textwrap, new import wx class Lame_Event_Widget: def bind_events(self): self.Bind(wx.EVT_LEFT_DOWN, self.on_left_down) self.Bind(wx.EVT_RIGHT_DOWN, self.on_right_down) self.Bind(wx.EVT_MIDDLE_DOWN, self.on_middle_down) self.Bind(wx.EVT_LEFT_UP, self.on_left_up) self.Bind(wx.EVT_RIGHT_UP, self.on_right_up) self.Bind(wx.EVT_TEXT, self.on_text) def on_left_down(self, e): print "lame normal method: on_left_down" e.Skip() def on_right_down(self, e): print "lame normal method: on_right_down" e.Skip() def on_middle_down(self, e): print "lame normal method: on_middle_down" e.Skip() def on_left_up(self, e): print "lame normal method: on_left_up" e.Skip() def on_right_up(self, e): print "lame normal method: on_right_up" e.Skip() def on_text(self, e): print "lame normal method: on_text" e.Skip() class Cool_Event_Widget: def bind_events(self): method_names = textwrap.dedent( """ on_left_down, on_right_down, on_middle_down, on_left_up, on_right_up, on_middle_up, on_text""" ).replace("\n", "").split(", ") for name in method_names: event_name = name.partition("_")[2] event_name = "wx.EVT_" + event_name.upper() exec("def " + name + "(self, e):\n" + " print 'cool dynamic method: " + name + "'\n" + " e.Skip()\n" "self." + name + " = new.instancemethod(" + name + ", self, self.__class__)\n" "self.Bind(" + event_name + ", self." + name + ")") if __name__ == "__main__": app = wx.App() frame = wx.Frame(None) panel = wx.Panel(frame) sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) class Cool_Text_Control(wx.TextCtrl, Cool_Event_Widget): def __init__(self, parent): wx.TextCtrl.__init__(self, parent) self.bind_events() def on_text(self, e): print "modified text in Cool_Text_Control" class Lame_Text_Control(wx.TextCtrl, Lame_Event_Widget): def __init__(self, parent): wx.TextCtrl.__init__(self, parent) self.bind_events() def on_text(self, e): print "modified text in Lame_Text_Control" sizer.Add(Cool_Text_Control(panel)) sizer.Add(Lame_Text_Control(panel)) frame.Show() app.MainLoop() From sjmachin at lexicon.net Tue Jun 17 19:36:32 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 17 Jun 2008 16:36:32 -0700 (PDT) Subject: Is there a standard binary search with overridable comparisons? References: <09baffe9-691a-47b0-9ba5-1de3231d6cba@8g2000hse.googlegroups.com> Message-ID: <5c4fb9e8-cb1f-4130-bf83-587109b75cbb@g16g2000pri.googlegroups.com> On Jun 18, 6:55 am, markscottwright wrote: > I've got an ordered list of MyClasses that I want to be able to do > binary searches on, but against a tuple. MyClass has valid > __lt__(self, rhs) and __eq__(self, rhs) member functions that work > when rhs is a tuple. > > This works: > l = [MyClass(..), MyClass(..), ...] > l.find((a,b)) > > But this doesn't: > bisect.bisect(l, (a,b)) > > I'm assuming ... Don't. It can be dangerous. > this is because inside bisect, it does 'key < list[x]' > rather than 'list[x] < key', so it's the tuple's __lt__ that is > called, rather than MyClass's tuple. Actually it appears (extremely gory details in Objects/object.c) that it tries all rich comparison possibilities first: tuple < myclass: not defined in tuple type myclass > tuple: not defined in MyClass before falling through to the default (which is based on addresses). > > Is there a way around this? Can I monkeypatch a new __lt__ into the > tuple class? Looks like you need to implement MyClass.__gt__ I suspect someone will say that this section of the manual is trying to tell us this: """ There are no reflected (swapped-argument) versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other's reflection, __le__() and __ge__() are each other's reflection, and __eq__() and __ne__() are their own reflection. """ ... "trying" being the operative word :-) Alternatively, do you really need rich comparison? Consider defining __cmp__ instead of 2 to 6 of the __lt__ etc brigade. HTH, John From fc14301589 at icqmail.com Sun Jun 15 21:55:32 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Mon, 16 Jun 2008 09:55:32 +0800 Subject: Hard to understand 'eval' References: <485381e7_2@news.tm.net.my> <4854e4a7_2@news.tm.net.my> <0eSdnazUa_iJGcjVnZ2dnUVZ_jadnZ2d@earthlink.com> Message-ID: <4855c817_1@news.tm.net.my> On 05:05, 16-6- 2008 Dennis Lee Bieber wrote: >> # any number of digit followed by 0 or 1 (k or m), case insensitive > > I don't do regular expressions... and the comment doesn't help > "digit followed by 0 or 1", when 0/1 ARE digits themselves... That means either none or one letter, of which k or m are allowed. > c is a mutable object; you don't have to return it; the change is > seen by anything holding a reference to the object. C is a dictionary, it might be omitted, but I'm still not sure if will lose its state. > Again, as c is mutable, it doesn't need to be returned. > Apparently Not so apparent, it's doing that, buddy :) > v = v.strip().lower() regexp did a fine check and case insensitive, but I like your idea too. > Biggest flaw, in my mind... You are using ONE identifier to control > TWO meanings... a boolean On/Off control AND an integer size limit > control. That occupy only small variable and as long as python can accept anything not zero, false or none for an _if_ condition, that might be allowable, I think. Then if not zero will mean the log will be *appended* to an existing file and if the value is something that can be converted in decimal value, then this will set the quota for the log file, as well. Here below dbg is the log file and if it isn't None then s a valid file path should work. dbg= sttng['log']; mode= 'w' # normally write, it writes new try: if sttng['append'] > Path.getsize(dbg): mode= 'a' except (OSError, TypeError): # found a boolean or dbg is new file pass So 5 line of code can do me the job smartly, I think ;) -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From Sengly.Heng at gmail.com Sun Jun 15 00:47:16 2008 From: Sengly.Heng at gmail.com (Sengly) Date: Sat, 14 Jun 2008 21:47:16 -0700 (PDT) Subject: Python library for clustering from distance vector References: <101cfef8-ecd2-409a-8701-905780a7862e@q24g2000prf.googlegroups.com> Message-ID: <7e028b55-a28a-4c5a-8be4-ba090b7df074@y22g2000prd.googlegroups.com> On May 19, 2:42?am, jay graves wrote: > On May 17, 11:49 pm, Sengly wrote: > > > I am looking for a python library which can cluster similar objects > > into their respective groups given their similarity score of each two > > of them. I have searched the group but I couldn't find any helpful > > information yet. > > How about google? ?Searching for the terms python and cluster gave > some results for me. > > http://www.google.com/search?q=python+cluster > > > Any suggestion is appreciated. Also, if you know any specific group > > that I should post this message, please also suggest. > > The book, "Programming Collective Intelligence" by Toby Segaran is > great and has examples of clustering algorithms written in Python. > > http://www.amazon.com/Programming-Collective-Intelligence-Building-Ap... > > ... > Jay Graves Thank you very much for your pointers. Regards, Sengly From sjmachin at lexicon.net Thu Jun 26 05:08:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 26 Jun 2008 02:08:34 -0700 (PDT) Subject: struct.pack behavior References: Message-ID: On Jun 26, 12:38?pm, "Steven Clark" wrote: > On Wed, Jun 25, 2008 at 7:03 PM, John Machin wrote: > > On Jun 26, 9:00 am, "Steven Clark" wrote: > >> Can anyone explain to me why > >> struct.pack('HB',1,2) gives 3 bytes, whereas struct.pack('BH',1,2) > >> gives 4 bytes? > > > Alignment -- read the manual. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > If "the manual" is the help files for the struct module, I've read it > several times over. I understand endianness; I don't understand > alignment. Could anyone give a less cryptic / terse answer? google("struct alignment") From walter.php at gmail.com Thu Jun 19 11:59:27 2008 From: walter.php at gmail.com (Walter Cruz) Date: Thu, 19 Jun 2008 12:59:27 -0300 Subject: regex \b behaviour in python Message-ID: <32cabba0806190859g529a82a5ne59d5a71ebdd7b2e@mail.gmail.com> Hi all! Just a simple question about the behaviour of a regex in python. (I discussed this on IRC, and they suggest me to post here). I tried to split the string "walter ' cruz" using \b . In ruby, it returns: irb(main):001:0>"walter ' cruz".split(/\b/) => ["walter", " ' ", "cruz"] and in php: Array ( [0] => [1] => walter [2] => ' [3] => cruz [4] => ) But in python the behaviour of \b is differente from ruby or php. The guys on the IRC pointed me a way to do that: [m.span() for m in re.finditer(r'\b',"walter ' cruz")], but if fact there's some differente as it strips the spaces :) My question is: why \b behaves like this on python? Why it's different from ruby or php (or even perl, I believe)? (For the sake of curiosity, I was trying to solve the http://www.rubyquiz.com/quiz76.html in python. But the question to not to solve the quiz, but understand why python is different) []'s - Walter From meesters at uni-mainz.de Sun Jun 15 12:56:39 2008 From: meesters at uni-mainz.de (Christian Meesters) Date: Sun, 15 Jun 2008 18:56:39 +0200 Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> Message-ID: Peter Otten wrote: > > How did you determine that standard python floats are not good enough? > Everything beyond that is unlikely to be supported by the hardware and > will therefore introduce a speed penalty. > > Did you try gmpy? I would like to add: If Python's precision (or that of additional modules) won't do it for you, look around what other people in the physics community are using. Christian From Lie.1296 at gmail.com Tue Jun 10 12:20:46 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 10 Jun 2008 09:20:46 -0700 (PDT) Subject: Python doesn't understand %userprofile% References: Message-ID: <54435ff9-a10f-4af8-9582-3b3c3cc62da3@u12g2000prd.googlegroups.com> On Jun 10, 11:11?pm, Tim Golden wrote: > bsag... at gmail.com wrote: > > In xp when I try os.path.getmtime("%userprofile/dir/file%") Python > > bites back with "cannot find the path specified" Since my script has > > to run on machines where the username is unspecified I need a fix. > > Well I can see a few problems here. > > First is that putting percent signs around the whole path is > never going to work anyway. You want something like: > > "%USERPROFILE%/dir/file". > > Secondly, the expansion of environment variables like > USERPROFILE is done for you by the shell or the command > prompt. You have to do it for yourself if you're opening your > own files. You want something like: > > import os > print os.path.getmtime (os.path.join (os.environ['USERPROFILE'], "ntuser.ini")) > > But finally, what do you mean "run on machines where the username is > unspecified"? If you mean: where no user is logged in, then you won't > have a (meaningful) userprofile in any case: it might be the Default User > profile; I'm not sure. But is that what you want? I think what he meant is where he doesn't know in advance the name of the user name. > You *can* use the functions in the win32profile module of the pywin32 > packages to find out various things about profiles directories, but things > can get quite complicated if users have roaming profiles and the like. > > TJG From jkugler at bigfoot.com Thu Jun 5 13:24:31 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Thu, 05 Jun 2008 09:24:31 -0800 Subject: Proof that \ is a better line joiner than parenthetical sets References: <4847f59f$0$25187$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > According to the Zen of Python, "explicit is better than implicit", and > the section in the Reference Manual describing the \ line joiner is called > "Explicit line joining" and the section describing parentheticals is > called "Implicit line joining." > > So there! ;) However, according to the Zen of Python, the line before "Explicit is better than implicit." says: "Beautiful is better than ugly." And I think putting parenthesis around a multi-line statement is much prettier. So there! :) j From Lie.1296 at gmail.com Sun Jun 8 06:08:23 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 8 Jun 2008 03:08:23 -0700 (PDT) Subject: Interesting Math Problem References: Message-ID: <7c28dbe0-3ae1-4553-bb7b-21eb9e5e754a@p39g2000prm.googlegroups.com> On Jun 6, 2:25?am, "R?diger Werner" wrote: > "BEES INC" schrieb im Newsbeitragnews:mailman.105.1212653740.1044.python-list at python.org... > ... > > Problem: Star Ratings > > People can rate cheeseburgers on my website with a star rating of 0-5 > stars (whole stars only), 5 being mighty tasty and 0 being disgusting. > I would like to show the average of everyone's ratings of a particular > cheeseburger to the nearest half star. I have already calculated the > average rating as a float (star_sum) and the total number of people > that rated the particular cheeseburger (num_raters). The result should > be stored as a float in a variable named "stars." > My Solution (in Python): > > Well seems this is a typical half even rounding problem. > > See > > http://mail.python.org/pipermail/python-list/2008-April/485889.html > > for a long discussion > > However since your problem looks like a typical homework problem i made my > example > buggy by intention. > > However the result should be correct. > > have fun! > > def myround(x): > ? ? d, m = divmod(x, 2) > ? ? return 2*d + round(m - 1) + 1 > > num = 1.5 > for _i in xrange(30): > ? ? print num, ' -> ', myround(num * 2)/2 > ? ? num -= 0.1 > > >pythonw -u "test18.py" > > 1.5 ?-> ?1.5 > 1.4 ?-> ?1.5 > 1.3 ?-> ?1.5 > 1.2 ?-> ?1.0 > 1.1 ?-> ?1.0 > 1.0 ?-> ?1.0 > 0.9 ?-> ?1.0 > 0.8 ?-> ?1.0 > 0.7 ?-> ?0.5 > 0.6 ?-> ?0.5 > 0.5 ?-> ?0.5 > 0.4 ?-> ?0.5 > 0.3 ?-> ?0.5 > 0.2 ?-> ?0.0 > 0.1 ?-> ?0.0 > -1.94289029309e-016 ?-> ?0.0 ? ?< --- hint for bug > -0.1 ?-> ?0.0 > -0.2 ?-> ?0.0 > -0.3 ?-> ?-0.5 > -0.4 ?-> ?-0.5 > -0.5 ?-> ?-0.5 > -0.6 ?-> ?-0.5 > -0.7 ?-> ?-0.5 > -0.8 ?-> ?-1.0 > -0.9 ?-> ?-1.0 > -1.0 ?-> ?-1.0 > -1.1 ?-> ?-1.0 > -1.2 ?-> ?-1.0 > -1.3 ?-> ?-1.5 > -1.4 ?-> ?-1.5 > > >Exit code: 0 > > to avoid the bug have a look at: > > http://mail.python.org/pipermail/python-list/2008-April/485934.html > > and try this example: > > num = 3 > for _i in xrange(num * 10,-num *10, -1): > ? ? if myround(float(_i)/10) != myround(num): > ? ? ? ? print num, " -> ", myround(num ), " --- ", ?myround(float(_i)/10) > ? ? ? ? print "-----" > ? ? num -= 0.1 Well, I don't think that's the problem. I don't think the OP cares what the rounding method is, it doesn't really matters that much in this case since this function is only used for output and the underlying rating value is untouched. In that case, try this: from __future__ import division rating = round(star_sum / num_raters) whole, half = divmod(rating, 2) From wuwei23 at gmail.com Tue Jun 3 22:19:01 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 3 Jun 2008 19:19:01 -0700 (PDT) Subject: a python phpmyadmin like program References: <6alsqjF38326vU1@mid.uni-berlin.de> <94c63219-85d6-47fa-9c4f-4e2e90293c66@s50g2000hsb.googlegroups.com> Message-ID: <1605c3a3-7af1-429a-97a4-fb9e1b1dee98@j33g2000pri.googlegroups.com> On Jun 4, 12:12 pm, Gandalf wrote: > mmm, for windows... ? Do we have to do this dance every single time you ask a question? Your time (and ours) would be better invested in your learning how to search for things via Google. From alon.benari at gmail.com Sun Jun 29 21:01:09 2008 From: alon.benari at gmail.com (Only-Trouble) Date: Sun, 29 Jun 2008 18:01:09 -0700 (PDT) Subject: How to invoke the Python idle Message-ID: <08484763-05df-49ee-b308-2dd64b7e2379@e39g2000hsf.googlegroups.com> Hi all I am running openSUSE 10.3 I am learning python on my own, it seems like the system has already installed a python IDLE The question is how to invoke it? Thanks Only-Trouble From michael at stroeder.com Fri Jun 20 02:52:55 2008 From: michael at stroeder.com (=?UTF-8?B?TWljaGFlbCBTdHLDtmRlcg==?=) Date: Fri, 20 Jun 2008 08:52:55 +0200 Subject: images on the web In-Reply-To: References: <2e72bd7d-9d33-43ba-8c08-ba3b39368466@z72g2000hsb.googlegroups.com> <485B4F31.6000104@mattnordhoff.com> Message-ID: <7n0si5-6u3.ln1@nb2.stroeder.com> Matt Nordhoff wrote: > Matt Nordhoff wrote: >> You could use data: URIs [1]. >> >> For example, a 43-byte single pixel GIF becomes this URI: >> >> >> >> They don't have universal browser support, but that might not be a >> problem in this case. >> >> As for generating them with Python, I'm not sure... I just used Hixie's >> data: URI kitchen [2] for the above example. >> >> [1] >> [2] > > Oh.. As > shows, the reason I couldn't find a data: URI Python library is because > they're utterly trivial to generate: > > import base64 > import urllib > > raw_data = create_gif() > uri = 'data:image/gif;base64,' + urllib.quote(base64.b64encode(raw_data)) > > (And it's even simpler if you leave out the base64-encoding.) The caveat with URL schema data: is that the amount of data to be transferred is significantly higher than including HTML tag in your HTML source and let the browser fetch the raw binary image data in a separate HTTP request (you also have to serve from your web application). Ciao, Michael. From timothy.grant at gmail.com Tue Jun 10 02:19:47 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Mon, 9 Jun 2008 23:19:47 -0700 Subject: Write to file and see content on screen In-Reply-To: <5b2e915f-9fc5-4acc-b49e-d1b90d00bda0@59g2000hsb.googlegroups.com> References: <5b2e915f-9fc5-4acc-b49e-d1b90d00bda0@59g2000hsb.googlegroups.com> Message-ID: On Mon, Jun 9, 2008 at 6:01 PM, wrote: > Hello all, > > New user to python. I can write to a file, however, I would like to > do both...whatever I do on the screen, I'd like to write it to a file. > > any pointers on where I can find this info. > > thanks, > This code has one really significant problem in that it opens the file each time it is called but it gives a bit of an idea about what you can do. tjg at bastard%) python Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> def myprintandwrite(outstr): ... f = open('out.txt', 'w') ... f.write(outstr) ... print outstr ... >>> myprintandwrite('this is a test') this is a test >>> ^D (tjg at bastard%) cat out.txt this is a test (tjg at bastard%) -- Stand Fast, tjg. -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Mon Jun 30 18:35:14 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 30 Jun 2008 15:35:14 -0700 (PDT) Subject: insertion sorts... References: <06adb999-c7e2-4475-a49f-dbfbe042f4fd@r66g2000hsg.googlegroups.com> <5f0111a3-c1b9-4864-bae3-32fa324c4e5e@j22g2000hsf.googlegroups.com> <841dd5b8-d99d-4a60-ad39-b7c9563fca1d@d1g2000hsg.googlegroups.com> <8ceb6019-6474-485c-8daf-91111c85040c@m36g2000hse.googlegroups.com> Message-ID: On Jun 30, 3:29?pm, python_newbie wrote: > On 25 Haziran, 17:44, MRAB wrote: > > > > > On Jun 25, 11:37?am, "A.T.Hofkamp" wrote: > > > > On 2008-06-25, python_newbie wrote: > > > > > On 24 Haziran, 04:33, Terry Reedy wrote: > > > > Thanks for all answers. At the end i ve only one point. If a decide to > > > > copy list to iterate when will i have to do this ? Before the > > > > iteration ? And then iterate through one list and change value of the > > > > other ? > > > > Before starting the iteration would be a good point.... > > > > I usually do in such cases: > > > > for x in mylist[:]: > > > ? ?... > > > > making a copy just before the for loop starts. > > > > Lately, I have started avoiding in-place modification of lists. Instead, I > > > construct a new list from scratch inside the for-loop, and replace the old list > > > with the newly constructed list afterwards like: > > > > new_list = [] > > > for x in mylist: > > > ? ?.... > > > ? ?new_list.append(x) > > > > mylist = new_list > > > > by appending a different value than the original or by not appending, you can > > > influence the contents of the new list. > > > > I find this solution nicer than in-place modification of an existing list. > > > > Sincerely, > > > Albert > > > And if you were originally doing in-place modification because there > > were also other references to the list then you could just do: > > > mylist[:] = new_list > > Thanks again. I see that you use two different syntax for lists > "mylist = new_list" and "mylist[:] = new_list" these are same i > think ? The difference is that "mylist = new_list" makes mylist refer to the same list as new_list: Before: otherlist ???? ????? [1, 2, 3] mylist ??????? new_list ????????? [4, 5, 6] After: otherlist ???????? [1, 2, 3] mylist ??????? ????? [4, 5, 6] new_list ????? whereas "mylist[:] = new_list" modifies the list to which mylist already refers to contain the same items as new_list: Before: otherlist ???? ????? [1, 2, 3] mylist ??????? new_list ????????? [4, 5, 6] After: otherlist ???? ????? [4, 5, 6] mylist ??????? new_list ????????? [4, 5, 6] (I hope the characters come out OK! :-)) From wegwerp at gmail.com Fri Jun 13 08:01:16 2008 From: wegwerp at gmail.com (Bas) Date: Fri, 13 Jun 2008 05:01:16 -0700 (PDT) Subject: Plotting Graphs + Bestfit lines References: <1a919a2b-6430-4e2e-a190-2e00e43a6138@25g2000hsx.googlegroups.com> Message-ID: <29b820e3-43af-4366-8931-04371940d50c@f63g2000hsf.googlegroups.com> I am not going to reverse engineer your code, but it looks like your writing your own least-squares fitting algorithm and doing some simple plots. Also, from your many posts last days, it looks like you are a newbie struggling with a python interface to gnuplot. May I suggest that you have a look at numpy/scipy/matplotlib instead? With those, the things that you are trying to do could be done trivially in a just a few lines. What you want to do could be done with something like (untested!): from pylab import * xdata = ... %whatever you get it from ydata = ... p = polyfit(xdata, ydata, 1) %fit 1st order polynomial plot(xdata, ydata, xdata, 'o', polyval(p, xdata)) %plot original data with fit show() Things like fitting algorithms are already included, so you can focus your energy on the real work. E.g., if you later want to change to a quadratic fit instead of a linear, you just change 1 to 2 in the polyfit. As you said in one of your other posts, you need to find the intersection point of two lines. If poly1 and poly2 are the polynomials describing the lines, you would get your answer as x_intersect = roots(poly1 - poly2) y_intersect = polyval(poly1,x_intersect) plot(x,polyval(poly1,x),x,polyval(poly2,x),x_intersect,y_intersect,'o') show() HTH, Bas From erokar at gmail.com Sat Jun 21 08:36:53 2008 From: erokar at gmail.com (erokar at gmail.com) Date: Sat, 21 Jun 2008 05:36:53 -0700 (PDT) Subject: Fast and easy GUI prototyping with Python Message-ID: <9c349bf0-ef63-4463-bd4e-cdbe331b58c3@z66g2000hsc.googlegroups.com> Which tools would you use? I want the interface design to be as easy and fast as possible, all ideology aside. I'm considering either IronPython+Visual Studio or Python+Qt -- but I'm open for other suggestions. Visual Studio seems to offer the easiest solution, but is IronPython stable enough? How easy is the IronPython/Visual Studi integration? What about IronPython Studio? From s0suk3 at gmail.com Thu Jun 26 22:47:29 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Thu, 26 Jun 2008 19:47:29 -0700 (PDT) Subject: Working with the Windows Registry References: <49beca2a-9d6c-40a2-a7c3-bf1cf376df0a@l28g2000prd.googlegroups.com> <11e16b1f-0770-4932-994e-1ac3bc8e17e4@c19g2000prf.googlegroups.com> Message-ID: <90e4f09d-25f4-41b0-8c65-ccca10184ed9@z72g2000hsb.googlegroups.com> On Jun 26, 4:24 am, teh_sAbEr wrote: > Great! It works properly now but I have one more question, would > anyone know how to get the changes to take effect immediately? Like > some sort of Python way to force the desktop to reload? AFAIK the only > way that'll happen is if I use the Display Properties dialog box. The > Registry value is changed properly, its just I don't think the changes > will take effect until I restart. I haven't tried this, but I'd suggest to look at the Windows API. There are several Python interface modules such as win32api. From bj_666 at gmx.net Mon Jun 2 04:32:01 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Jun 2008 08:32:01 GMT Subject: Writing HTML References: <3760e9d1-d385-4e36-8ca6-e03e48ffdfbf@c58g2000hsc.googlegroups.com> Message-ID: <6ahpg1F379skjU3@mid.uni-berlin.de> On Mon, 02 Jun 2008 01:03:05 -0700, miller.paul.w wrote: > I've searched the standard library docs, and, while there are a couple > options for *reading* HTML from Python, I didn't notice any for > *writing* it. I guess that's where the many templating engines are used. Ciao, Marc 'BlackJack' Rintsch From mdw at distorted.org.uk Sun Jun 8 09:11:50 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Sun, 8 Jun 2008 13:11:50 +0000 (UTC) Subject: Newbie question, list comprehension References: <3rooh5xmap.ln2@joeserver.homelan.net> Message-ID: Johannes Bauer wrote: > import time > localtime = time.localtime(1234567890) > fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % (localtime[0], localtime[1], > localtime[2], localtime[3], localtime[4], localtime[5]) > print fmttime > > fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % ([localtime[i] for i in > range(0, 5)]) To reduce typing, set format = '%04d-%02d-%02d %02d:%02d:%02d' Two problems. * Firstly, range(0, 5) == [0, 1, 2, 3, 4], so it's not big enough. Python tends to do this half-open-interval thing. Once you get used to it, you'll find that it actually reduces the number of off-by-one errors you make. * Secondly, the result of a list comprehension is a list; (Unsurprising, really, I know.) But the `%' operator only extracts multiple arguments from a tuple, so you'd need to convert: format % tuple(localtime[i] for i in xrange(6)] (I've replaced range by xrange, which avoids building an intermediate list, and the first argument to range or xrange defaults to zero anyway.) Another poster claimed that localtime returns a tuple. This isn't correct: it returns a time.struct_time, which is not a tuple as you can tell: >>> '%s' % localtime '(2009, 2, 13, 23, 31, 30, 4, 44, 0)' This is one of those times when Python's duck typing fails -- string formatting really wants a tuple of arguments, and nothing else will do. But you can slice a time.struct_time, and the result /is/ a genuine tuple: >>> type(localtime[:6]) which is nice: >>> format % localtime[:6] '2009-02-13 23:31:30' But really what you wanted was probably >>> time.strftime('%Y-%m-%d %H:%M:%S', localtime) '2009-02-13 23:31:30' -- [mdw] From omer at no-log.org Fri Jun 13 11:27:54 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Fri, 13 Jun 2008 17:27:54 +0200 Subject: TypeError with date class In-Reply-To: <74e228bf0806130624y4f40e11do6181905119c82941@mail.gmail.com> References: <74e228bf0806130624y4f40e11do6181905119c82941@mail.gmail.com> Message-ID: <200806131727.54802.omer@no-log.org> Hi, Le Friday 13 June 2008 15:24:31 Dummy Pythonese Luser, vous avez ?crit?: > Greetings *.*: > > The following program caused an error and puzzled me to no end. Any help > immensely appreciated. > > > class Second(First): > def __init__(self, datestr): > y = int(datestr[0:4]) > m = int(datestr[4:6]) > d = int(datestr[6:8]) > First.__init__(self, y, m, d) > > # a = Second("20060201") > # TypeError: function takes exactly 3 arguments (1 given) > # Why? probably because date is an immutable type, so the init stuff is done in __new__ and not __init__ (and thus __new__ expects the same args as __init__). So you should replace First and Second __init__ methods by something like this : def __new__ (cls, datestr): y = int(datestr[0:4]) m = int(datestr[4:6]) d = int(datestr[6:8]) self = date.__new__(cls, y, m, d) return self The general rule is to do your initialization in __new__ for immutable types and in __init__ for mutable ones. See the chapter 3 of the reference manual (data model) for more infos. -- C?dric Lucantis From bignose+hates-spam at benfinney.id.au Wed Jun 4 01:55:38 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 04 Jun 2008 15:55:38 +1000 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> <873antn9il.fsf@benfinney.id.au> <6ammujF38poe2U2@mid.uni-berlin.de> Message-ID: <87y75llp5x.fsf@benfinney.id.au> Marc 'BlackJack' Rintsch writes: > On Wed, 04 Jun 2008 13:50:42 +1000, Ben Finney wrote: > > > It seems you [alex23] have a different idea of what unit testing > > is for from me. > > For me it's about finding bugs where documentation and > implementation disagree. Where "documentation" is "specified externally-visible behaviour of the unit", I agree with this. > And if you document private functions By definition, "private" functions are not part of the publicly documented behaviour of the unit. Any behaviour exhibited by some private component is seen externally as a behaviour of some public component. > it makes sense to me to also test if they work as documented. If they affect the behaviour of some public component, that's where the documentation should be. If they *don't* affect the external behaviour, then they shouldn't be there :-) Or, at least, their behaviour shouldn't be asserted as part of the tests of external behaviour. > Because the official API relies on the correct implementation of the > private parts it uses under the hood. Only to the extent that the documented behaviour of the API is affected. The main benefit of marking something as "not public" is that one *is* free to change its behaviour, so long as the public API is preserved. > One part of writing unit tests is invoking functions with arguments > that you think are "corner cases". For example test if a function > that takes a list doesn't bomb out when you feed the empty list into > it. Or if it handles all errors correctly. This sounds like part of the externally-visible behaviour of the code unit; i.e. something that belongs in the public API. I agree that this is the domain of a unit test. > If a function `f()` calls internally `_g()` and that function might > even call other private functions, then you have to know how `f()` > works internally to create input that checks if error handling in > `_g()` works correctly. No, you don't need to know how it works internally; you need only know what guarantees it must keep for its external behaviour. If someone wants to alter the `_g()` function, or remove it entirely while preserving the correct behaviour of `f()`, that should have no effect on the external behaviour of `f()`. That is to say, the knowledge of the "internals" of `f()` in your example is actually knowledge of something that should be documented as part of the external behaviour of `f()` ? that, or it's not relevant to the behaviour of `f()` and shouldn't be unit tested in order that encapsulation is preserved. > What do you do in such a situation? Build something from untested > private parts and just test the assembled piece? Assert the corner-case behaviour of `f()`, through unit tests that operate on `f()` without caring about its internals. > I prefer to test the private functions too. After all the private > functions are not private to the everybody, there *are* functions > that rely on them working correctly. Then for *those* interfaces, unit tests can be devised that make assertions about those interfaces. -- \ "[T]he speed of response of the internet will re-introduce us | `\ to that from which our political systems have separated us for | _o__) so long, the consequences of our own actions." -- Douglas Adams | Ben Finney From rhamph at gmail.com Sat Jun 7 02:32:32 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Fri, 6 Jun 2008 23:32:32 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> Message-ID: On Jun 6, 12:44 pm, The Pythonista wrote: > It's always been my understanding that you can't forcibly kill a thread > in Python (at least not in a portable way). The best you can do is > politely ask it to die, IIRC. Inherently, the best you can do in most languages is ask them politely to die. Otherwise you'll leave locks and various other datastructures in an inconvenient state, which is too complex to handle correctly. The exception is certain functional languages, which aren't capable of having threads and complex state in the same sense. However, you could go quite far with a standardized mechanism of politely asking threads to die. For instance, all blocking I/O functions could be made to support it. This is how cancellation works in python-safethread. From rgacote at AppropriateSolutions.com Mon Jun 9 15:48:41 2008 From: rgacote at AppropriateSolutions.com (Ray Cote) Date: Mon, 9 Jun 2008 15:48:41 -0400 Subject: Web Crawler - Python or Perl? In-Reply-To: <1a91e16d-ccfc-487a-80fc-4d9992455eb9@p25g2000hsf.googlegroups.com> References: <484D7329.6060107@behnel.de> <1a91e16d-ccfc-487a-80fc-4d9992455eb9@p25g2000hsf.googlegroups.com> Message-ID: At 11:21 AM -0700 6/9/08, subeen wrote: >On Jun 10, 12:15 am, Stefan Behnel wrote: >> subeen wrote: >> > can use urllib2 module and/or beautiful soup for developing crawler >> >> Not if you care about a) speed and/or b) memory efficiency. >> > > http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/ >> >> Stefan > >ya, beautiful soup is slower. so it's better to use urllib2 for >fetching data and regular expressions for parsing data. > > >regards, >Subeen. >http://love-python.blogspot.com/ >-- >http://mail.python.org/mailman/listinfo/python-list Beautiful Soup is a bit slower, but it will actually parse some of the bizarre HTML you'll download off the web. We've written a couple of crawlers to run over specific clients sites (I note, we did _not_ create the content on these sites). Expect to find html code that looks like this:
[from a real example, and yes, it did indeed render in IE.] I don't know if some of the quicker parsers discussed require well-formed HTML since I've not used them. You may want to consider using one of the quicker HTML parsers and, when they throw a fit on the downloaded HTML, drop back to Beautiful Soup -- which usually gets _something_ useful off the page. --Ray -- Raymond Cote Appropriate Solutions, Inc. PO Box 458 ~ Peterborough, NH 03458-0458 Phone: 603.924.6079 ~ Fax: 603.924.8668 rgacote(at)AppropriateSolutions.com www.AppropriateSolutions.com From paddy3118 at googlemail.com Tue Jun 24 03:44:47 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 24 Jun 2008 00:44:47 -0700 (PDT) Subject: Is there any way to find out sizeof an object References: Message-ID: <2338ccaf-d653-403a-9630-c06e7df98184@m73g2000hsh.googlegroups.com> On Jun 24, 6:00?am, srinivasan srinivas wrote: > Hi, > I have written a class which has some attributes. I want to know how do i find out the size of an?instance of this class?? > class T(object): > ??? def __init__(self, fn_name, *args, **kwds): > ??? ??? self.fn_name = fn_name > ??? ??? self.args = args > ??? ??? self.kwds = kwds > Thanks, > Srini > > ? ? ? Bollywood, fun, friendship, sports and more. You name it, we have it onhttp://in.promos.yahoo.com/groups/bestofyahoo/ Check memory Create a million Check memory Do maths! ;-) - Paddy. From omer at no-log.org Thu Jun 19 06:06:42 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Thu, 19 Jun 2008 12:06:42 +0200 Subject: Simple wxPython SetLabel question In-Reply-To: <005654a8-3406-4063-8e06-d7cf567b96d6@z66g2000hsc.googlegroups.com> References: <005654a8-3406-4063-8e06-d7cf567b96d6@z66g2000hsc.googlegroups.com> Message-ID: <200806191206.42524.omer@no-log.org> Le Thursday 19 June 2008 11:48:54 dp_pearce, vous avez ?crit?: > Hi All, > > Apologies if this should be seriously obvious. But I am quite new to > Python and it is not quite so obvious yet. > > I have a GUI which will eventually load and display database > information. I want the user to be able to browse for a database and > then load it. My problem relates to how I set the value of a TextCtrl > once the user has selected the database they wish to load. > > Here is a snip of my code: > > import wx > import os > > class TestFrame(wx.Frame): > def __init__(self): > wx.Frame.__init__(self, None, -1, "Code Snip") > panel = wx.Panel(self) > > databaseLbl = wx.StaticText(panel, -1, "Database:") > database = wx.TextCtrl(panel, -1, "") > databaseBtn = wx.Button(panel, -1, "Browse") > self.Bind(wx.EVT_BUTTON, self.OnBrowse, databaseBtn) > fetchSizer = wx.BoxSizer(wx.HORIZONTAL) > fetchSizer.Add(databaseLbl) > fetchSizer.Add(database, -1, wx.LEFT |wx.RIGHT, 5) > fetchSizer.Add(databaseBtn) > > panel.SetSizer(fetchSizer) > > def OnBrowse(self, event): > wildcard = "Access Database (*.mdb) | *.mdb | Access Database > (*.MDB) | *.MDB | All Files (*.*) | *.*" > dialog = wx.FileDialog(None, "Choose an database", > os.getcwd(), "", wildcard, wx.OPEN) > > if dialog.ShowModal() == wx.ID_OK: > path = dialog.GetPath() > ######################################### > # NOW SET TEXTCTRL "database" TO "path" > panel.database.SetLabel(path) > ######################################### > dialog.Destroy() > > app = wx.PySimpleApp() > TestFrame().Show() > app.MainLoop() > > The current code returns that "global name 'panel' is not defined" 'panel' is local to your __init__ function, so it's not available elsewhere. You should store it as an instance attribute instead : # in __init__: self.panel = wx.Panel(self) # in OnBrowse self.panel.database.SetLabel(patrh) note that unlike some other languages, panel and self.panel are two distinct variables, so you should replace _all_ references to panel by self.panel. -- C?dric Lucantis From jon.harrop.ms.sharp at gmail.com Thu Jun 5 09:17:01 2008 From: jon.harrop.ms.sharp at gmail.com (jon.harrop.ms.sharp at gmail.com) Date: Thu, 5 Jun 2008 06:17:01 -0700 (PDT) Subject: The Importance of Terminology's Quality References: Message-ID: On 5 Giu, 12:37, Jon Harrop wrote: > [...] P.S. Please don't look at my profile (at google groups), thanks! Jon Harrop From paul at boddie.org.uk Wed Jun 11 05:36:41 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 11 Jun 2008 02:36:41 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <4847d39d$0$7614$426a74cc@news.free.fr> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> <484cf5f6$0$15495$426a74cc@news.free.fr> <127975a3-b3d9-4799-9673-b292ec8d37e3@x19g2000prg.googlegroups.com> <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> <484e3526$0$30894$426a74cc@news.free.fr> <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> <783c55ec-a294-4600-91d9-4a0d78632c49@t12g2000prg.googlegroups.com> <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> <484f880c$0$6412$426a74cc@news.free.fr> Message-ID: On 11 Jun, 10:10, Bruno Desthuilliers wrote: > Russ P. a ?crit : > > > You may be right to an extent for small or medium-sized non-critical > > projects, but you are certainly not right in general. I read something > > a while back about the flight software for the Boeing 777. I think it > > was something like 3,000,000 lines of Ada code. > > I can't obviously back my claim, but you could probably have the same > feature set implemented in 10 to 20 times less code in Python. It's easy to make claims like this knowing that people aren't likely to try and write such a system in Python. > Not that > I suggest using Python here specifically, but just to remind you that > kloc is not a very exact metric - it's relative to the design, the > language and the programmer(s). The first project I worked on > (professionaly) was about 100 000 locs when I took over it, and one year > later it was about 50 000 locs, with way less bugs and way more > features. FWIW, the bigger the project, the bigger the chances that you > could cut it by half with a good refactoring. Perhaps you should get in touch with the advocacy-sig mailing list and provide them with the concrete details, because although you and I (and many others) recognise intuitively that Python code is typically shorter than, say, Java because the boilerplate of the latter is unnecessary, the last big discussion I recall about Python code being shorter than that of statically typed languages didn't really yield much in the way of actual projects to make the case. > > Normally, for a > > project of that magnitude the final integration would be expected to > > take something like three months. However, the precise interface specs > > and encapsulation methods in Ada allowed the integration to be > > completed in just three days. > > > By your recommended method of social interaction, that would be one > > hell of a lot of talking! > > Or just writing and reading. Maybe, but I'd imagine that the project mentioned is a fairly large one with all the classic observations by Brooks highly applicable. Such things can incur huge costs in a large project. > > I realize that Python is not designed for such large projects, > > Clueless again. Python is pretty good for large projects. It might be good for large projects but is it good for large projects *such as the one mentioned*? > Now the point > is that it tends to make them way smaller than some other much more > static languages. As an average, you can count on something between 5:1 > to 10:1 ratio between Java (typical and well-known reference) and Python > for a same feature set. And the larger the project, the greater the ratio. Again, I don't doubt this intuitively, but many people do doubt it. Citation needed! [...] > Do you really think you're talking to a bunch of clueless newbies ? You > can bet there are quite a lot of talented *and experimented* programmers > here. Maybe, but with the style of discourse you've been using, you're not really speaking for them, are you? > > Perhaps the benefits of interface specs and encapsulation are not as > > obvious for smaller projects, > > Plain wrong. I'm not a big fan of lots of up-front declarations when the code is easy to understand intuitively, but what are you trying to say here? That interface specifications and encapsulation are as essential for a three line script as they are for a large project? > > but certainly they are not zero. > > You still fail to get the point. Interface specifications and > encapsulation are design principles. period. These principles are just > as well expressed with documentation and naming conventions, and the > cost is way lower. I guess it depends on how the documentation gets written, because from what I've seen documentation is one of the more neglected areas of endeavour in software development, with many development organisations considering it a luxury which requires only a cursory treatment in order to get the code out of the door. > Russ, do yourself a favor : get out of your cargo-cult one minute and > ask yourself whether all python users are really such a bunch of > clueless newbies and cowboy hackers. You may not have noticed, but there > are some *very* talented and *experimented* programmers here. Maybe, but I'd hope that some of those programmers would be at least able to entertain what Russ has been saying rather than setting themselves up in an argumentative position where to concede any limitation in Python might be considered some kind of weakness that one should be unwilling to admit. Paul From tryacct at gmail.com Fri Jun 13 09:24:31 2008 From: tryacct at gmail.com (Dummy Pythonese Luser) Date: Fri, 13 Jun 2008 21:24:31 +0800 Subject: TypeError with date class Message-ID: <74e228bf0806130624y4f40e11do6181905119c82941@mail.gmail.com> Greetings *.*: The following program caused an error and puzzled me to no end. Any help immensely appreciated. (Thanks)^2 - Yet Another Dummy Python User (Python version: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 ) ------------------------------------------------------------------------------------------- from datetime import date #------------------------------------------------------------ class First(date): def __init__(self, y, m, d): date.__init__(self, y, m, d) class Second(First): def __init__(self, datestr): y = int(datestr[0:4]) m = int(datestr[4:6]) d = int(datestr[6:8]) First.__init__(self, y, m, d) #------------------------------------------------------------ class One(object): def __init__(self, y, m, d): self.y = y self.m = m self.d = d class Two(One): def __init__(self, datestr): y = int(datestr[0:4]) m = int(datestr[4:6]) d = int(datestr[6:8]) One.__init__(self, y, m, d) #------------------------------------------------------------ # Do this and you get an error: # a = Second("20060201") # TypeError: function takes exactly 3 arguments (1 given) # Why? a = Second("20060201") print a #------------------------------------------------------------ # By comparison, do this and there's no error. b = Two("20060301") print b -------------- next part -------------- An HTML attachment was scrubbed... URL: From sspatz at kcnet.com Mon Jun 23 13:41:28 2008 From: sspatz at kcnet.com (Saul Spatz) Date: Mon, 23 Jun 2008 12:41:28 -0500 Subject: Question: How do I format printing in python In-Reply-To: References: Message-ID: format the strings: http://www.python.org/doc/2.1.3/lib/typesseq-strings.html joemacbusiness at yahoo.com wrote: > Hi All, > > How do I format printed data in python? > I could not find this in the Python Reference Manual: > http://docs.python.org/ref/print.html > Nor could I find it in Matloff's great tutorial: > http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf > > > For example, how do I turn this: > > 512 Jun 5 2004 X11r6 > 22 Jan 17 2005 a2p > 22 Jan 17 2005 acctcom > 5374 Sep 15 2002 acledit > 5664 May 13 2004 aclget > 12020 May 13 2004 aclput > 115734 Jun 2 2004 adb > 46518 Jun 4 2004 admin > 66750 Sep 16 2002 ali > 1453 Sep 15 2002 alias > 28150 Jun 4 2004 alog > 15 May 12 2005 alstat > > into this: > > 512 Jun 5 2004 X11r6 > 22 Jan 17 2005 a2p > 22 Jan 17 2005 acctcom > 5374 Sep 15 2002 acledit > 5664 May 13 2004 aclget > 12020 May 13 2004 aclput > 115734 Jun 2 2004 adb > 46518 Jun 4 2004 admin > 66750 Sep 16 2002 ali > 1453 Sep 15 2002 alias > 28150 Jun 4 2004 alog > 15 May 12 2005 alstat > > Thank you From aleksi at agee.com Sat Jun 21 16:19:23 2008 From: aleksi at agee.com (Aleksi Krause) Date: Sat, 21 Jun 2008 15:19:23 -0500 Subject: Welho luopunut TF-boxin markkinoinnista. References: Message-ID: <1214079563_3929@news-in1.superfeed.net> 01.05.2008 J?? historian kirjoihin erityisp?iv?m??r?n? josta alkaa ydinalan vaikeudet kasautumaan aivan erityisesti my?s Suomessa. Jo siit? asti kun puollisentoista vuotta sitten Krister Fuuglesangin NASA:n avaruusionisaatioraportin tiedot maapalloa kohtaavasta v??j??m?tt?m?st? ydinvoimap??st?jen megatuhosta vuodettiin maailman p??tt?jille ydinalan alasajon v?ltt?m?tt?myys on ollut tiedossa. Samasta pohjasta jopa IPCC ennakoi koko ilmastoj?rjestelm?n tuhoa 10v sis?ll?. Mutta toukokuusta alkaa my?s tietomuruja mainiyusta maailmanhistorian suurimmasta ydinkatastrofitulemisesta vuotaa, esim. kauttani viimein suuren kansanmassan tietoisuuteen. Mist? tarkemmin on kyse. Maailman metastabiilinen perustaustataso on 10-kertaistunut totaalisen tuhoisaan suuntaansa romahdellen. Luonto itsess??n viestitt?? katastrofaalisista mehil?istuhoviesteist? ja vastaavantyyppisist? ydinkampamaneetti-invaasioista kiihtyv?sti. Einsteinin 5v mehil?ish?vi?misn?yt?ist? ennakoima ionosf??rituho on vy?ry?m?ss? kaikin merkein ihmiskunnan kohtaloksi. Onnistuin saamaan ydinalan silkaksi kauhuksi YVA 4/TEM tiedostoihin maininnat siit?, ett? tulevat sukupolvet voivat my?s arkistofaktojen perusteella tuomita nykyiset ydintoimitsijat, firmat ja p??tt?j?t ydinalan kansainv?liseen Nyyrbergin oikeudenk?yntiin p??tt?jiemme nyttemmin kiistatta tiet?mist? rikoksistaan ihmiskuntaa vastaan. Niin pitk?lle on prosessi edennyt, ett? Sis?ministeri? jo panikoi t?m?n tulevan faktan tiet?en! YLE-teksti-TV kirjoitti, miten v?hin ??nin oli muutettu maamme lakia rajusti: " Rikoksista ihmisyytt? vastaan on toimeenpantu lakimuutos 01.05 lukien, ett? jatkossa henkil?it?, ryhmi? ja teollisuuslaitoksia jne. jotka tuomitaan eritt?in raskauttavista (ydin) ja sotatoimista kansaansa vastaan ja rikoksista ihmisyytt? vastaan ei voida tuomita Suomesta kansainv?lisiin Haagin tuomioistuimiin saamaan jopa kuolemantuomioitaan. Vaan jopa n?in rajuista rikoksista langetetaan korkeintaan Suomen lains??d?nn?ll? paikan p??ll? maksimirangaistukseksi rajaten vain elinkautisiksi! Siis huh, hu alkaa ydinherrojemme polvet tutista alati kasvavien ydinrikosilmitulojen paineissa! Ilmankos Heiniluoma sanoi, ettei Suomeen TVO:n kaavailemia isotooppilaitostartteja ja ydinvoimaloittemme keskeisi? plutoniumpoltto-oikeuksia, uraanikaivosmassiiveineen ja ydinj?tek?sittelyineen EU:sta kiirehdit?. Vaan oltiin yht ?kki? sit? mielt?, ettei edes seuraavakaan hallitus tunke kokoomuksen/TVO/Posiva:n suunnattomaksi mieliharmiksi lupaa hakien kansantahtoa vastaan edell?mainittuihin NATOn hyv?ksymiin-optiotoimiin. 02.04-08. Uutiset kertoivat, ett? j?lleen kerran oli Norjassa 200km Oslosta pohjoiseen Ottessa sortunut tektoniliikunnasta 300m pitk? ja 50m leve? kalliorinne ja allle oli hautautunut v?hint??n 150 hengen pakolaisvirran startanneen v?est?n kymmenet talot. Edellisest? t?st? kuuluisasta 2500 km pitk?st? Laatokka-Skotlantitektonisesta Litoraanisaumalikunnasta Olkiluodon l?pi olimme saaneet viestej? Norjasta 5 hengen kuolemaep?ilyst? ja 7m liikuneesta vuorirojahduksesta kuukausi sitten. P?iv?n selv?sti t?m? kyseinen maailman syvin maanp??llinen tektonisauma on hurjasti aktivoitumassa. Niin ruotsalaisvoimalat, kuin Olkiluodon kaikki laittomasti mm. kallioon ankkuroidut ydinvoimalat tulevat liikuntojen murskaamina joutumaan suunnattomiin vaikeuksiin. 5cm/v liikuva sauma kun tuottaa jatkossa ruotsalaisopein huikeita mitattuja yli 8 Rihterin maanj?ristyksi?! Edes vuoden takaista 450m kallioliikuntoa Ruotsissa saati saman aikaista 14 Norjan luolan tuhoa ei olla uskallettu tutkia julkisesti. Virannoimaisten panikointi muutti jo nyt koko Ruotsin tektonisaumaan ydinj?tehautauskuviot totaalisesti syv?porausmalleihinsa. Esimauksi my?s Suomeen 10 kertaistuneine lis?maksuin turvarajamuutospakoin. Mutta kaikesta n?kee, ettei luonto t?h?n tyydy, vaan pahentaa odotettaan alati! From stefan_ml at behnel.de Thu Jun 5 04:00:47 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 05 Jun 2008 10:00:47 +0200 Subject: Looking for some good python learning resources on the web In-Reply-To: <8c4fb782-2767-4163-a577-195a22623493@v1g2000pra.googlegroups.com> References: <8c4fb782-2767-4163-a577-195a22623493@v1g2000pra.googlegroups.com> Message-ID: <48479D2F.3000902@behnel.de> fivetwentysix at gmail.com wrote: > What are the best sites to read to learn python? http://wiki.python.org/moin/BeginnersGuide Stefan From exarkun at divmod.com Wed Jun 25 11:48:56 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 25 Jun 2008 11:48:56 -0400 Subject: sending executable data over network.. In-Reply-To: <7-ydnfk_Rd2E-f_VnZ2dnUVZ_tbinZ2d@comcast.com> Message-ID: <20080625154856.4714.269231644.divmod.quotient.13035@ohm> On Wed, 25 Jun 2008 10:28:10 -0500, Larry Bates wrote: >C?dric Lucantis wrote: >>Le Tuesday 24 June 2008 08:59:40 Piyush Anonymous, vous avez ?crit : >>>hi, >>>i wish to change the way the function definition at run time in a running >>>server. new function code which is to be executed is provided by a client >>>at different location. >>>i am getting it by reading a file and sending it using makefile() with >>>server/client connected using sockets. >>> >>>how can make the lines received in a string array as new function >>>definition? or should i receive it in a different way? >>> >>>is there any better way to do the entire thing? >> >>One way is to transmit the code as a string and compile it on server-side >>with the 'compile' builtin function. Another is to compile it on client- >>side and transmit the resulting code object with the marshal module but >>there are many restrictions on it (specially the fact that the client and >>server will have to run the same python version) so carefully read the docs >>first. I'd choose the first solution, eventually using the pickle module to >>avoid encoding problems. >You may want to take a look at Twisted Python Perspective Broker. I believe >it does what you are looking for. > Twisted PB goes out of its way to *not* allow arbitrary code specified by a peer to be executed, actually. :) It is intended to be used when you cannot trust the network (a common scenario) but still want to perform complex operations and pass complex data around. Jean-Paul From stargaming at gmail.com Wed Jun 18 02:32:58 2008 From: stargaming at gmail.com (Robert Lehmann) Date: 18 Jun 2008 06:32:58 GMT Subject: Name lookup inside class definition References: <1c1a1181-905c-4401-ae00-36b3fabebab9@v1g2000pra.googlegroups.com> Message-ID: <4858ac1a$0$23848$9b622d9e@news.freenet.de> On Tue, 17 Jun 2008 23:05:56 -0700, WaterWalk wrote: > Hello. Consider the following two examples: class Test1(object): > att1 = 1 > def func(self): > print Test1.att1 // ok > > class Test2(object): > att1 = 1 > att2 = Test2.att1 // NameError: Name Test2 is not defined > > It seems a little strange. Why a class name can be used in a method > while cannot be used in the class block itself? I read the "Python > Reference Manual"(4.1 Naming and binding ), but didn't get a clue. It's because functions actually defer the name lookup. So you can use *any* name in a function, basically. If it's there at the function's runtime (not its declaration time), you're okay. During the execution of a class body, the class is not yet created. So you're running this ``Test2.att1`` lookup already (it has to be executed *now*, during the class creation) and fail because the class is not there. You can still refer to the class' scope as a local scope:: >>> class A(object): ... att1 = 1 ... att2 = att1 + 2 ... >>> A.att1 1 >>> A.att2 3 HTH, -- Robert "Stargaming" Lehmann From google at mrabarnett.plus.com Wed Jun 25 10:44:50 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 25 Jun 2008 07:44:50 -0700 (PDT) Subject: insertion sorts... References: <06adb999-c7e2-4475-a49f-dbfbe042f4fd@r66g2000hsg.googlegroups.com> <5f0111a3-c1b9-4864-bae3-32fa324c4e5e@j22g2000hsf.googlegroups.com> <841dd5b8-d99d-4a60-ad39-b7c9563fca1d@d1g2000hsg.googlegroups.com> Message-ID: <8ceb6019-6474-485c-8daf-91111c85040c@m36g2000hse.googlegroups.com> On Jun 25, 11:37?am, "A.T.Hofkamp" wrote: > On 2008-06-25, python_newbie wrote: > > > On 24 Haziran, 04:33, Terry Reedy wrote: > > Thanks for all answers. At the end i ve only one point. If a decide to > > copy list to iterate when will i have to do this ? Before the > > iteration ? And then iterate through one list and change value of the > > other ? > > Before starting the iteration would be a good point.... > > I usually do in such cases: > > for x in mylist[:]: > ? ?... > > making a copy just before the for loop starts. > > Lately, I have started avoiding in-place modification of lists. Instead, I > construct a new list from scratch inside the for-loop, and replace the old list > with the newly constructed list afterwards like: > > new_list = [] > for x in mylist: > ? ?.... > ? ?new_list.append(x) > > mylist = new_list > > by appending a different value than the original or by not appending, you can > influence the contents of the new list. > > I find this solution nicer than in-place modification of an existing list. > > Sincerely, > Albert And if you were originally doing in-place modification because there were also other references to the list then you could just do: mylist[:] = new_list From dan at catfolks.net Wed Jun 4 08:47:20 2008 From: dan at catfolks.net (Daniel Mahoney) Date: Wed, 04 Jun 2008 07:47:20 -0500 Subject: Handling some isolated iso-8859-1 characters References: Message-ID: > No, it's not you, those headers are formatted following RFC 2047 > > Python already has support for that format, use the email.header class, > see Excellent, that's exactly what I was looking for. Thanks! From omer at no-log.org Mon Jun 23 10:24:40 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Mon, 23 Jun 2008 16:24:40 +0200 Subject: Distutils and unit test files Message-ID: <200806231624.40062.omer@no-log.org> > On Mon, Jun 23, 2008 at 9:59 AM, C?dric Lucantis wrote: > > Yes a checksuite should be kept separate from the 'real' code. You can > > run it locally by setting the PYTHONPATH environment variable : > > > > PYTHONPATH=/path/to/your/modules python checksuite.py > > So I could also just append the path to sys.path in checksuite.py file > and use checksuite to run all my unit tests? > (woops, sorry for the private post :) Yes this is equivalent, as sys.path is initialized from PYTHONPATH at startup. But I'd suggest to insert your path at the beginning of sys.path rather than appending it, so you'll be sure to use the local modules even if they are already installed (I use 1 instead of 0 because sys.path[0] has a special meaning) : sys.path.insert(1, '/path/...') But I prefer to use PYTHONPATH, so the user keeps control on it (and can eventually check installed modules too). If you don't want to have to set it at each run, you can still write a simple wrapper script for your own needs. -- C?dric Lucantis From bruno.42.desthuilliers at websiteburo.invalid Fri Jun 6 11:33:26 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 06 Jun 2008 17:33:26 +0200 Subject: Newb question: underscore In-Reply-To: References: Message-ID: <48495888$0$26543$426a74cc@news.free.fr> John Fabiani a ?crit : > Skye wrote: > >> What is this doing? >> >> print >> fd, _(__doc__) >> >> >> I'm guessing line-splitting __doc__ into a list, but what's that >> leading underscore do? >> >> Thanks! > I think it is standard practice to use the underscore for unicode converts. Actually, it's for i18n, not for encoding. From george.sakkis at gmail.com Mon Jun 16 10:55:54 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 16 Jun 2008 07:55:54 -0700 (PDT) Subject: Removing inheritance (decorator pattern ?) References: <6blbcoF3b6v17U1@mid.uni-berlin.de> <6bmomrF3d11s6U1@mid.uni-berlin.de> Message-ID: <720877e5-0ee3-4f1e-8600-483d45d67475@e53g2000hsa.googlegroups.com> On Jun 16, 5:04?am, "Diez B. Roggisch" wrote: > Diez B. Roggisch wrote: > > George Sakkis schrieb: > >> I have a situation where one class can be customized with several > >> orthogonal options. Currently this is implemented with (multiple) > >> inheritance but this leads to combinatorial explosion of subclasses as > >> more orthogonal features are added. Naturally, the decorator pattern > >> [1] comes to mind (not to be confused with the the Python meaning of > >> the term "decorator"). > > >> However, there is a twist. In the standard decorator pattern, the > >> decorator accepts the object to be decorated and adds extra > >> functionality or modifies the object's behavior by overriding one or > >> more methods. It does not affect how the object is created, it takes > >> it as is. My multiple inheritance classes though play a double role: > >> not only they override one or more regular methods, but they may > >> override __init__ as well. Here's a toy example: > > >> class Joinable(object): > >> ? ? def __init__(self, words): > >> ? ? ? ? self.__words = list(words) > >> ? ? def join(self, delim=','): > >> ? ? ? ? return delim.join(self.__words) > > >> class Sorted(Joinable): > >> ? ? def __init__(self, words): > >> ? ? ? ? super(Sorted,self).__init__(sorted(words)) > >> ? ? def join(self, delim=','): > >> ? ? ? ? return '[Sorted] %s' % super(Sorted,self).join(delim) > > >> class Reversed(Joinable): > >> ? ? def __init__(self, words): > >> ? ? ? ? super(Reversed,self).__init__(reversed(words)) > >> ? ? def join(self, delim=','): > >> ? ? ? ? return '[Reversed] %s' % super(Reversed,self).join(delim) > > >> class SortedReversed(Sorted, Reversed): > >> ? ? pass > > >> class ReversedSorted(Reversed, Sorted): > >> ? ? pass > > >> if __name__ == '__main__': > >> ? ? words = 'this is a test'.split() > >> ? ? print SortedReversed(words).join() > >> ? ? print ReversedSorted(words).join() > > >> So I'm wondering, is the decorator pattern applicable here ? If yes, > >> how ? If not, is there another way to convert inheritance to > >> delegation ? > > > Factory - and dynamic subclassing, as shown here: > > > import random > > > class A(object): > > ? ? ?pass > > > class B(object): > > ? ? ?pass > > > def create_instance(): > > ? ? ?superclasses = tuple(random.sample([A, B], random.randint(1, 2))) > > ? ? ?class BaseCombiner(type): > > > ? ? ? ? ?def __new__(mcs, name, bases, d): > > ? ? ? ? ? ? ?bases = superclasses + bases > > ? ? ? ? ? ? ?return type(name, bases, d) > > > ? ? ?class Foo(object): > > ? ? ? ? ?__metaclass__ = BaseCombiner > > ? ? ?return Foo() > > > for _ in xrange(10): > > ? ? ?f = create_instance() > > ? ? ?print f.__class__.__bases__ > > Right now I see of course that I could have spared myself the whole > __metaclass__-business and directly used type()... Oh well, but at least it > worked :) > > Diez Ok, I see how this would work (and it's trivial to make it cache the generated classes for future use) but I guess I was looking for a more "mainstream" approach, something that even a primitive statically typed language could run :) Even in Python though, I think of Runtime Type Generation like eval(); it's good that it exists but it should be used as a last resort. Also RTG doesn't play well with pickling. Since I don't have many useful subclasses so far, I'll stick with explicit inheritance for now but I'll consider RTG if the number of combinations becomes a real issue. George From space.captain.face at gmail.com Fri Jun 6 22:59:05 2008 From: space.captain.face at gmail.com (Kalibr) Date: Fri, 6 Jun 2008 19:59:05 -0700 (PDT) Subject: Dynamically naming objects. Message-ID: <8a99c3fa-1eeb-49b3-a714-b6063ec1daab@d19g2000prm.googlegroups.com> I've been developing a small script to fiddle with classes, and came accross the following problem. Assuming I get some user input asking for a number, how would I spawn 'n' objects from a class? i.e. I have a class class 'user' and I don't know how many of them I want to spawn. Any ideas? From aishwaryagroup at gmail.com Thu Jun 12 05:44:06 2008 From: aishwaryagroup at gmail.com (AISHWARYA) Date: Thu, 12 Jun 2008 02:44:06 -0700 (PDT) Subject: ATT WIRELESS Message-ID: ______________________________________________ http://attwireless1.blogspot.com http://onenesstemple.blogspot.com http://maintanancemanagementsoftwareservises.blogspot.com http://consolidation2.blogspot.com http://debtmanagementcompany.blogspot.com/ http://personalloanscash.blogspot.com/ http://attwireless1.blogspot.com From michele.simionato at gmail.com Tue Jun 24 14:07:28 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 24 Jun 2008 11:07:28 -0700 (PDT) Subject: Python 3000 vs Perl 6 References: <89fbe834-68b7-49e6-8136-62dee53c2f40@t54g2000hsg.googlegroups.com> <7bad9ebd-81ab-48c4-854b-05f085e9d936@27g2000hsf.googlegroups.com> <1cbcd0fd-b168-4018-a69a-bba8fb26924e@79g2000hsk.googlegroups.com> Message-ID: On Jun 24, 5:11?pm, bearophileH... at lycos.com wrote: > Well chosen restrictions sometimes are very useful, they may act like > a scaffolding, you can build higher constructions on them (Python has > no macros, this is a restriction. But this restriction has some > advantages. One of the main advantages is that it makes the Python > code more uniform across different programmers, this is one of the > thinks that makes the Python world so full of pre-made modules to do > most of the things you may want to do). I am all in favor of *well chosen* restrictions. However the meaning of "well chosen" depends on the context. For instance, just today I was reading this very interesting paper on PLT Scheme object system: http://www.cs.utah.edu/plt/publications/aplas06-fff.pdf The interesting thing is that the whole system is built in pure Scheme on top of macros, and still it has an acceptable performance. In Python I could never do the same, I would need to resort to C. So, while I agree that for the common use cases of the enterprise programmer Python is much more productive than Scheme, a computer scientists experimenting with object systems will probably find Scheme more suitable then Python. But I am digressing. The point is that a language with very few well chosen features (say Scheme) allows you to build everything else on top of it (say an object system) without needing to resort to a different implementation language. I program in Python much more than in Scheme for many reasons, but not because I think that Clinger's maxin is wrong. Michele Simionato From apardon at forel.vub.ac.be Thu Jun 5 04:21:41 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 5 Jun 2008 08:21:41 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> <873antn9il.fsf@benfinney.id.au> <6ammujF38poe2U2@mid.uni-berlin.de> <87y75llp5x.fsf@benfinney.id.au> <6an5a7F38poe2U3@mid.uni-berlin.de> <6aok3pF38pu6cU2@mid.uni-berlin.de> Message-ID: On 2008-06-04, Marc 'BlackJack' Rintsch wrote: > On Wed, 04 Jun 2008 09:34:58 +0000, Antoon Pardon wrote: > >> On 2008-06-04, Marc 'BlackJack' Rintsch wrote: >> >>>>> it makes sense to me to also test if they work as documented. >>>> >>>> If they affect the behaviour of some public component, that's where >>>> the documentation should be. >>> >>> As I said they are public themselves for someone. >> >> Isn't that contradictory: "Public for someone" I always >> thought "public" meant accessible to virtually anyone. >> Not to only someone. > > For the programmer who writes or uses the private API it isn't really > "private", he must document it or know how it works. How does that make it not private. Private has never meant "accessible to noone". And sure he must document it and know how it works. But that documentation can remain private, limited to the developers of the product. It doesn't have to be publicly documented. -- Antoon Pardon From wizzardx at gmail.com Sat Jun 7 04:26:20 2008 From: wizzardx at gmail.com (David) Date: Sat, 7 Jun 2008 10:26:20 +0200 Subject: How to kill a thread? In-Reply-To: References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> Message-ID: <18c1e6480806070126w145f3dbw5a31e322c1111452@mail.gmail.com> Would it be possible for a 3rd-party threading library to an 'interruptible' version of Queue? The same methods as the normal Queue, but when you call a new .kill() method on the queue, all the threads locking on the queue get a "QueueKilled" exception thrown. It might be as simple as a Queue wrapper where .kill() adds a speciall Killed value to the queue, and the .get() wrapper throws a QueueKilled exception (after re-putting Killed) when it reads Killed. Locking for queues with a limited size is more complicated. Maybe .kill() can also set an .killed attribute, and pop anything already in the queue before putting Killed. Then when the put() wrapper unlocks, it checks if .killed is set, and throws a QueueKilled exception. One side-effect is that the queue becomes unusable (get & put now immediately throw QueueKilled), unless you make a .unkill() method. David From M8R-yfto6h at mailinator.com Mon Jun 16 10:02:31 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Mon, 16 Jun 2008 07:02:31 -0700 Subject: Iterate creating variables? References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> Message-ID: "Hyuga" wrote in message news:f9b72959-8c81-4e26-84e6-c80b1c84c4b2 at 34g2000hsh.googlegroups.com... > On Jun 13, 11:34 am, "Reedick, Andrew" wrote: >> > -----Original Message----- >> > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- >> > list-bounces+jr9445=att.... at python.org] On Behalf Of tda... at gmail.com >> > Sent: Friday, June 13, 2008 11:11 AM >> > To: python-l... at python.org >> > Subject: Iterate creating variables? >> >> > I have twenty-five checkboxes I need to create (don't ask): >> >> > self.checkbox1 = ... >> > self.checkbox2 = ... >> > . >> > . >> > . >> > self.checkbox25 = ... >> >> > Right now, my code has 25 lines in it, one for each checkbox, since >> > these are all variables. >> >> > Is there a way to write a loop so that I can have fewer lines of code >> > but still keep the variables? >> >> > I've tried: >> >> > for o in xrange(25): >> > self.checkbox[o] = ... >> >> > which didn't work, and >> >> > for o in xrange(25): >> > self.checkbox[''%d'%(o)] = ... >> >> > which also didn't work. >> >> > Both give the error message: "Attribute error: Main.App has no >> > attribute "checkbox"", which clearly indicates that I'm not keeping >> > the "variability" aspect I want. >> >> > Is there a way? >> >> > I appreciate any and all answers! >> >> Either store the checkboxes in an array or hash/dictionary. If that's >> not practical, then >> You can use strings to build the code and use eval to execute the string >> as code. Ex: >> >> for i in range(10): >> code = "%d + %d" % (i, i) >> print eval(code) > > Don't do this. You want > > for idx in range(10): > setattr(self, 'checkbox_%i' % idx) Assuming create_checkbox() is the function to create a checkbox, this will create a list of 25 checkboxes:: checkbox = [create_checkbox() for i in xrange(25)] --Mark From joemystery123 at gmail.com Mon Jun 23 19:43:05 2008 From: joemystery123 at gmail.com (joe shoemaker) Date: Mon, 23 Jun 2008 19:43:05 -0400 Subject: MD5 hash for url and utf unicode converting to ascii Message-ID: <372de840806231643m59c422a4n347915467f44cd04@mail.gmail.com> I would like to convert url into md5 hash. My question is that md5 hash will create collision at 2^64. If you do long(value,16), where value is the md5 hash string, would value returned from long(value, 16) be unique as long as md5 hashed string is unique? when you move md5 hashed string to long, where will the collision occur, at anything >= 2^64? hash = md5.new() hash.update("some_url_") value = hash.digest() value_in_int = long(value, 16) #would this be unique as long as hashed string is unique(i.e < 2^64) hash = md5.new() hash.update("some_url_") value = hash.digest() value_in_int = long(value, 16) #would this be unique as long as hashed string is unique(i.e < 2^64) Do I need to also convert the value to base64.encodestring(value)? What is the purpose of base64.encodestring? For unicode encoding, I can do, md5.update(value.encode('utf-8')) to give me ascii values. Thank you, j From sturlamolden at yahoo.no Wed Jun 4 14:21:30 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 4 Jun 2008 11:21:30 -0700 (PDT) Subject: how should i use this function? References: <99ed3c04-bd62-4456-ae12-eca4179005dc@r66g2000hsg.googlegroups.com> Message-ID: <5a09fa94-b3ce-4a13-af42-b9a1e6980900@25g2000hsx.googlegroups.com> On Jun 4, 8:14 pm, Gandalf wrote: > I tried to import win32ui.PyCRichEditCtrl, But the shell told me > their's no such module. There isn't, as it is a class. win32ui is a module. If you cannot import that, you don't have pywin32 installed. Go get it from Sourceforge. From bruno.42.desthuilliers at websiteburo.invalid Fri Jun 6 10:35:24 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 06 Jun 2008 16:35:24 +0200 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: <87hcc7zgo1.fsf@mulj.homelinux.net> References: <25e0de62-4c63-4545-8684-69a410639807@i76g2000hsf.googlegroups.com> <87hcc7zgo1.fsf@mulj.homelinux.net> Message-ID: <48494aef$0$11974$426a74cc@news.free.fr> Hrvoje Niksic a ?crit : > "bruno.desthuilliers at gmail.com" > writes: > >> On 5 juin, 17:40, Gabriel Rossetti >> wrote: >>> Hello everyone, >>> >>> I had read somewhere that it is preferred to use >>> self.__class__.attribute over ClassName.attribute to access class (aka >>> static) attributes. >> It's even prefered to use self.attribute, > > I was going to write exactly that, but it occurred to me that he might > want to be *assigning* to self.__class__.attribute (or > HisClass.attribute) from his methods, in which case self.attribute > would be quite different. ACK. From Sengly.Heng at gmail.com Sun Jun 8 02:42:48 2008 From: Sengly.Heng at gmail.com (Sengly) Date: Sat, 7 Jun 2008 23:42:48 -0700 (PDT) Subject: simple question on list manipulation from a newbie References: <76ccc0a8-90de-4717-9e6f-06836827b1e1@i18g2000prn.googlegroups.com> <6hD2k.4836$co7.3109@nlpi066.nbdc.sbc.com> Message-ID: <9ab9cb3f-787f-4552-9dc2-3f36c4c2ebe1@j33g2000pri.googlegroups.com> On Jun 8, 6:38?am, Sam Denton wrote: > Sengly wrote: > > Dear all, > > > I am working with wordnet and I am a python newbie. I'd like to know > > how can I transfer a list below > > > In [69]: dog > > Out[69]: > > [{noun: dog, domestic_dog, Canis_familiaris}, > > ?{noun: frump, dog}, > > ?{noun: dog}, > > ?{noun: cad, bounder, blackguard, dog, hound, heel}, > > ?{noun: frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, > > weenie}, > > ?{noun: pawl, detent, click, dog}, > > ?{noun: andiron, firedog, dog, dog-iron}] > > > to a list like this with python: > > > [dog, domestic_dog, Canis_familiaris, > > frump, dog, > > dog, > > cad, bounder, blackguard, dog, hound, heel, > > frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, > > weenie}, > > pawl, detent, click, dog}, > > andiron, firedog, dog, dog-iron] > > I can't help you with the formatting, but here's a solution using Python > data structures: > > ?>>> alist = [ > ? ? ?{'noun': ('dog', 'domestic_dog', 'Canis_familiaris')}, > ? ? ?{'noun': ('frump', 'dog')}, > ? ? ?{'noun': ('dog',)}, > ? ? ?{'noun': ('cad', 'bounder', 'blackguard', 'dog', 'hound', 'heel')}, > ? ? ?{'noun': ('frank', 'frankfurter', 'hotdog', 'hot_dog', 'dog', > 'wiener', 'wienerwurst', 'weenie')}, > ? ? ?{'noun': ('pawl', 'detent', 'click', 'dog')}, > ? ? ?{'noun': ('andiron', 'firedog', 'dog', 'dog-iron')}, > ? ? ?] > > ?>>> merged = {} > ?>>> for d in alist: > ? ? ? ? ?for key, value in d.iteritems(): > ? ? ? ? ? ? ?merged.setdefault(key, []).extend(value) > > ?>>> merged > {'noun': ['dog', 'domestic_dog', 'Canis_familiaris', 'frump', 'dog', > 'dog', 'cad', 'bounder', 'blackguard', 'dog', 'hound', 'heel', 'frank', > 'frankfurter', 'hotdog', 'hot_dog', 'dog', 'wiener', 'wienerwurst', > 'weenie', 'pawl', 'detent', 'click', 'dog', 'andiron', 'firedog', 'dog', > 'dog-iron']} Thank you all for your help. I found a solution as the following: alist = [ {'noun': 'dog', 'domestic_dog', 'Canis_familiaris'}, {'noun': 'frump', 'dog'}, {'noun': 'dog',}, {'noun': 'cad', 'bounder', 'blackguard', 'dog', 'hound', 'heel'}, {'noun': 'frank', 'frankfurter', 'hotdog', 'hot_dog', 'dog', 'wiener', 'wienerwurst', 'weenie'}, {'noun': 'pawl', 'detent', 'click', 'dog'}, {'noun': 'andiron', 'firedog', 'dog', 'dog-iron'}, ] def getAll(alist): list=[] for i in range(0,len(alist)): list.extend(alist[i][:]) return list Kind regards, Sengly From cokofreedom at gmail.com Wed Jun 4 08:30:06 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 4 Jun 2008 05:30:06 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> Message-ID: > > But the leading underscore doesn't tell you whether it is your own > private date, which you can use a you see fit, or those of someone > else, which you have to be very carefull with. > > -- > Antoon Pardon Well how is that different from public accessor and mutators of private variables? From ram.rachum at gmail.com Wed Jun 18 14:56:59 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Wed, 18 Jun 2008 11:56:59 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> <4857AA74.2080205@electrooptical.net> <1015fc7a-9e2c-4025-a062-9f90311ed120@r66g2000hsg.googlegroups.com> Message-ID: <4972e14f-dcb6-4a8b-bc9b-3c1aecfc892a@e39g2000hsf.googlegroups.com> On Jun 17, 5:04?pm, "Richard Brodie" wrote: > wrote in message > > news:1015fc7a-9e2c-4025-a062-9f90311ed120 at r66g2000hsg.googlegroups.com... > > >That was suggested. Problem is, that sometimes the velocities are near > >zero. So this solution, by itself, is not general enough. > > Maybe working in p, and delta-p would be more stable. That's a good one. It will, however, involve complicated calculations for obtaining v from p, so it might be slower than mpmath. I'll consider it. From pavlovevidence at gmail.com Fri Jun 27 07:04:32 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 27 Jun 2008 04:04:32 -0700 (PDT) Subject: Cyclic imports References: <1a5a1eb9-b4d1-4905-b60c-48fc93056e4d@k13g2000hse.googlegroups.com> <2588f7e0-ccbb-40cb-84da-d133349f5b72@u36g2000prf.googlegroups.com> Message-ID: <9aa6cb7a-34f0-4d3a-a21e-388886eb14d5@56g2000hsm.googlegroups.com> On Jun 27, 12:58 am, James wrote: > > # a.py > > import b > > # refer to b.b > > > # b.py > > import a > > # refer to a.a > > Thanks Dan, but that still doesn't work for me I'm afraid... > > I renamed the modules avoid name overloading -- a.py is now: > import b > > class A(): > print('b.b_mod:', b.b_mod) > > b is now defined, but b.b_mod isn't: > File "main.py", line 1, in > from a import a_mod > File "/Users/james/tmp/python/a/a_mod.py", line 3, in > class A(): > File "/Users/james/tmp/python/a/a_mod.py", line 4, in A > print('b.b_mod:', b.b_mod) > AttributeError: 'module' object has no attribute 'b_mod' > > I must be missing something here - I've tried adding the modules to > __all__ in __init__.py but that didn't help either. The above print statement runs at module import time, so you're seeing something that might not be an issue in functioning code. For instance, if you rewrite A like the following: class A(object): def print_b(self): print('b.b_mod:', b.b_mod) If you call the print_b method from outside the module (say, from main.py), it should work. What lessons did we learn here? Be aware of the difference between code that runs at module import time, and code that runs after the module is imported. In code that runs after the module has been imported (basically anything defined in a function that isn't called by code that runs at module time), you can expect the variables defined in the imported module to be available. In code that runs at module import time, there is no such guarantee, so you have to arrange your modules so that code that depends on another module is run after the dependent module. (One common time where this happens is when subclassing a class from another module: the module with the base class needs to run first.) If you have circular imports involved, making sure the modules import in a certain order can be quite hairy. (Faced with this problem, I found it necessary to write an import hook to pre-import certain modules.) Carl Banks From david at abbottdavid.com Mon Jun 23 22:17:05 2008 From: david at abbottdavid.com (David) Date: Mon, 23 Jun 2008 22:17:05 -0400 Subject: IDE on the level of Eclipse or DEVc++? In-Reply-To: <48604941.6030707@gmail.com> References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> <48604941.6030707@gmail.com> Message-ID: <48605921.4050000@abbottdavid.com> Rich Healey wrote: > > I don't want to start a flamewar. > > But I like vim. > Hi Rich, could I take a look at your .vimrc , the python stuff. thanks -- http://mail.python.org/mailman/listinfo/python-list -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From stephan.diehl at gmx.net Mon Jun 9 13:02:01 2008 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Mon, 09 Jun 2008 19:02:01 +0200 Subject: money data type References: Message-ID: Lie wrote: > On Jun 9, 10:22?pm, Stephan Diehl wrote: >> Hi lazyweb, >> I'm wondering, if there is a usable money data type for python available. >> A quick search in pypi and google didn't convey anything, even though the >> decimal data type seemed to be planned as a money data type originaly. >> Thanks for any pointers >> >> Stephan > > What is it that you feel is lacking in the decimal datatype that makes > you feel you require a money datatype? > Decimal datatype was a general purpose fixed-point number, which is > usually the behavior required for money calculation, but it's not > named 'money' because this behavior isn't only useful for money > calculation, so they don't name it money. I'm actually quite sure that the decimal data type will be sufficient for what I plan to do, but in a general setting, one would need currency support, maybe different rounding rules for different currencies, exchange rates, etc. From maric at aristote.info Fri Jun 13 11:13:25 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 13 Jun 2008 17:13:25 +0200 Subject: Summing a 2D list In-Reply-To: <878wx9leiv.fsf@ara.blue-cable.net> References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <878wx9leiv.fsf@ara.blue-cable.net> Message-ID: <200806131713.26364.maric@aristote.info> Le Friday 13 June 2008 14:12:40 Karsten Heymann, vous avez ?crit?: > Hi Mark, > > Mark writes: > > I have a scenario where I have a list like this: > > > > User ? ? ? ? ? ?Score > > 1 ? ? ? ? ? ? ? ? 0 > > 1 ? ? ? ? ? ? ? ? 1 > > 1 ? ? ? ? ? ? ? ? 5 > > 2 ? ? ? ? ? ? ? ? 3 > > 2 ? ? ? ? ? ? ? ? 1 > > 3 ? ? ? ? ? ? ? ? 2 > > 4 ? ? ? ? ? ? ? ? 3 > > 4 ? ? ? ? ? ? ? ? 3 > > 4 ? ? ? ? ? ? ? ? 2 > > > > And I need to add up the score for each user to get something like > > this: > > > > User ? ? ? ? ? ?Score > > 1 ? ? ? ? ? ? ? ? 6 > > 2 ? ? ? ? ? ? ? ? 4 > > 3 ? ? ? ? ? ? ? ? 2 > > 4 ? ? ? ? ? ? ? ? 8 > > > > Is this possible? If so, how can I do it? I've tried looping through > > the arrays and not had much luck so far. > > Although your problem has already been solved, I'd like to present a > different approach which can be quite a bit faster. The most common > approach seems to be using a dictionary: > > summed_up={} > for user,vote in pairs: > ? if summed_up.has_key(user): > ? ? summed_up[user]+=vote > ? else: > ? ? summed_up[user]=vote > > But if the list of users is compact and the maximum value is known > before, the using a list and coding the user into the list position is > much more elegant: > So, writing C in python, which has dictionnary as builtin type, should be considered "more elegant" ? > summed_up=list( (0,) * max_user ) > for user,vote in pairs: > ? summed_up[user] += vote > > I've run a quick and dirty test on these approaches and found that the > latter takes only half the time than the first. More precisely, with > about 2 million pairs, i got: > > * dict approach: 2s > ? ? ? ? (4s with "try: ... except KeyError:" instead of the "if") > * list approach: 0.9s > You are comparing apples with lemons, there is no such a difference between list index access and dictionnary key access in Python. > BTW this was inspired by the book "Programming Pearls" I read some > years ago where a similar approach saved some magnitudes of time >(using a bit field instead of a list to store reserved/free phone > numbers IIRC). If you know in advance the number and names of users, what prevent you to initialize completelly the target dictionnary ? The following code compare the same algorithm, once with list and the second time with dict : #!/usr/bin/env python def do(f, u, v) : from time import time n=time() f(u, v) return time() -n def c_dict(users, votes) : d = dict(((e, 0) for e in users)) for u, v in votes : d[u] += v return d.values() def c_list(users, votes) : d = [ 0 for i in users ] for u, v in votes : d[u] += v return d u = range(3000) import random v = list((u[r%3000], random.randint(0,10000)) for r in range(5*10**6)) print "with list", do(c_list, u, v) print "with dict", do(c_dict, u, v) The result is pretty close now : maric at redflag1 17:04:36:~$ ./test.py with list 1.40726399422 with dict 1.63094091415 So why use list where the obvious and natural data structure is a dictionnary ? -- _____________ Maric Michaud From castironpi at gmail.com Tue Jun 24 12:23:29 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 24 Jun 2008 09:23:29 -0700 (PDT) Subject: very large graph References: <135bba90-a9dd-4fcd-9220-6271e5a7c876@59g2000hsb.googlegroups.com> <02ef6dc2-9ddb-4fbc-b3ce-5e6247daab33@e39g2000hsf.googlegroups.com> Message-ID: <5bed4786-ceff-4aeb-bb5b-6e0ab95ebd1c@f36g2000hsa.googlegroups.com> On Jun 24, 5:58?am, "A.T.Hofkamp" wrote: > On 2008-06-24, MRAB wrote: > > > On Jun 24, 1:26?am, chrispoliq... at gmail.com wrote: > >> I need to represent the hyperlinks between a large number of HTML > >> files as a graph. ?My non-directed graph will have about 63,000 nodes > >> and and probably close to 500,000 edges. > > >> I have looked into igraph (http://cneurocvs.rmki.kfki.hu/igraph/doc/ > >> python/index.html) and networkX (https://networkx.lanl.gov/wiki) for > >> generating a file to store the graph, and I have also looked into > >> Graphviz for visualization. ?I'm just not sure which modules are > >> best. ?I need to be able to do the following: > > Afaik Graphviz is not good at abstracting the graph, which you may need here. > A page with 63,000 circles on it, and 500,000 edges will probably come out of > the printer as a black sheet of paper. > (8"x11" paper, 1 circle is 1/5", then you have only 2200 circles at one sheet. > You need a factor 28 more circles which leads to a circle of about 0.007".) > > Even when actual paper format would not be a problem, you will need some > abstraction and/or tools, as you will not find anything manually in an ocean of > 63,000 elements. > > One area you may want to start looking for tools is in state graphs, where the > set of possible states of an entire system is unfolded. These things go up to > over a million states, so you only have a 'small' problem there... > > > > > > >> 1) ?The names of my nodes are not known ahead of time, so I will > >> extract the title from all the HTML files to name the nodes prior to > >> parsing the files for hyperlinks (edges). > > >> 2) Every file will be parsed for links and nondirectional connections > >> will be drawn between the two nodes. > > >> 3) ?The files might link to each other so the graph package needs to > >> be able to check to see if an edge between two nodes already exists, > >> or at least not double draw connections between the two nodes when > >> adding edges. > > >> I'm relatively new to graph theory so I would greatly appreciate any > >> suggestions for filetypes. ?I imagine doing this as a python > >> dictionary with a list for the edges and a node:list paring is out of > >> the question for such a large graph? > > > Perhaps a dictionary where the key is a node and the value is a set of > > destination nodes? > > For undirected edges, you could make an Edge class and have a set of Edge's > (where two Edge objects are equal when they connect the same nodes). > I don't expect 500,000 elements in a set to be a problem. > > Sincerely, > Albert- Hide quoted text - > > - Show quoted text - Readability counts: Do you need to be able to examine the datafile by hand? If not, investigate the 'shelve' module. You can go two ways. One is to map each node to a list of nodes. It's probably more intuitive, but it needs repeated code: shelf['pageA'].add( pageB ) shelf['pageB']= pageB shelf['pageB'].add( pageA ) Which is incorrect as is anyway-- updates to shelved objects aren't committed automatically. a= shelf['pageA'] a.add( pageB ) shelf['pageA']= a b= shelf['pageB'] b.add( pageA ) shelf['pageB']= b is closer. Otherwise, two is to store a 2-tuple of node keys in a secondary file. shelfEdges[ frozenset( shelfVerts[ 'pageA' ], shelfVerts[ 'pageB' ] ) ]= True From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 30 06:08:58 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 30 Jun 2008 12:08:58 +0200 Subject: list extension ? In-Reply-To: References: Message-ID: <4868b0ba$0$17063$426a34cc@news.free.fr> Stef Mientki a ?crit : > hello, > > I basically need a list with a few extra attributes, > so I derived a new object from a list, and it works perfect. > But I wonder why the newly derived list component is much more flexible ? > > # so here is the new list object > class tGrid_List ( list ) : pep08: class GridList(list): > def __init__ ( self, value = [] ) : Gotcha : default argument values are eval'd only once. Also, it would make more sense IMHO to follow the parent's class initializer's behaviour: def __init__(self, *args) > list.__init__ ( self, value ) list.__init__(self, *args) > # and with this new list component, I can add new attributes on the fly > > a = tGrid_list ( [ 2, 3 ] ) a = GridList(2, 3) or l = [2, 3] a = GridList(*l) > a.New_Attribute = 'some text' > > # I'm not allowed to this with the standard list > > a = [ 2, 3 ] > a.New_Attribute = 'some text' <== ERROR > > Can someone explain this different behavior ? Most builtin types are optimized, and not having a __dict__ is part of this optimization. From martin at v.loewis.de Sat Jun 14 12:48:16 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 14 Jun 2008 18:48:16 +0200 Subject: Was the move to Python 2.0 as big a deal? In-Reply-To: <4853f365$0$11601$607ed4bc@cv.net> References: <4853f365$0$11601$607ed4bc@cv.net> Message-ID: <4853F650.8060602@v.loewis.de> > Just curious if people put up any resistance to 2.0 like some people do > for 3.0. IIRC, yes, it was. People have continued to use Python 1.5.2 afterwards for several years. > Was it as big of a change in the language, or was the > transition smoother? The changes were significantly smaller, so the transition was smoother. > It seems silly for anyone to say they would prefer > to stick with 1.x versions at this point, so perhaps we'll get there > with 3.0 eventually too. People will continue to use 2.x for several years certainly. > Anyway, I'm just trying to figure out if the whole "I don't like 3.0" > mentality (of some people, not all of course) is merely a result of it > still being new and not even released yet, and will completely go away > after a year or two; or if there really are such drastic changes that > people won't want to adopt it at all. A year or two won't be sufficient. IMO, the resistance is due to the feeling "it will cause me efforts to change my code, and I don't like additional efforts". This is a reasonable point to take, IMO, so people who have the time and inclination to convert their code will do so, and many others won't. Over time, people will convert the code when they do have the time (or the feeling that they shouldn't push it away further). Eventually, those people will convert that need some kind of library (change) that is only available for 3.x. Regards, Martin From kris at FreeBSD.org Wed Jun 18 11:01:38 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Wed, 18 Jun 2008 17:01:38 +0200 Subject: Looking for lots of words in lots of files In-Reply-To: References: Message-ID: <48592352.60908@FreeBSD.org> Calvin Spealman wrote: > Upload, wait, and google them. > > Seriously tho, aside from using a real indexer, I would build a set of > the words I'm looking for, and then loop over each file, looping over > the words and doing quick checks for containment in the set. If so, add > to a dict of file names to list of words found until the list hits 10 > length. I don't think that would be a complicated solution and it > shouldn't be terrible at performance. > > If you need to run this more than once, use an indexer. > > If you only need to use it once, use an indexer, so you learn how for > next time. If you can't use an indexer, and performance matters, evaluate using grep and a shell script. Seriously. grep is a couple of orders of magnitude faster at pattern matching strings in files (and especially regexps) than python is. Even if you are invoking grep multiple times it is still likely to be faster than a "maximally efficient" single pass over the file in python. This realization was disappointing to me :) Kris From fetchinson at googlemail.com Sat Jun 14 16:11:19 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 14 Jun 2008 13:11:19 -0700 Subject: Configuration files In-Reply-To: <485419f0$0$5958$e4fe514c@dreader16.news.xs4all.nl> References: <485419f0$0$5958$e4fe514c@dreader16.news.xs4all.nl> Message-ID: > What is the most Pythonic way to maintain a configuration file? > Are there any libraries mimicking registry / ini file writing that many > windows programming languages/environments offer? Check this out: http://www.voidspace.org.uk/python/configobj.html Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From oesoriano at gmail.com Sun Jun 22 14:06:21 2008 From: oesoriano at gmail.com (oesoriano at gmail.com) Date: Sun, 22 Jun 2008 11:06:21 -0700 (PDT) Subject: Learning Python in a group References: Message-ID: I might be interested in joining your group. I'm trying to learn python, too, but tend to get frustrated by the isolation. can you send me, or post, some details? - O From msvelu88 at gmail.com Tue Jun 17 00:48:05 2008 From: msvelu88 at gmail.com (msvelu) Date: Mon, 16 Jun 2008 21:48:05 -0700 (PDT) Subject: read the message Message-ID: Please sent your country nature picture in need it. plz ya From sjmachin at lexicon.net Tue Jun 17 09:43:55 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 17 Jun 2008 06:43:55 -0700 (PDT) Subject: go to specific line in text file References: <1xsmb1wlk1554$.gey53bzk6vfd$.dlg@40tude.net> <87iqw8tejf.fsf@mulj.homelinux.net> Message-ID: <662110f6-d4fd-4df8-8de3-209fffc2eb96@j33g2000pri.googlegroups.com> On Jun 17, 10:46 pm, Hrvoje Niksic wrote: > Patrick David writes: > > I am searching for a way to jump to a specific line in a text file, > > let's say to line no. 9000. Is there any method like file.seek() > > which leads me to a given line instead of a given byte? > > You can simulate it fairly easily, but it will internally read the > file line by line and will take the time roughly proportional to the > size of the file. > > from itertools import islice > def seek_to_line(f, n): The OP gave no impression that he'd restrict himself to one seek_to_line call per open. Perhaps you need f.seek(0) here otherwise seek_to_line(f, 20) seek_to_line(f, 10) will give something unexpected (like jumping forwards instead of backwards). > for ignored_line in islice(f, n - 1): > pass # skip n-1 lines > > f = open('foo') > seek_to_line(f, 9000) # seek to line 9000 > > # print lines 9000 and later > for line in f: > print line From bearophileHUGS at lycos.com Tue Jun 24 08:53:28 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 24 Jun 2008 05:53:28 -0700 (PDT) Subject: binary representation of an integer References: <14e14b5e-ce39-414a-a450-7c81baaabc3a@79g2000hsk.googlegroups.com> Message-ID: <34d32582-aabe-4de3-9138-2d2cb9b3306e@k30g2000hse.googlegroups.com> eliben: > Python's pack/unpack don't have the binary format for some reason, so > custom solutions have to be developed. One suggested in the ASPN > cookbook is:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 > However, it is very general and thus inefficient. Try mine, it may be fast enough for your purposes: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440528 Bye, bearophile From mathieu.malaterre at gmail.com Tue Jun 10 10:13:22 2008 From: mathieu.malaterre at gmail.com (mathieu) Date: Tue, 10 Jun 2008 07:13:22 -0700 (PDT) Subject: DICOM library References: <8c79237c-4e75-4908-93f2-393f750d90fc@m36g2000hse.googlegroups.com> Message-ID: <044894f8-a8b1-4533-8bc9-07de2f2752c6@x35g2000hsb.googlegroups.com> On Jun 10, 1:05 pm, ust... at gmail.com wrote: > Hi everybody! > I've been looking for a python library wich allows me to work with > with DICOM files, for medical image processing. Finding nothing at > first, evenctually i've find thegdcmlibrary, wich is suposed to be > for c developement, but they say that you can use it with python, as > "It is automatically wrapped to python (using swig)". So, the cuestion > is: how can I use this kind of library, wich is suposed to be used > with c, in python? When I download the tarball there ae only 2 .py > files. shall I install the whole library for using in C, and then try > to import thegdcmmodule in python? becouse i'm afraid it won't work. > Thanks in advance, and sorry for my english, wich is not very good > actually. Sorry for asking for something before trying everything, but > i'm almost desperate to find a library like that. You will get a tons more help directly at GDCM ML: https://lists.sourceforge.net/lists/listinfo/gdcm-developers The process is quite simple, GDCM is written using a limited subset of C++ (not C!) and using SWIG the API can be automagically wrap into another target language (in your case: python). If you download the binaries, you are all set (expect maybe adjusting your PYTHONPATH). Anyway this is highly GDCM oriented, and we should continue this discussion directly on the GDCM ML. HTH -Mathieu From Lie.1296 at gmail.com Thu Jun 19 08:22:11 2008 From: Lie.1296 at gmail.com (Lie) Date: Thu, 19 Jun 2008 05:22:11 -0700 (PDT) Subject: Simple Python class questions References: Message-ID: <9358fc58-0934-4d2f-8422-94cfa2601d06@h1g2000prh.googlegroups.com> On Jun 19, 6:54?pm, John Dann wrote: > A Python newbie, but some basic understanding of how classes, objects > etc work in eg VB.Net. However, I'm struggling a little to translate > this knowledge into the Python context. > > I'm trying to teach myself this aspect of Python by working up a trial > project, part of which calls for pulling in data from a serial data > connection at regular intervals. It looked sensible to place all the > comms procedures/functions in their own class and module and make > calls to those functions from an object instantiated in a main > controlling module. But I'm struggling to get this working - not sure > whether it's a fundamental misunderstanding of the use of classes in > Python, syntax errors pure and simple or, most likely, a combination > of both! > > Maybe I could provide some outline code as an illustration: > > Let's say I define the class in a module called comms.py. The class > isn't really going to inherit from any other class (except presumably > in the most primitive base-class sense, which is presumably automatic > and implicit in using the class keyword). Let's call the class > serial_link. So in comms.py I have: > > class serial_link: > ? ? ? ? def __init__(self): > ? ? ? ? ? ? ? ? Try > ? ? ? ? ? ? ? ? ? ? ? ? Import serial # the pyserial library > ? ? ? ? ? ? ? ? Except ImportException > ? ? ? ? ? ? ? ? ? ? ? ? #Error handling > > ? ? ? ? def openPort(self): > ? ? ? ? ? ? ? ? Try > ? ? ? ? ? ? ? ? ? ? ? ? #Code to try opening serial port > ? ? ? ? ? ? ? ? ? ? ? ? Return "Success" > ? ? ? ? ? ? ? ? Except SerialException > ? ? ? ? ? ? ? ? ? ? ? ? Return "Failure" > > Then in my separate main calling module I might have: > > Import comms > serlink=comms.seral_link ? ? #Create instance of serial_link class > print serlink.openPort > > The last line I'm hoping would print Success or Failure. But I just > seem to get some internal reference to the openPort function enclosed > in <>. > > So why doesn't it work please? I may be making multiple errors here > but as far as I can see the syntax seems right. For this particular > example, I don't need to pass any arguments from the > 'seriallink.openPort' function so haven't included any parentheses (or > are they mandatory even if empty?) I could go on with the explanations > etc, but it may be simplest to see if anyone can spot a howler > straight out. Yes they're mandatory even if there is no arguments, this is needed so python can differentiate between calling function and passing function objects. > TIA for anyone willing to help From svasulu2 at gmail.com Sat Jun 28 03:50:45 2008 From: svasulu2 at gmail.com (chinu) Date: Sat, 28 Jun 2008 00:50:45 -0700 (PDT) Subject: EARN $$$ IN EVERY MONTH. Message-ID: <53fc5aec-2175-4a7e-a235-f8a18913196c@u12g2000prd.googlegroups.com> GET + 1000$$$ @ MANY CASH OFFERS & ENJOY!!!!! Open the Site & Click the Banners = Easy forex + Get Web Hosting- Free Domains-Ring Tones-Freelance Jobs-Games-Surveys-Blogs-Dating sites- Surffing and hyips - E-Mail Marketing with or without Investment etc., http://srinubuisiness.blogspot.com/ From circularfunc at yahoo.se Tue Jun 3 17:11:30 2008 From: circularfunc at yahoo.se (cirfu) Date: Tue, 3 Jun 2008 14:11:30 -0700 (PDT) Subject: Webpy vs Django? References: <7db4dfb2-1e50-4a89-a47b-7356119b2741@r66g2000hsg.googlegroups.com> Message-ID: wow now i have django running. now i see... From bsagert at gmail.com Thu Jun 26 15:30:31 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Thu, 26 Jun 2008 12:30:31 -0700 (PDT) Subject: Help me optimize my feed script. Message-ID: <184ee312-e54f-48bd-ac9f-1eb7e1737fc7@v26g2000prm.googlegroups.com> I wrote my own feed reader using feedparser.py but it takes about 14 seconds to process 7 feeds (on a windows box), which seems slow on my DSL line. Does anyone see how I can optimize the script below? Thanks in advance, Bill # UTF-8 import feedparser rss = [ 'http://feeds.feedburner.com/typepad/alleyinsider/ silicon_alley_insider', 'http://www.techmeme.com/index.xml', 'http://feeds.feedburner.com/slate-97504', 'http://rss.cnn.com/rss/money_mostpopular.rss', 'http://rss.news.yahoo.com/rss/tech', 'http://www.aldaily.com/rss/rss.xml', 'http://ezralevant.com/atom.xml' ] s = '\n\nC:/x/test.htm\n' s += '\n' s += '\n\n
\n' for url in rss: d = feedparser.parse(url) title = d.feed.title link = d.feed.link s += '\n

'+ title +'

\n' # aldaily.com has weird feed if link.find('aldaily.com') != -1: description = d.entries[0].description s += description + '\n' for x in range(0,3): if link.find('aldaily.com') != -1: continue title = d.entries[x].title link = d.entries[x].link s += ''+ title +'
\n' s += '

\n\n' f = open('c:/scripts/myFeeds.htm', 'w') f.write(s) f.close print print 'myFeeds.htm written' From ccy56781 at gmail.com Mon Jun 16 23:50:15 2008 From: ccy56781 at gmail.com (ccy56781 at gmail.com) Date: Mon, 16 Jun 2008 20:50:15 -0700 (PDT) Subject: How to catch StopIteration? Message-ID: <5f27181e-f558-4760-b6a8-4fb7ef4c5848@a9g2000prl.googlegroups.com> I'm writing to see calcuration process. And so, I can't catch StopIteration... What is mistake? def collatz(n): r=[] while n>1: r.append(n) n = 3*n+1 if n%2 else n/2 yield r for i, x in enumerate(collatz(13)): try: last = x[:i+1] print x[:i+1] except StopIteration: print last.appnd(1) Output: [13] [13, 40] [13, 40, 20] [13, 40, 20, 10] [13, 40, 20, 10, 5] [13, 40, 20, 10, 5, 16] [13, 40, 20, 10, 5, 16, 8] [13, 40, 20, 10, 5, 16, 8, 4] [13, 40, 20, 10, 5, 16, 8, 4, 2] last.appnd(1) <= [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] # i want this list From mathieu.prevot at ens.fr Thu Jun 5 18:45:02 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Fri, 6 Jun 2008 00:45:02 +0200 Subject: gcc error in Mac OS X In-Reply-To: <12956470806041550k7e2815b4ga6823ee7967a8718@mail.gmail.com> References: <12956470806041550k7e2815b4ga6823ee7967a8718@mail.gmail.com> Message-ID: <3e473cc60806051545x5a7d89e4g3677fd84557cb1c6@mail.gmail.com> 2008/6/5 Zhaojie Boulder : > Hello, > I am new to Mac and used python in linux before. What I am trying to do is > to install "Ipython" and "PyCogent" in Mac OS X. > For PyCogent, after entering the package path, I typed "python setup.py > install". The results are as follows: > Didn't find Pyrex - will compile from .c files > running install > running build > running build_py > running build_ext > building 'cogent.align._compare' extension > gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd > -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DMACOSX > -I/usr/include/ffi -DENABLE_DTRACE -arch i386 -arch ppc -pipe > -I/Users/zhaojie/Downloads/PyCogent-1.0.1/include > -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 > -c cogent/align/_compare.c -o > build/temp.macosx-10.5-i386-2.5/cogent/align/_compare.o -w > unable to execute gcc: No such file or directory > error: command 'gcc' failed with exit status 1 > After google, I installed Xcode,but it did not help. Also, the Xcode folder > is not within "applications" folder, but a separate one parallel with > "applications". Dragging Xcode folder into the applications folder did not > make a difference, either. > Hope someone familiar with Mac can help me out. Normally gcc is installed in /usr/bin. If you type "which gcc", it should return "/usr/bin/gcc". Xcode is an IDE that use gcc or another compiler eg. icc the Intel compiler, hence if you move Xcode in the application folfer it won't change anything. You install Xcode by double clicking on a .pkg file from your Leopard DVD. You also can download gcc from the site and bootstrap/compile it. Cheers Mathieu From ram.rachum at gmail.com Tue Jun 17 09:39:38 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Tue, 17 Jun 2008 06:39:38 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> <4857AA74.2080205@electrooptical.net> Message-ID: <1015fc7a-9e2c-4025-a062-9f90311ed120@r66g2000hsg.googlegroups.com> On Jun 17, 3:13?pm, Phil Hobbs wrote: > ram.rac... at gmail.com wrote: > > On Jun 15, 7:43 pm, Peter Otten <__pete... at web.de> wrote: > >> ram.rac... at gmail.com wrote: > >>> On Jun 15, 6:58 pm, Christian Meesters wrote: > >>>>> I do need speed. Is there an option? > >>>> Mind telling us what you *actually* want to achieve? (What do you want to > >>>> calculate?) > >>>> Christian > >>> Physical simulations of objects with near-lightspeed velocity. > >> How did you determine that standard python floats are not good enough? > > > I have a physical system set up in which a body is supposed to > > accelerate and to get very close to lightspeed, while never really > > attaining it. After approx. 680 seconds, Python gets stuck and tells > > me the object has passed lightspeed. I put the same equations in > > Mathematica, again I get the same mistake around 680 seconds. So I > > think, I have a problem with my model! Then I pump up the > > WorkingPrecision in Mathematica to about 10. I run the same equations > > again, and it works! At least for the first 10,000 seconds, the object > > does not pass lightspeed. > > I concluded that I need Python to work at a higher precision. > > >> Everything beyond that is unlikely to be supported by the hardware and will > >> therefore introduce a speed penalty. > > > I have thought of that as well. However I have no choice. I must do > > these calculations. If you know of any way that is supported by the > > hardware, it will be terrific, but for now the slower things will have > > to do. > > You need to change your representation. ?Try redoing the algebra using > (c-v) as the independent variable, and calculate that. > > Cheers, > > Phil Hobbs That was suggested. Problem is, that sometimes the velocities are near zero. So this solution, by itself, is not general enough. From swetav02 at gmail.com Fri Jun 27 03:49:52 2008 From: swetav02 at gmail.com (swetav02 at gmail.com) Date: Fri, 27 Jun 2008 00:49:52 -0700 (PDT) Subject: Earn 25 US$ in just 5 mins . . . Message-ID: <3012cf2d-ee22-439b-b5f8-a8e0d7ceb4c5@f24g2000prh.googlegroups.com> Earn 25 US$ in just 5 mins . . . You can earn 25 US$ in just 5mins from now, please follow the simple steps: It's absolutely free to join. Step 01 CLICK HERE http://www.awsurveys.com/HomeMain.cfm?RefID=242423 A page will open Step 02 Click on "Create a Free Account" Step 03 Fill up the details and register. Step 04 After registration, go to home. You will see - The Following Surveys are Available: A list of surveys is given under this heading. Just click on those surveys and fill up the details. You will get paid. For More Details Plz contact me : ssweta.verma at yahoo.com Click Here For More Earning opportunities http://freemoneyteamonline.blogspot.com/ CLICK HERE TO VISIT MY WEBSITE http://www.sweta-verma.blogspot.com/ Regards Sweta Verma From Russ.Paielli at gmail.com Tue Jun 3 01:42:36 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 2 Jun 2008 22:42:36 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> Message-ID: <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> On Jun 2, 10:23 pm, alex23 wrote: > Then again, I have no issue with the current convention and personally > find the idea of adding a "private" keyword makes as much sense as > being able to syntactically define "model", "view" and "controller" > methods. Well, the designers of C++, Java, and Ada, to name just three very popular languages (well, two) seem to think it makes sense. But maybe you know more than they know. From george.sakkis at gmail.com Thu Jun 12 00:16:08 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 11 Jun 2008 21:16:08 -0700 (PDT) Subject: Simple and safe evaluator References: Message-ID: On Jun 11, 8:15?pm, bvdp wrote: > Matimus wrote: > > > The solution I posted should work and is safe. It may not seem very > > readable, but it is using Pythons internal parser to parse the passed > > in string into an abstract symbol tree (rather than code). Normally > > Python would just use the ast internally to create code. Instead I've > > written the code to do that. By avoiding anything but simple operators > > and literals it is guaranteed safe. > > Just wondering ... how safe would: > > ? ? ? ? ?eval(s, {"__builtins__":None}, {} ) > > be? From my testing it seems that it parses out numbers properly (int > and float) and does simple math like +, -, **, etc. It doesn't do > functions like int(), sin(), etc ... but that is fine for my puposes. > > Just playing a bit, it seems to give the same results as your code using > ast does. I may be missing something! Probably you do; within a couple of minutes I came up with this: >>> s = """ ... (t for t in 42 .__class__.__base__.__subclasses__() ... if t.__name__ == 'file').next()('/etc/passwd') ... """ >>> eval(s, {"__builtins__":None}, {} ) Traceback (most recent call last): File "", line 1, in File "", line 3, in IOError: file() constructor not accessible in restricted mode Not an exploit yet but I wouldn't be surprised if there is one. Unless you fully trust your users, an ast-based approach is your best bet. George George From news at prodata.co.uk Thu Jun 26 05:09:09 2008 From: news at prodata.co.uk (John Dann) Date: Thu, 26 Jun 2008 10:09:09 +0100 Subject: Komodo Edit newbie Q Message-ID: I'm learning Python using the Komodo Edit freeware code editor. One thing I'm finding a little confusing is that the code completion lists (what I would call Intellisense coming from a .Net background) are often very incomplete, especially with imported classes like wx. It's like KE can't look far enough into these classes to offer a comprehensive list of method etc options. I presume that I haven't possibly omitted some KE setup step that would give more detail to the code completion? If not then maybe this is just a limitation of the KE freeware (because it's free?). Does anyone know if say Komodo IDE offers more in the way of code completion (I know that it offers more things in the way of debugging etc, but it's code completion specifically that I'm asking about here). Or is one of the other Python IDEs maybe more capable when it comes to code completion? From lists at cheimes.de Sun Jun 15 16:30:04 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 15 Jun 2008 22:30:04 +0200 Subject: 32 bit or 64 bit? In-Reply-To: <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> Message-ID: ram.rachum at gmail.com wrote: > I have a physical system set up in which a body is supposed to > accelerate and to get very close to lightspeed, while never really > attaining it. After approx. 680 seconds, Python gets stuck and tells > me the object has passed lightspeed. I put the same equations in > Mathematica, again I get the same mistake around 680 seconds. So I > think, I have a problem with my model! Then I pump up the > WorkingPrecision in Mathematica to about 10. I run the same equations > again, and it works! At least for the first 10,000 seconds, the object > does not pass lightspeed. > I concluded that I need Python to work at a higher precision. I conclude that your algorithm is numerical wrong. It probably suffers from a rounding error which increases itself in every iteration. Increasing the precision doesn't solve your problem. It's only going to hide the fact that your algorithm doesn't do its job. Please don't get me wrong. I don't want to imply that you are an idiot who doesn't know what he is doing. :] Most likely you weren't taught how to write numerical sound algorithms. Let's all blame your school or university. *g* Numerics is a complex area and it took me more than a year to learn the basics. Don't be embarrassed! From ioceanio at gmail.com Fri Jun 13 21:27:34 2008 From: ioceanio at gmail.com (Ping Zhao) Date: Sat, 14 Jun 2008 01:27:34 +0000 Subject: struct unpack issue Message-ID: <20080614012734.30329619.ioceanio@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, I am writing a small program to decode MS bitmap image. When I use statements as follow, it works fine: header['sig'] = str(struct.unpack('2s', self.__read(src, 2))[0]) header['len'] = int(struct.unpack('1i', self.__read(src, 4))[0]) However, when I tried to rewrite them in short: header = struct.unpack('2s1i', self.__read(src, 6)) The Python interpreter in my Linux box came up with an error: ... header = struct.unpack('2s1i', self.__read(src, 6)) File "/usr/lib/python2.5/struct.py", line 87, in unpack return o.unpack(s) struct.error: unpack requires a string argument of length 8 It was weired that the required argument length increased to 8. Any idea on this? I am using a 32bit pentium-m and the picture file was stored in little-edian format. Sincerely, - -- Ping Zhao, PhD Student Dormitory: +82-(0)31-338-9503-0415 Information Engineering ioceanio at gmail.com Myongji University http://oceanio.wordpress.com GMT +09:00 (Seoul) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAkhTHocACgkQyOZNd2jjOpvTxgCfYnJKZqf4d3Em3xKDcAcpvK8i tx4AoI0WvEBv5tvoTQrQlMsj/3UO16t1 =SGnL -----END PGP SIGNATURE----- From ppayala at gmail.com Wed Jun 11 02:38:15 2008 From: ppayala at gmail.com (Payala) Date: Tue, 10 Jun 2008 23:38:15 -0700 (PDT) Subject: Cannot install python under Win32 References: <82d86466-0b90-47aa-af40-f52b52eb2526@d77g2000hsb.googlegroups.com> <484e258f$0$13627$9b622d9e@news.freenet.de> <0358337a-b147-4e38-b37f-a8119a39b6d7@j22g2000hsf.googlegroups.com> Message-ID: Hi Martin, I checked the md5 checksum, it is the following: d806af2312a33a8d817a6cc3d2ee7bed *python-2.5.2.msi which doesn't match with the one on the website ( http://www.python.org/download/releases/2.5.2/ ) d71e45968fdc4e206bb69fbf4cb82b2d python-2.5.2.msi (11294720 bytes, signature) File size doesn't match either ( it is 11.292.672 bytes ) I downloaded it again and I have the same md5. We have one of those "Panda GateDefender" gateways which look at everything you download and surf. It must be corrupting the file somehow. Anyways, I have found a co-worker who had a copy of Python 2.5, and I have installed it without problems. Thank you very much Pedro From grante at visi.com Wed Jun 11 19:11:28 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 11 Jun 2008 18:11:28 -0500 Subject: how to indent/dedent a region in emacs? References: Message-ID: <5badnSRqPZk9xs3VnZ2dnUVZ_hninZ2d@posted.visi> On 2008-06-11, Alexander Schmolck wrote: > Grant Edwards writes: > >> I've recently switched from Jed to Emacs for editing python >> source, and I'm still stumped as to how one indents or dedents >> a region of code. In Jed it's 'C-c <' or 'C-c >'. Google has >> found several answers, but none of them work, for example I've >> tried bot "C-c tab" and "C-c C-r" based on postings Google has >> found, but neither appears to actually _do_ anyting. > > In python-mode C-c > and C-c < should work as well. It does. I'm still baffled as to how I initially convinced myself it didn't... > (note that you have to download python-mode.el; I don't know > if the above also works with python.el which comes with emacs; Yes, it does. > C-h m will tell you which mode you're using) I don't remember installing python-mode.el, and what comes up when I hit C-h m matches what's in /usr/share/emacs/22.2/lisp/progmodes/python.el > Outside python-mode, you can use string-rectangle and > kill-rectangle, but that's inconvenient, so I've globally > bound the below functions to these keys (you can just use the > plain py-shift-region{-left,right} if you like them better). Thanks, I'll make a note of those... -- Grant Edwards grante Yow! Why is everything made at of Lycra Spandex? visi.com From nir1408 at gmail.com Fri Jun 6 04:13:28 2008 From: nir1408 at gmail.com (Nir) Date: Fri, 6 Jun 2008 01:13:28 -0700 (PDT) Subject: Cannot use Winpdb (or PyDev) to trace embedded Python script in MSVC++ application - ImportError: No module named _socket References: <8a739206-1f72-47ee-8a9f-50ec2c91bde2@j33g2000pri.googlegroups.com> Message-ID: <82989ee9-f9ce-4a88-84b8-c5a0fa2e784e@t12g2000prg.googlegroups.com> You seem to be having a problem with the import path of the embedded interpreter. I suppose the embedded interpreter includes some modules in a particular folder and _socket is not one of them. For the sake of debugging try adding the c:\python25\lib path to the sys.path variable of the interpreter before attempting to import rpdb2. Does this work? Nir On Jun 5, 2:52 pm, Chris8B... at gmail.com wrote: > I am embedding Python in a MSVC++ (2005) application. The application > creates some environment and then launches a Python script that will > call some functions exported from the MSVC++ application. > > I want to be able to debug the Python script by using a debug server, > likeWinpdb(winpdb.org). > > I use ActivePython 2.5.2.2, Microsoft Visual Studio 2005, andWinpdb > 1.3.8. > > When I launch a script like "e:>python test.py" everything is O'K and > I can useWinpdbto trace/debug. > > When I run the same script from the MSVC++ application, there is > always a complain "ImportError: No module named _socket". > > Here is the basic test script I use: > > > > def Process( something ): > print "\n\nStarted debugging\n=================\n" > #pydevd.settrace() > import rpdb2; rpdb2.start_embedded_debugger("1") > print "\n\nStopped debugging\n=================\n" > > if __name__ == '__main__': > Process( "test" ) > <<< > > In the MSVC++ application I tried many approaches, as suggested by > many people, and all of them work to launch the script, but none of > them works withWinpdb(or PyDev for Eclipse - same problem). Just for > completeness - here is one: > > > > PyRun_SimpleString("import sys"); > PyRun_SimpleString("import os"); > PyRun_SimpleString( "fullpath = os.path.abspath(\"E:/Test.py\")" ); > PyRun_SimpleString( "g = globals().copy()" ); > PyRun_SimpleString( "g['__file__'] = fullpath"); > PyRun_SimpleString( "execfile(fullpath, g) "); > <<< > > If I use pdb (import pdb + pdb.runcall(something) ) everything works > fine, but I need the performance and convinience ofWinpdb. > > What am I doing wrong? > > Your help is highly appreciated! > > Best regards, > Chris From jim.hefferon at gmail.com Tue Jun 24 10:31:53 2008 From: jim.hefferon at gmail.com (Jim) Date: Tue, 24 Jun 2008 07:31:53 -0700 (PDT) Subject: Sending information to a website References: Message-ID: <97ada989-630b-4fc3-ad4c-28e2410714bb@59g2000hsb.googlegroups.com> One way is to use a package that allows you to simulate being a browser: http://wwwsearch.sourceforge.net/mechanize/ . From bruno.42.desthuilliers at websiteburo.invalid Thu Jun 19 03:59:07 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 19 Jun 2008 09:59:07 +0200 Subject: Looking for lots of words in lots of files In-Reply-To: References: Message-ID: <485a11c5$0$17213$426a74cc@news.free.fr> brad a ?crit : > Just wondering if anyone has ever solved this efficiently... not looking > for specific solutions tho... just ideas. > > I have one thousand words and one thousand files. I need to read the > files to see if some of the words are in the files. I can stop reading a > file once I find 10 of the words in it. It's easy for me to do this with > a few dozen words, but a thousand words is too large for an RE and too > inefficient to loop, etc. Any suggestions? Full text indexing. From cwitts at gmail.com Sun Jun 29 10:03:34 2008 From: cwitts at gmail.com (Chris) Date: Sun, 29 Jun 2008 07:03:34 -0700 (PDT) Subject: Testing for Null? References: <268ac2770806281605n663670e9n29620f344ed66e4d@mail.gmail.com> Message-ID: On Jun 29, 3:12?am, c0mrade wrote: > Try something like this... > > list = ['lkdfjsldk', None, '', '0', 'slfkjsdlfj', 'lsdgjdlfg', False, True] > for n, it in enumerate(list): > ? ? if not it: print 'Error on this definition' > ? ? else: print '%d. %s' % (n+1, it) > > Results: > 1. lkdfjsldk > Error on this definition > Error on this definition > 4. 0 > 5. slfkjsdlfj > 6. lsdgjdlfg > Error on this definition > 8. True > > > > Alexnb wrote: > > > I am having a problem with a list value that is empty. I have a list of > > definitions called mainList. the 5th value in the list doesn't have > > anything > > in it. In this case, the values are definitions; also, in this case just > > the > > word cheese is defined. Here is my output to the console: > > > 5. ? a sprawling,weedy plant having small lavender or white flowers and > > round, flat, segmented fruits thought to resemble little wheels of cheese. > > 6. > > 7. ?an ingot or billet made into a convex, circular form by blows at the > > ends. > > > I've made it so where the numbers, the period, and two spaces follow that, > > then the definition. However, as you can see in 6, there is nothing. Here > > is > > the code to print all this: > > > n=0 > > > for x in mainList: > > ? ? if mainList[n] == "": > > ? ? ? ? print "Error on this definition" > > ? ? else: > > ? ? ? ? print str(n+1)+". ?"+str(mainList[n]) > > ? ? n=n+1 > > > Now the two "" is where I need to figure out if it is empty. What is up > > right now doesn't work; or at least doesn't give the desired result. So I > > need to know how to write the if statement to make it work. This should be > > simple, but I just don't know how to do it, never had this problem before. > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > View this message in context:http://www.nabble.com/Testing-for-Null--tp18175738p18176481.html > Sent from the Python - python-list mailing list archive at Nabble.com. myList = ['lkdfjsldk', None, '', '0', 'slfkjsdlfj', 'lsdgjdlfg', False, True] ['%s\t%s'%((i+1),element) if element else '%s\tError on this definition'%(i+1) for i,element in enumerate(myList)] From subhabrata.iisc at hotmail.com Fri Jun 13 03:24:31 2008 From: subhabrata.iisc at hotmail.com (subhabrata.iisc at hotmail.com) Date: Fri, 13 Jun 2008 00:24:31 -0700 (PDT) Subject: error showing file not found References: Message-ID: <2bbb14ce-a209-439e-bc88-d2897c354d3a@26g2000hsk.googlegroups.com> You can see the file whether it is loaded in C:\Python and you entered it correctly. Problem should not occur. Else you may refer Python docs for Error and Exception handling. Regs, Subhabrata. bio... at physics.iisc.ernet.in wrote: > Hi, > I am new to python.I have installed Biopython in Windows.I am working > using IDLE.When I want to get structure of local pdb file it is showing > error that "no such file or directory".Can anybody tell what is the > problem. > > > -- > This message has been scanned for viruses and > dangerous content by MailScanner, and is > believed to be clean. > > > -- > This message has been scanned for viruses and > dangerous content by MailScanner, and is > believed to be clean. From brendon at christian.net Thu Jun 19 02:11:13 2008 From: brendon at christian.net (Brendon Costa) Date: Wed, 18 Jun 2008 23:11:13 -0700 (PDT) Subject: How do i : Python Threads + KeyboardInterrupt exception References: <089f56d2-5e44-4161-b580-84881717bd05@w4g2000prd.googlegroups.com> <6cfbfaa2-293f-41d3-b544-fd47f05d0d36@j33g2000pri.googlegroups.com> Message-ID: I tested this a bit more. My windows example was incorrect. It should have used CTRL_C_EVENT. But even then, the problem is that the process will also close the console window from which it was called because of the 0. Also this requires that the process actually have a console and is not a GUI application. Is there some other method rather than a blocking "for line in fin:" that i can use for reading from a file like device that plays nicely with other threads asynchronously waking it up? Sorry for all the posts. I am giving updates as i look further into the problem. From tjreedy at udel.edu Mon Jun 23 16:57:39 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Jun 2008 16:57:39 -0400 Subject: 2to3 bug and question In-Reply-To: <6c95nbF3euiugU1@mid.dfncis.de> References: <6c95nbF3euiugU1@mid.dfncis.de> Message-ID: Helmut Jarausch wrote: > is this the right group to ask / report problems with python3.0 ? It is certainly a place. Given the number of bogus bug reports on bugs.python.org, asking here is often a good idea. In this and your other post, the problems you report look like probable bugs to me, so go ahead and report them on the bug list unless someone else has an explanation (within a day, say). 2to3 had probably been less well tested and debugged than either of the new releases, so testing it now is helpful. tjr From geoff.bache at jeppesen.com Mon Jun 23 11:33:33 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Mon, 23 Jun 2008 08:33:33 -0700 (PDT) Subject: Terminating processes on Windows (handles and IDs) Message-ID: <98b73a28-fa07-4eac-8f3c-aec65aa819fe@k37g2000hsf.googlegroups.com> Hi all, I've always wondered why os.kill isn't supported on Windows. I found a discussion somewhere from 2006 about this so it seems others have wanted it, but still nothing. So I have a half-baked solution involving calling "taskkill" on Windows Vista or "tskill" on Windows XP via the shell. I feel there has to be a better way. I'm also fairly confused about when I've got an ID and when I've got a handle. The subprocess module gives me IDs which the above programs accept, but other ways of spawning processes give me process handles (while referring to them as process IDs in the docs...) and I don't know how to kill a process with these. Besides, I've found an amazingly useful PyGTK method, gobject.child_watch_add, which does exactly what I want on UNIX but wants process handles on Windows. So I can't use it in conjunction with subprocess there, and if I use some other way of spawning processes I can't clean them up later. Is there any way to convert one of these numbers to the other? Or to get a process handle out of subprocess? (There must be one down there somewhere, surely?) Sorry for rambling a bit, am confused. Regards, Geoff Bache From Lie.1296 at gmail.com Tue Jun 10 11:45:59 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 10 Jun 2008 08:45:59 -0700 (PDT) Subject: EXE is very slow by starting (>10sec.) (build with PyInstaller) References: Message-ID: <18d1b258-06bf-463a-b799-8c76b8efa99d@q24g2000prf.googlegroups.com> On Jun 10, 5:29?pm, "Mark Delon" wrote: > Hi, > > My Python executable created with PyInstaller is too slow by starting... > It takes about 15 secs.!!! > > I am ?using PyQt4 libraries for creating my very simple GUI-application. > > -> How can I SPEED UP my executable ??? > -> Do you know some GOOD build switches? > > Thank you very much for every idea... > > Best Regards > > Mark > > -- > Der GMX SmartSurfer hilft bis zu 70% Ihrer Onlinekosten zu sparen! > Ideal f?r Modem und ISDN:http://www.gmx.net/de/go/smartsurfer Possibly you could use a splash screen and as have been said, you should load modules as late as possible (that means the some import statement is not positioned in the beginning of the code). You should reach the event loop as soon as possible. From kyosohma at gmail.com Tue Jun 10 14:50:29 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 10 Jun 2008 11:50:29 -0700 (PDT) Subject: problems with opening files due to file's path References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> Message-ID: <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> On Jun 10, 1:25?pm, "Thomas Morton" wrote: > maybe try string substitution... not sure if that's really the BEST way to > do it but it should work > > startfile(r"%s"%variable) I concur. That should work. A slightly more in depth example (assuming Windows): os.startfile(r'C:\Documents and Settings\%s\Desktop\myApp.exe' % username) or os.startfile(r'C:\Program Files\%s' % myApp) Hopefully this is what you are talking about. If you were referring to passing in arguments, than you'll want to use the subprocess module instead. > > -------------------------------------------------- > From: "Alexnb" > Sent: Tuesday, June 10, 2008 7:05 PM > To: > Subject: Re: problems with opening files due to file's path > > > > > Well, now i've hit another problem, this time being that the path will be > > a > > variable, and I can't figure out how to make startfile() make it raw with > > a > > variable, if I put startfile(r variable), it doesn't work and > > startfile(rvariable) obviously won't work, do you know how to make that > > work > > or better yet, how to take a regular string that is given and make every > > single "\" into a double "\\"? > Mike From swukong04 at gmail.com Sat Jun 21 08:34:56 2008 From: swukong04 at gmail.com (tom) Date: Sat, 21 Jun 2008 05:34:56 -0700 (PDT) Subject: some jordan shoes and something for wholesale Message-ID: <92ac942b-b4bc-42af-8fd5-852ffff17447@u6g2000prc.googlegroups.com> would you want to buy cheap something?welcome to www.wholenikee.cn From mc at mclaveau.com Sun Jun 1 04:52:13 2008 From: mc at mclaveau.com (MClaveau) Date: Sun, 1 Jun 2008 10:52:13 +0200 Subject: Merging ordered lists In-Reply-To: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> References: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> Message-ID: Hi! Use set (union). Example: la=[2,1,3,5,4,6] lb=[2,8,6,4,12] #compact: print list(set(la).union(set(lb))) #detail: s1 = set(la) s2 = set(lb) s3 = s1.union(s2) print list(s3) @-salutations Michel Claveau From simon at brunningonline.net Thu Jun 19 09:26:09 2008 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 19 Jun 2008 14:26:09 +0100 Subject: python script for tortoise cvs In-Reply-To: References: Message-ID: <8c7f10c60806190626i2dd28eacp50a4de20c2a6556d@mail.gmail.com> On Thu, Jun 19, 2008 at 2:14 PM, sandeep wrote: > hi > > we are using tortoise cvs and putty. i want to write a python script > to whom i can provide a tag and module.now what this script will do is > look for this specific tag and checks for whether its a individual tag > or its inside a branch.if its inside a branch then find out what is > the branch tag and then check out that branch for me else it checks > out that module with that tag. > > Actually the thing is i am not able to find the way how i will do it > and for where i have to look for the info.so any help will be > appreciated. I don't know if Tortoise is scriptable, but Subversion certainly is - - and nothing you mention is Tortoise specific. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From jonas.esp at googlemail.com Tue Jun 10 03:49:26 2008 From: jonas.esp at googlemail.com (Kless) Date: Tue, 10 Jun 2008 00:49:26 -0700 (PDT) Subject: Does the python library of Google Data API is truly free? References: <3ac654b2-61b4-44ce-8e03-75f2344d5869@s50g2000hsb.googlegroups.com> <6fb57ab1-b0d2-4b7d-93c1-b919ca0e51a0@i36g2000prf.googlegroups.com> <3a296d00-d4e0-4f03-b6b3-bef4c5d628dd@x35g2000hsb.googlegroups.com> <6b5mloF3aeui4U1@mid.uni-berlin.de> Message-ID: <18115776-edf7-41b8-a5e9-639847c57a6a@x41g2000hsb.googlegroups.com> On 9 jun, 22:46, "Diez B. Roggisch" wrote: > Kless schrieb: > > > On 9 jun, 21:40, Lie wrote: > >> Do you notice that the terms are for the SERVICE not for the SOFTWARE. > >> The terms for the service is quite reasonable, as I see it. > >> The software itself is governed by the Apache License 2.0, detailed > >> here:http://www.apache.org/licenses/LICENSE-2.0 > > > Well, it's used a free license to access to a service that is not free > > -it's owner and too restrictive-. And it isn't nothing reasonable that > > Google get many rights about your content, and that you have not any > > right about the rest of the content. > > > This goes against the free software, considering that a service is > > software. > > This is nonsense. If a hosting provider offers you free hosting based on > linux - and then goes out of business or is forced to charge money - do > you say "that's against free software?" I don't speak about hosting else rights about data, data that are entered by people: "By submitting, posting or displaying the content you give Google a perpetual, irrevocable, worldwide, royalty-free, and non- exclusive license to reproduce, adapt, modify, translate, publish, publicly perform, publicly display and distribute any Content which you submit, post or display on or through, the Services..." "You agree that this license includes a right for Google to make such Content available to other companies, organizations or individuals with whom Google has relationships for the provision of syndicated services..." > Or if they prohibit you to host malicious, offending or otherwise > problematic content served by the free apache - is that "against free > software?" Please, don't be demagogue. > A service is a service. It is offered as is, under whatever conditions > the provider likes it. A service or web service to follows being software. A software where is more easy to add restrictions, in this case those restrictions goes against the freedoms of the free software. > Offering a convenient way to access the service using a FOSS license is > good style. But you aren't forced to use that, you can write your own. > But that doesn't change the terms and conditions of the service itself. Offering access via Apache 2.0 -wich is not compatible with GPLv2- to a non-free service is a mortal trap where people are falling. From upton at virginia.edu Sun Jun 29 14:42:11 2008 From: upton at virginia.edu (Dan Upton) Date: Sun, 29 Jun 2008 14:42:11 -0400 Subject: Why is recursion so slow? In-Reply-To: References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> <5504f9ac0806290703h1bf44639jbfe5331c4a2d1369@mail.gmail.com> Message-ID: <5504f9ac0806291142v3fde4311h1c5cac16e7e55814@mail.gmail.com> On Sun, Jun 29, 2008 at 2:35 PM, Terry Reedy wrote: > > People should read posts to the end before replying, in case it actually > says what one thinks it should, but just in a different order than one > expected. Well, pardon me. From stef.mientki at gmail.com Fri Jun 6 18:45:07 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 07 Jun 2008 00:45:07 +0200 Subject: how to build a street with more than 1 house ? Message-ID: <4849BDF3.3010902@gmail.com> hello, In the code below, I can build a large street like this: large_street = house * 25 but not a small street. like this: small_street = 5 * house Why is this different ? And more interesting, how do I get the right results ? thanks, Stef Mientki class type_house ( object ) : def __init__( self, front_doors = 1 ) : self.front_doors = front_doors def __mul__ ( self, b ) : return type_house ( self.front_doors * b ) house = type_house () large_street = house * 25 print large_street.front_doors small_street = 5 * house print small_street.front_doors From gopalm at infotechsw.com Fri Jun 13 00:55:58 2008 From: gopalm at infotechsw.com (gopal mishra) Date: Fri, 13 Jun 2008 10:25:58 +0530 Subject: How to set directory in save as combo box Message-ID: <000a01c8cd11$c5566210$2fc513ac@pwit.com> TJG, I am trying to save a file, it is working fine. But if the file is not on the foreground while setting combo box directory, changing the value in the combo box by setLookIn() appear on the foreground window. I am using following functionality to save the file. def saveAsFile(fileName, path): while 1: # findWindow function returns a window class which contains all its childwindow and its components with handler id. saveaswindow = self.findWindow('Save As') saveaswindow._setLookIn(path) #save function save the file in specified path saveaswindow.save(False) def _setLookIn(self, path): try: #XXX set the directory in combo box win32gui.SendMessage(win32con.CB_DIR, 0, path) win32gui.SendMessage(win32con.WM_LBUTTONDOWN, 0, 0) win32gui.SendMessage(win32con.WM_LBUTTONUP, 0, 0) win32gui.SendMessage(win32con.WM_LBUTTONDOWN, 0, 0) win32gui.SendMessage(win32con.WM_LBUTTONUP, 0, 0) except : raise OpenSaveDialogError('Cannot set Look In path. %s is not a valid folder path.' % path) -----Original Message----- From: Tim Golden [mailto:mail at timgolden.me.uk] Sent: Thursday, June 12, 2008 1:22 PM Cc: python-list at python.org Subject: Re: How to set directory in save as combo box gopal mishra wrote: > In 'save as' dialog of window application, I am trying to set the path in > 'save in' combo box using python win32 programming. > How we can set the directory in the 'save in' combo box. There are several ways to display a "Save As" dialog. Can you post [a minimal version of] the code you're using so we can see what you're doing, please? TJG -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sun Jun 15 05:47:03 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Jun 2008 11:47:03 +0200 Subject: marshal.dumps quadratic growth and marshal.dump not allowing file-like objects References: Message-ID: bkustel at gmail.com wrote: > I'm stuck on a problem where I want to use marshal for serialization > (yes, yes, I know (c)Pickle is normally recommended here). I favor > marshal for speed for the types of data I use. > > However it seems that marshal.dumps() for large objects has a > quadratic performance issue which I'm assuming is that it grows its > memory buffer in constant increments. This causes a nasty slowdown for > marshaling large objects. I thought I would get around this by passing > a cStringIO.StringIO object to marshal.dump() instead but I quickly > learned this is not supported (only true file objects are supported). > > Any ideas about how to get around the marshal quadratic issue? Any > hope for a fix for that on the horizon? Thanks for any information. Here's how marshal resizes the string: newsize = size + size + 1024; if (newsize > 32*1024*1024) { newsize = size + 1024*1024; } Maybe you can split your large objects and marshal multiple objects to keep the size below the 32MB limit. Peter From stefan_ml at behnel.de Wed Jun 4 13:56:27 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 04 Jun 2008 19:56:27 +0200 Subject: Trying to extend Python with C: undefined reference to `Py_BuildValue' In-Reply-To: <045458d3-771b-459d-b5ef-21d8f3c08659@2g2000hsn.googlegroups.com> References: <045458d3-771b-459d-b5ef-21d8f3c08659@2g2000hsn.googlegroups.com> Message-ID: <4846D74B.1050905@behnel.de> spectrumdt at gmail.com wrote: > I am trying to extend Python with some C code. Have you considered using Cython instead of C? http://cython.org/ Stefan From geoff.bache at jeppesen.com Tue Jun 24 07:54:16 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Tue, 24 Jun 2008 04:54:16 -0700 (PDT) Subject: Terminating processes on Windows (handles and IDs) References: <98b73a28-fa07-4eac-8f3c-aec65aa819fe@k37g2000hsf.googlegroups.com> <36a78f0c-cbd4-45cd-a69f-44566f47b15f@b1g2000hsg.googlegroups.com> Message-ID: <4a8a46bc-119f-4e0e-85eb-f930130c2d31@25g2000hsx.googlegroups.com> Thanks for the tip. This does seem rather overkill to introduce all these dependencies just to be able to kill a process though... I've discovered that subprocess.Popen objects have a member "_handle" which is undocumented but appears to work, so I'm using that for now. Better suggestions gratefully received... Geoff > My way to do it is using excellent wmi module by Tim Golden, which > relies on Mark Hammond's pywin32 and Windows native wmi functionality. > Here is the link -http://tgolden.sc.sabren.com/python/wmi.html > Maybe, there is a more elegant way of doing that, but it works for me, > and i feel nice with wmi. From tim.arnold at sas.com Mon Jun 23 12:52:55 2008 From: tim.arnold at sas.com (Tim Arnold) Date: Mon, 23 Jun 2008 12:52:55 -0400 Subject: IDE on the level of Eclipse or DEVc++? References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> Message-ID: "cirfu" wrote in message news:563a8619-df8b-4de2-b9af-9ae70f6cedb4 at t54g2000hsg.googlegroups.com... > is there an IDE for python of the same quality as Eclipse or DEVC++? > > I am currently using the editor that coems iwth python and it is all > fine but for bigger projects it would be nice to have some way to > easier browse the projectfiles for example. why not eclipse itself, using the pydev plugin? --Tim From duncan.booth at invalid.invalid Sun Jun 8 05:54:42 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Jun 2008 09:54:42 GMT Subject: Can this be done with list comprehension? References: Message-ID: Lie wrote: > On Jun 8, 7:27?am, "Terry Reedy" wrote: >> "Karlo Lozovina" <_karlo_ at _mosor.net_> wrote in message >> >> news:Xns9AB7858EC056mosornet at 161.53.160.64... >> | I figured that out few minutes ago, such a newbie mistake :). The >> | fix I came up with is: >> | >> | ?result = ['something'] + [someMethod(i) for i in some_list] >> | >> | Are there any other alternatives to this approach? >> >> result = [something] >> result.extend(someMethod(i) for i in some_list) >> >> avoids creating and deleting an intermediate list > > or: > result = ['something'].extend(someMethod(i) for i in some_list) > > it also avoids intermediate list and is one line. and also throws the list away as soon as it creates it. Didn't you read earlier in this thread: list methods that mutate the list in-place return None. From musiccomposition at gmail.com Thu Jun 19 22:39:29 2008 From: musiccomposition at gmail.com (Benjamin) Date: Thu, 19 Jun 2008 19:39:29 -0700 (PDT) Subject: Python-3.0b1 build fails on Linux : _gestalt References: <6bupftF3d2d0kU1@mid.dfncis.de> Message-ID: <36ada6d7-747c-4ec6-9be8-cc5862f40c28@l64g2000hse.googlegroups.com> On Jun 19, 5:07?am, Helmut Jarausch wrote: > Hi, > > trying to build Python-3.0b1 on my Gentoo Linux box fails with > > Failed to find the necessary bits to build these modules: > _gestalt > > Looking at setup.py it seems that module '_gestalt' > is only needed on Darwin but my build on Linux fails > nevertheless. Your build has not failed. The _gestalt module just didn't build and was marked as missing. Note this has been fixed on the trunk. From dananrg at yahoo.com Sat Jun 21 09:58:47 2008 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: Sat, 21 Jun 2008 06:58:47 -0700 (PDT) Subject: Getting column names from a cursor using ODBC module? Message-ID: Is there any way to retrieve column names from a cursor using the ODBC module? Or must I, in advance, create a dictionary of column position and column names for a particular table before I can access column values by column names? I'd prefer sticking with the ODBC module for now because it comes standard in Python. I'm using Python 2.4 at the moment. Thanks. From mccredie at gmail.com Wed Jun 18 16:55:07 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 18 Jun 2008 13:55:07 -0700 (PDT) Subject: How to split a string containing nested commas-separated substrings References: <0b568cf3-ecce-4da0-9d23-1cbfe47a5fe7@m36g2000hse.googlegroups.com> <31c424a3-15cf-4ecb-bcf6-5edd24aa19ca@s50g2000hsb.googlegroups.com> Message-ID: <1fa7e725-c5ca-452f-8705-741f6e33d316@z72g2000hsb.googlegroups.com> On Jun 18, 10:54 am, Matimus wrote: > On Jun 18, 10:19 am, Robert Dodier wrote: > > > > > Hello, > > > I'd like to split a string by commas, but only at the "top level" so > > to speak. An element can be a comma-less substring, or a > > quoted string, or a substring which looks like a function call. > > If some element contains commas, I don't want to split it. > > > Examples: > > > 'foo, bar, baz' => 'foo' 'bar' 'baz' > > 'foo, "bar, baz", blurf' => 'foo' 'bar, baz' 'blurf' > > 'foo, bar(baz, blurf), mumble' => 'foo' 'bar(baz, blurf)' 'mumble' > > > Can someone suggest a suitable regular expression or other > > method to split such strings? > > > Thank you very much for your help. > > > Robert > > You might look at the shlex module. It doesn't get you 100%, but its > close: > > >>> shlex.split('foo, bar, baz') > > ['foo,', 'bar,', 'baz']>>> shlex.split( 'foo, "bar, baz", blurf') > > ['foo,', 'bar, baz,', 'blurf']>>> shlex.split('foo, bar(baz, blurf), mumble') > > ['foo,', 'bar(baz,', 'blurf),', 'mumble'] > > Using a RE will be tricky, especially if it is possible to have > recursive nesting (which by definition REs can't handle). For a real > general purpose solution you will need to create a custom parser. > There are a couple modules out there that can help you with that. > > pyparsing is one:http://pyparsing.wikispaces.com/ > > Matt Following up to my own post, Here is a working example that uses the built-in _ast module. I posted something similar the other day. This uses pythons own internal parser to do it for you. It works in this case because, at least from what you have posted, your syntax doesn't violate python syntax. [code] import _ast def eval_tuple(text): """ Evaluate a string representing a tuple of strings, names and calls, returns a tuple of strings. """ ast = compile(text, "", 'eval', _ast.PyCF_ONLY_AST) return _traverse(ast.body) def _traverse(ast): """ Traverse the AST returning string representations of tuples strings names and calls. """ if isinstance(ast, _ast.Tuple): return tuple(_traverse(el) for el in ast.elts) elif isinstance(ast, _ast.Str): return ast.s elif isinstance(ast, _ast.Name): return ast.id elif isinstance(ast, _ast.Call): name = ast.func.id args = [_traverse(x) for x in ast.args] return "%s(%s)"%(name, ", ".join(args)) raise SyntaxError() examples = [ ('foo, bar, baz', ('foo', 'bar', 'baz')), ('foo, "bar, baz", blurf', ('foo', 'bar, baz', 'blurf')), ('foo, bar(baz, blurf), mumble', ('foo', 'bar(baz, blurf)', 'mumble')), ] def test(): for text, expected in examples: print "trying %r => %r"%(text, expected) result = eval_tuple(text) if result == expected: print "PASS" else: print "FAIL, GOT: %r"%result if __name__ == "__main__": test() [/code] Matt From arslanburney at gmail.com Mon Jun 16 03:25:00 2008 From: arslanburney at gmail.com (arslanburney at gmail.com) Date: Mon, 16 Jun 2008 00:25:00 -0700 (PDT) Subject: Changing Colors in gnuplot.py Message-ID: <6f34751e-9eb3-4948-9aab-39e643a6c920@56g2000hsm.googlegroups.com> Hello, Could some1 tell me how u could change the colours of the different lines that you have plotted while using gnuplot.py. Also how to change the background colour, line thickness etc. Thnx From dsdale24 at gmail.com Sun Jun 29 08:31:38 2008 From: dsdale24 at gmail.com (Darren Dale) Date: Sun, 29 Jun 2008 05:31:38 -0700 (PDT) Subject: windows installers and license agreement Message-ID: <4559617d-0e0d-49de-b536-0de20ac07a65@k13g2000hse.googlegroups.com> Is it possible to create a windows installer using distutils that includes a prompt for the user to agree to the terms of the license? Thanks, Darren From martin at v.loewis.de Thu Jun 12 19:17:50 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 13 Jun 2008 01:17:50 +0200 Subject: Making wxPython a standard module? In-Reply-To: <48512f69$0$11262$c3e8da3@news.astraweb.com> References: <48512f69$0$11262$c3e8da3@news.astraweb.com> Message-ID: <4851ae9f$0$13597$9b622d9e@news.freenet.de> > Just out of curiosity, what are the chances of this happening (sort of like > what happened with sqlite)? As a starting point, the author(s) of wxPython would need to contribute it to Python (and then also give the PSF the permission to relicense it). If no such contribution is made, chances are zero. Somebody else contributing it in place of the authors is not acceptable - that somebody likely doesn't have the right to grant the proper license to the PSF, and it would also meant that the in-core version of wxPython forked from the official version, which would be unacceptable. In addition, a group of people (not necessarily the authors) would have to offer maintaining the in-core copy of wxPython, in the sense of keeping it synchronized with the stand-alone release, resolving bug reports related to the library (in particular wrt. portability), and so on. Again, with nobody offering maintenance, chances are again zero. For sqlite, both conditions were met, so it could be integrated. HTH, Martin From sjmachin at lexicon.net Sat Jun 28 02:20:24 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 27 Jun 2008 23:20:24 -0700 (PDT) Subject: problem compiling extensions with mingw References: <4973972a-e510-49b1-86bf-4ee4294842cd@m44g2000hsc.googlegroups.com> <73f6d268-252e-4de8-9839-4bab4c256d62@k13g2000hse.googlegroups.com> Message-ID: On Jun 28, 3:41 pm, eliben wrote: > On Jun 27, 3:10 pm, eliben wrote: > > > > > Hello, > > I'm trying to compile the minimal example fromhttp://en.wikibooks.org/wiki/Python_Programming/Extending_with_Cwith > > MinGW (latest version) and Python 2.5 (latest ActiveState binary > > install). When running the setup file, the following happens: > > > running build > > running build_ext > > building 'hello' extension > > writing build\temp.win32-2.5\Release\hello.def > > d:\mingw\bin\gcc.exe -mno-cygwin -shared -s build > > \temp.win32-2.5\Release\hellomo > > dule.o build\temp.win32-2.5\Release\hello.def -LC:\Python25\libs -LC: > > \Python25\P > > Cbuild -lpython25 -lmsvcr71 -o build\lib.win32-2.5\hello.pyd > > build\temp.win32-2.5\Release\hellomodule.o:hellomodule.c:(.text+0x3e): > > undefined > > reference to `_imp___Py_NoneStruct' > > build\temp.win32-2.5\Release\hellomodule.o:hellomodule.c:(.text+0x46): > > undefined > > reference to `_imp___Py_NoneStruct' > > collect2: ld returned 1 exit status > > error: command 'gcc' failed with exit status 1 > > > What's more, compiling the same extension with Visual Studio 2005 > > (without using distutils) works fine, the extension is loaded and ran > > successfully from Python. Any ideas about this error ? > > > Eli > > Problem solved:http://eli.thegreenplace.net/2008/06/28/compiling-python-extensions-w... libpython2?.a is now *supplied* with the official CPython distribution from www.python.org. The procedure that you followed is described in the manual: http://docs.python.org/inst/tweak-flags.html#SECTION000622000000000000000 Cheers, John From bruno.desthuilliers at gmail.com Mon Jun 30 17:13:30 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 30 Jun 2008 14:13:30 -0700 (PDT) Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> Message-ID: <80c529ed-8eb9-4c70-acbe-bfc3a89ebf3d@26g2000hsk.googlegroups.com> On 30 juin, 21:34, Mike wrote: > On Jun 30, 1:49 pm, "bruno.desthuilli... at gmail.com" > > wrote: > > > > Then what is so *good* about it, why embedding HTML into Python is not > > > good? > > > Who said embedding HTML in Python was bad ? Did you _carefully_ read > > John's question ?-) > > I should have say "why embedding HTML into Python is not good > enough?" ;=) Every time I took this road (be it only because I was too lazy to install and set up an existing templating package), I ended up writing yet another half-backed templating system. > > wrt/ what's so good about it: web designers are usually better at > > working with this approach (whatever scripting language embedded in > > html) than they are writing Python code - either as plain strings or > > using a more declarative syntax like the one provided by Stan or > > I keep reading this argument that some mythical 'web designers' are > usually > better at working with this abracadabra (TAL etc.). BTW, most of the > times > it is used by programmers :). Your experience. Not mine. In my shop, 80% of "template code" (from ZPT to raw PHP including various templating systems) is written by web designers. Same pattern in my previous shop FWIW. > > equivalent html generators. But nothing prevents you from using > > Mako's internals directly if you find it easier and more > > maintainable !-) > > Yea, that is a perfect and universal advise - use whatever fits you > best!;:=} Which is probably why all designers I know prefer the 'script in html' approach - it fits how *they* perceive dynamic html generation : it's html *plus* a couple simple instructions/special markup/etc to handle the dynamic part. From jr9445 at ATT.COM Fri Jun 13 11:34:26 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 13 Jun 2008 10:34:26 -0500 Subject: Iterate creating variables? In-Reply-To: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of tdahsu at gmail.com > Sent: Friday, June 13, 2008 11:11 AM > To: python-list at python.org > Subject: Iterate creating variables? > > I have twenty-five checkboxes I need to create (don't ask): > > self.checkbox1 = ... > self.checkbox2 = ... > . > . > . > self.checkbox25 = ... > > Right now, my code has 25 lines in it, one for each checkbox, since > these are all variables. > > Is there a way to write a loop so that I can have fewer lines of code > but still keep the variables? > > I've tried: > > for o in xrange(25): > self.checkbox[o] = ... > > which didn't work, and > > for o in xrange(25): > self.checkbox[''%d'%(o)] = ... > > which also didn't work. > > Both give the error message: "Attribute error: Main.App has no > attribute "checkbox"", which clearly indicates that I'm not keeping > the "variability" aspect I want. > > Is there a way? > > I appreciate any and all answers! Either store the checkboxes in an array or hash/dictionary. If that's not practical, then You can use strings to build the code and use eval to execute the string as code. Ex: for i in range(10): code = "%d + %d" % (i, i) print eval(code) From priyaavarmaa at gmail.com Fri Jun 27 04:30:09 2008 From: priyaavarmaa at gmail.com (lovely) Date: Fri, 27 Jun 2008 01:30:09 -0700 (PDT) Subject: Work 2 Hrs at Net EARN 10,000/- Rs Above Message-ID: <4aedd6d8-10cc-4e94-8b19-67513d3a985c@r37g2000prm.googlegroups.com> HAI.......... Guys this web site s very useful to you........... How This site helps.......... how to earn money form online...... In this site, you wil earn more than 10000/- Rs per month.... its true ....... just login this site and << EARN MONEY >> www.freeonlinedollers.blogspot.com www.freedollers.blogspot.com From timr at probo.com Thu Jun 5 03:15:14 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 05 Jun 2008 07:15:14 GMT Subject: readline() & seek() ??? References: <12655f64-33b1-4ab0-b6fb-294bfd2fa8c6@d45g2000hsc.googlegroups.com> Message-ID: DataSmash wrote: > >I have a text file that contains thousands of lines and each line is >256 characters long. > >This is my task: >For each line in the file, move to the 25th character, if the >character is a "T", >move to the 35th character of the line and read 5 characters from >there. >Capture these 5 characters and write them to a new text file, each 5 >characters separated by a comma. > >I appreciate your help! Did you even TRY this? Your task reads like pseudocode that translates virtually line-for-line to Python code. fout = open('outputfile.txt','w') for line in open('inputfile.txt'): if line[24] == 'T': fout.write( line[34:39] + ',' ) -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From google at mrabarnett.plus.com Tue Jun 24 07:13:02 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 24 Jun 2008 04:13:02 -0700 (PDT) Subject: calling a .exe from Python References: Message-ID: On Jun 24, 10:50?am, "evidentemente.yo" wrote: > Hi, i am trying to call a .exe from my .py file, i have found the exec > function, but i'm not sure of how to use it:S > > would it be f.e.: > > execl (mypath/myfile.exe,myfile,arg1,arg2,...) > > ???? > > Another question is, when i call my .exe with exec, i understand that > my .py file will stop running, and instead the new process will be > launched instead of it. Is it true? > Is there a way to launch my .exe without finishing my .py file?? > > thank you very much:) The exec function is for executing Python code. Have a look at the subprocess module. From rianby64 at hotmail.com Sat Jun 21 19:36:09 2008 From: rianby64 at hotmail.com (Byron Rios) Date: Sun, 22 Jun 2008 03:36:09 +0400 Subject: Python doc problem example: gzip module (reprise) Message-ID: >>> fileToCompress = open('finalcallejon.mb') >>> fileToStr = fileToCompress.read() >>> import gzip >>> fileZipped = gzip.GzipFile('finalcallejon.mb.gz', 'wb', 9) >>> fileZipped.write(fileToStr) >>> fileZipped.close() this may help you in http://mail.python.org/pipermail/python-list/2005-November/349718.html have a nice day -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Emoticon1.gif Type: image/gif Size: 257 bytes Desc: not available URL: From sam at mitre.org Tue Jun 10 15:44:54 2008 From: sam at mitre.org (Samuel Bayer) Date: Tue, 10 Jun 2008 15:44:54 -0400 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: Message-ID: <484ED9B6.5020006@mitre.org> Jonathan Gardner wrote: > Let me share my personal insight. I used Python for a mission-critical > application that needed, in effect, almost 100% uptime with superior > throughput. In other words, it was a very fine piece of art that > needed to be precise and correct. In the end, Python delivered, under > budget, under schedule, and with superbly low maintenance costs > (practically 0 compared to other systems written in Java and C). I > didn't have to use any of the features you mentioned, and I can't > imagine why you would need them. In fact, having them in the language > would encourage others to use them and make my software less reliable. At the risk of prolonging this thread, I'll add my own personal insight. I've spent a decent amount of time programming in Java, and the overhead of assigning a too-restrictive privacy level (which happens a lot, once privacy levels are in the language) has cost me an immense amount of time. I've lost count of how often I've had a software package which made an element non-public, in many cases for no apparent good reason, except that they hadn't anticipated the way I was going to use their code. Tracing down the consequences of these decisions, and trying to work around them, has been exceptionally time-consuming for me. You can say that I can go and modify the source code, as long as I have the source code, but that misses the point: I don't WANT to keep my own copy of the code, with the attended overhead in merging it with subsequent releases, etc. I'm not going to claim that data hiding has no purpose - it clearly addresses a set of concerns that programmers have about managing APIs. But I've found that its difficulties far outweigh its benefits. Sam Bayer From fuzzyman at gmail.com Thu Jun 5 08:51:25 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Thu, 5 Jun 2008 05:51:25 -0700 (PDT) Subject: Creating A Tuple From A List, Adding To Tuple As You Do References: Message-ID: <75463f10-4a5e-40f0-a972-4d09304d7d8b@e53g2000hsa.googlegroups.com> On Jun 5, 1:41 pm, Jeff Nyman wrote: > Greetings all. > > The subject line of this thread is probably one of the worst ever. I > was trying to encapsulate what I am doing. Based on my new-found > knowledge from another thread, I'm able to get a list of directories > and they come to me in the form of a list. Here is an example: > > from glob import glob > DC_List = glob('\\\\vcdcflx006\\Flex\\Sites\\*\\') > DC_List = ['Baltimore', 'Birmingham', 'Cincinnati', 'Cleveland', > LosAngeles'] > NEW_LIST = [(entry, '') for entry in DC_List] Does this get you what you want? Michael Foord http://www.ironpythoninaction.com > (Each element in the DC_List is actually a full directory path, but I > shortened that in the interest of clarity.) > > The problem is that I need to pass this list to a list control in a > wxWidgets application. In order to do that, I need to pass in a list > like this: > > [ ('Baltimore', ''), ('Birmingham', ''), ('Cincinnati', ''), > ('Cleveland', ''), ('LosAngeles', '') ] > > In other words, each element in the list is a tuple that has an empty > second string. The problem I'm having is in converting my list above > to be of this type. I can't do append because that (logically) puts > everything at the end. I did try this: > > for count in range(0, len(DC_List)): > DC_List.insert(count, '') > > Here I was thinking I could insert a '' into the right place after > each entry in the list. That doesn't quite work. Does anyone have an > idea of a good approach here? (I did search on tuples and lists and > while I found a lot of information about both, I couldn't find a > solution that did what I'm discussing above.) > > - Jeff From washakie at gmail.com Wed Jun 11 13:41:30 2008 From: washakie at gmail.com (john) Date: Wed, 11 Jun 2008 10:41:30 -0700 (PDT) Subject: [Tutor] python gui References: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> <333efb450806110818g134b930cj6e36f7bd79a9083@mail.gmail.com> <9d68e4e90806110818q18c57bd2v8b3219de9b2a1ca1@mail.gmail.com> Message-ID: W W wrote: > On Wed, Jun 11, 2008 at 10:18 AM, Gabriela Soares > wrote: > > How ? > > That's an extremely broad question, and shows little initiative, and > offers little information. Most of us are happy to help you solve > problems for free, but few, if any, are willing to write your programs > for free. > Ah, come on, it's not that broad, and easy to answer!! "With a lot of patience!" From gherron at islandtraining.com Mon Jun 2 20:52:11 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 02 Jun 2008 17:52:11 -0700 Subject: "Faster" I/O in a script In-Reply-To: <4cf35e78-8d19-4367-9e1d-efed2b5a360c@79g2000hsk.googlegroups.com> References: <4cf35e78-8d19-4367-9e1d-efed2b5a360c@79g2000hsk.googlegroups.com> Message-ID: <484495BB.50108@islandtraining.com> miller.paul.w at gmail.com wrote: > On Jun 2, 2:08 am, "kalakouentin" wrote: > > >> Do you know a way to actually load my data in a more >> "batch-like" way so I will avoid the constant line by line reading? >> > > If your files will fit in memory, you can just do > > text = file.readlines() > > and Python will read the entire file into a list of strings named > 'text,' where each item in the list corresponds to one 'line' of the > file. > No that won't help. That has to do *all* the same work (reading blocks and finding line endings) as the iterator PLUS allocate and build a list. Better to just use the iterator. for line in file: ... Gary Herron > -- > http://mail.python.org/mailman/listinfo/python-list > From bruno.42.desthuilliers at websiteburo.invalid Fri Jun 20 12:04:22 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 20 Jun 2008 18:04:22 +0200 Subject: An idiom for code generation with exec In-Reply-To: <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> Message-ID: <485bd4f8$0$30999$426a74cc@news.free.fr> eliben a ?crit : > On Jun 20, 9:17 am, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> eliben a ?crit :> Hello, >> >>> In a Python program I'm writing I need to dynamically generate >>> functions[*] >> (snip) >> >>> [*] I know that each time a code generation question comes up people >>> suggest that there's a better way to achieve this, without using exec, >>> eval, etc. >> Just to make things clear: you do know that you can dynamically build >> functions without exec, do you ? >> > > Yes, but the other options for doing so are significantly less > flexible than exec. Let's see... >>> But in my case, for reasons too long to fully lay out, I >>> really need to generate non-trivial functions with a lot of hard-coded >>> actions for performance. >> Just out of curiousity : could you tell a bit more about your use case >> and what makes a simple closure not an option ? > > Okay. > > I work in the field of embedded programming, and one of the main uses > I have for Python (and previously Perl) is writing GUIs for > controlling embedded systems. The communication protocols are usually > ad-hoc messages (headear, footer, data, crc) built on top of serial > communication (RS232). ok > The packets that arrive have a known format. For example (YAMLish > syntax): > > packet_length: 10 > fields: > - name: header > offset: 0 > length: 1 > - name: time_tag > offset: 1 > length: 1 > transform: val * 2048 > units: ms > - name: counter > offset: 2 > length: 4 > bytes-msb-first: true > - name: bitmask > offset: 6 > length: 1 > bit_from: 0 > bit_to: 5 > ... > > This is a partial capability display. Fields have defined offsets and > lengths, can be only several bits long, can have defined > transformations and units for convenient display. ok > I have a program that should receive such packets from the serial port > and display their contents in tabular form. I want the user to be able > to specify the format of his packets in a file similar to above. ok > Now, in previous versions of this code, written in Perl, I found out > that the procedure of extracting field values from packets is very > inefficient. I've rewritten it using a dynamically generated procedure > for each field, that does hard coded access to its data. For example: > > def get_counter(packet): > data = packet[2:6] > data.reverse() > return data > > This gave me a huge speedup, because each field now had its specific > function sitting in a dict that quickly extracted the field's data > from a given packet. ok. So if I get it right, you build the function's code as a string based on the YAML specification. If so, well, I can't think of anything really better[1] - at least *if* dynamically generated procedures are really better performance wise, which may *or not* be the case in Python. [1] except using compile to build a code object with the function's body, then instanciate a function object using this code, but I'm not sure whether it will buy you much more performance-wise. I'd personnaly prefer this because I find it more explicit and readable, but YMMV. > Now I'm rewriting this program in Python and am wondering about the > idiomatic way to use exec (in Perl, eval() replaces both eval and exec > of Python). Well... So far, the most pythonic way to use exec is to avoid using it - unless it's the right tool for the job !-) From karsten.heymann at blue-cable.net Thu Jun 5 09:55:20 2008 From: karsten.heymann at blue-cable.net (Karsten Heymann) Date: Thu, 05 Jun 2008 15:55:20 +0200 Subject: Creating A Tuple From A List, Adding To Tuple As You Do References: Message-ID: <87ej7casvr.fsf@ara.blue-cable.net> Hi Jeff, Jeff Nyman writes: > I did try this: > > for count in range(0, len(DC_List)): > DC_List.insert(count, '') On additional note: You can be quite sure you'll never have to iterate over the length of a list (or tuple) in python. Just iterate over the list itself: for DC in DC_List: # do something with DC. Yours Karsten From johnjsal at gmailNOSPAM.com Sat Jun 14 12:35:43 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sat, 14 Jun 2008 12:35:43 -0400 Subject: Was the move to Python 2.0 as big a deal? Message-ID: <4853f365$0$11601$607ed4bc@cv.net> Just curious if people put up any resistance to 2.0 like some people do for 3.0. Was it as big of a change in the language, or was the transition smoother? It seems silly for anyone to say they would prefer to stick with 1.x versions at this point, so perhaps we'll get there with 3.0 eventually too. Anyway, I'm just trying to figure out if the whole "I don't like 3.0" mentality (of some people, not all of course) is merely a result of it still being new and not even released yet, and will completely go away after a year or two; or if there really are such drastic changes that people won't want to adopt it at all. From gandalf at shopzeus.com Mon Jun 2 14:16:23 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 02 Jun 2008 20:16:23 +0200 Subject: platypus in page header Message-ID: <484438F7.7020106@shopzeus.com> Is it possible to use platypus in page header and footer? I need to create a document with long paragraphs but also I need to put tables and images in page header and multi line info in page footer with alignment etc. Thanks, Laszlo From cooperq at gmail.com Wed Jun 18 12:26:04 2008 From: cooperq at gmail.com (cooperq at gmail.com) Date: Wed, 18 Jun 2008 09:26:04 -0700 (PDT) Subject: Hrounding error References: Message-ID: On Jun 18, 8:02?am, "Jerry Hill" wrote: > On Wed, Jun 18, 2008 at 1:47 AM, ? wrote: > >>>> 234 - 23234.2345 > > -23000.234499999999 > > > This is not correct by my calculations. > > Python floating point operations use the underlying C floating point > libraries which, in turn, usually rely on the hardware's floating > point implementations. ?This Wikipedia article talks about how those > values are usually stored and manipulated:http://en.wikipedia.org/wiki/IEEE_floating-point_standard > > So, which IEEE double precision floating point value would you like > instead? ?As far as I understand it, these are your two choices: > > 'ba490c020f76d6c0' = -23000.234499999999 > 'bb490c020f76d6c0' = -23000.234500000002 > > Alternatively, investigate the Decimal module, but keep in mind that > it can have the same sorts of issues, just on different numbers. > Compare, for instance: > > >>> (1.0/3.0) * 3.0 > > 1.0 > > >>> from decimal import Decimal > >>> ( Decimal('1.0')/Decimal('3.0') ) * Decimal('3.0') > > Decimal("0.9999999999999999999999999999") > > > > -- > Jerry So it seems then that python might not be very good for doing precision floating point work, because there is a good chance its floating points will be off by a (very small) amount? Or is there a way to get around this and be guaranteed an accurate answer? From timr at probo.com Thu Jun 5 01:33:52 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 05 Jun 2008 05:33:52 GMT Subject: can python do some kernel stuff? References: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> <48366cfa$0$15168$607ed4bc@cv.net> <28c432f0-657c-4272-8cd4-a9081b013279@w5g2000prd.googlegroups.com> <69nigsF3499pqU2@mid.uni-berlin.de> <4836994e$0$11625$607ed4bc@cv.net> <69nls3F344g2cU1@mid.uni-berlin.de> <4836a876$0$11623$607ed4bc@cv.net> Message-ID: <5iue44930uncm7gjv4r90fqc4alr6hhasr@4ax.com> sturlamolden wrote: > >On Jun 4, 12:41 am, Ethan Furman wrote: > >> the kernel itself, *is* kernel coding. And as wonderful as Python is, >> it is *not* for kernel coding. > >Not in its present form, no, it would take some porting. But aside >from that, is there any reason one could not embed a python >interpreter in the kernel? Not at all. Microsoft Research has issued a preview release of an operating system called "Singularity" where the entire kernel and all drivers are written as managed code. Since Python can now be used to write managed code (via IronPython), Q.E.D. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From zephyrfalcon!NO_SPAM! at gmail.com Fri Jun 27 18:32:46 2008 From: zephyrfalcon!NO_SPAM! at gmail.com (Hans Nowak) Date: Fri, 27 Jun 2008 18:32:46 -0400 Subject: Do I need "self" and "other"? In-Reply-To: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> Message-ID: Kurda Yon wrote: > Hi, > > I found one example which defines the addition of two vectors as a > method of a class. It looks like that: > > class Vector: > def __add__(self, other): > data = [] > for j in range(len(self.data)): > data.append(self.data[j] + other.data[j]) > return Vector(data) > > In this example one uses "self" and "other". Does one really need to > use this words? And, if yes, why? I have replaced "self" by "x" and > "other" by "y" and everything looks OK. Is it really OK or I can have > some problem in some cases? You can use whichever (valid) names you want, but in general 'self' and 'other' are used for clarity. In this case, they indicate the vector that is operated on ("self") and another vector ("other"). Using 'x' and 'y' would be less clear here. -- Hans Nowak (zephyrfalcon at gmail dot com) http://4.flowsnake.org/ From johnjsal at gmailNOSPAM.com Fri Jun 27 23:10:53 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Fri, 27 Jun 2008 23:10:53 -0400 Subject: Using just the Mako part of Pylons? In-Reply-To: <4865a871$0$5024$607ed4bc@cv.net> References: <4865a871$0$5024$607ed4bc@cv.net> Message-ID: <4865abc7$0$5025$607ed4bc@cv.net> John Salerno wrote: > I just installed Pylons onto my hosting server so I could try out > templating with Mako, but it seems a little more complicated than that. > From the look of it all, the site seems to want a full Pylons > application. Is it possible to just use regular HTML files with a bit of > the Mako language embedded, or will I actually have to use all aspects > of Pylons? > > In other words, can I use *just* Mako (sort of like as a replacement for > PHP) without having to use a framework? > > For example, I'd like to just test out the <%include /> tag and see it > in action, but the site doesn't seem to be looking for a regular HTML > file (like index.html), it seems to want a "controller". So is Pylons > overkill for just this? How would I try out *just* Mako? > > Thanks! Ok, I figured out how to get it to just use regular HTML files as if it were a regular, static site. However, the include directive I used didn't seem to work. I used: <%include file="separate.html"/> And it just shows that text in the browser. Am I missing something? From mark.deverter at dads.state.tx.us Thu Jun 26 13:09:38 2008 From: mark.deverter at dads.state.tx.us (Deverter,Mark) Date: Thu, 26 Jun 2008 12:09:38 -0500 Subject: I Need A Placeholder Message-ID: I typically use pass for a place holder. try: # Do some code here var = 1 # For example except: pass HTH, Mark -----Original Message----- From: python-list-bounces+mark.deverter=dads.state.tx.us at python.org [mailto:python-list-bounces+mark.deverter=dads.state.tx.us at python.org] On Behalf Of Ampedesign Sent: Thursday, June 26, 2008 12:04 PM To: python-list at python.org Subject: I Need A Placeholder I'm trying to build a try/except case, and I want to have the except function like such: try: # Do some code here var = 1 # For example except: #Do nothing here The only problem is if I leave a comment only in the except block, I get an error back saying that the except block is not properly formatted, since it has no content other than a comment. So if anyone could suggest some code to put there as a placeholder that would be wonderful. -- http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Thu Jun 19 21:03:26 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 19 Jun 2008 18:03:26 -0700 (PDT) Subject: Pattern Matching Over Python Lists References: <21a9c996-75ff-4f7c-b7e9-c94247f65674@c58g2000hsc.googlegroups.com> <87ej6w6ql6.fsf@internal.daycos.com> <61ea5c70-4352-4d2f-a0ef-62eb76ba933a@m36g2000hse.googlegroups.com> <6e31e7ef-3eea-4edc-88bc-471e78dbb46c@i76g2000hsf.googlegroups.com> Message-ID: <1379d69a-af3f-4e06-8bd4-b85e0213399a@g16g2000pri.googlegroups.com> On Jun 20, 10:45 am, Chris wrote: > On Jun 17, 1:09 pm, bearophileH... at lycos.com wrote: > > > Kirk Strauser: > > > > Hint: recursion. Your general algorithm will be something like: > > > Another solution is to use a better (different) language, that has > > built-in pattern matching, or allows to create one. > > > Bye, > > bearophile > > Btw, Python's stdlib includes a regular expression library. I'm not > sure if you're trolling or simply unaware of it, but I've found it > quite adequate for most tasks. Kindly consider a third possibility: bearophile is an experienced Python user, has not to my knowledge exhibited any troll-like behaviour in the past, and given that you seem to be happy using the re module not on strings but on lists of integers, may have been wondering whether *you* were trolling or just plain confused but just too polite to wonder out loud :-) From sylvain.vivien at gmail.com Fri Jun 6 09:31:51 2008 From: sylvain.vivien at gmail.com (Sylvain) Date: Fri, 6 Jun 2008 06:31:51 -0700 (PDT) Subject: cgi, parse_header and semi-colon Message-ID: Hi, I'm playing with Google App Engine and during my tests it seems that there is a bug in cgi. parse_header function. If we upload a file with a semi-colon (i.e : "C:/my;file.jpg") : cgi.FieldStorage.filename returns only "my" everything after the semi- colon is missing Is it a bug or i'm missing something ? Regards From toby at tobiah.org Wed Jun 4 15:49:29 2008 From: toby at tobiah.org (Tobiah) Date: Wed, 04 Jun 2008 12:49:29 -0700 Subject: Exit from os.chroot() References: Message-ID: >> So you need some programs in your chroot: Then put a directory >> usr/bin into the chroot directory and bind the system's /usr/bin >> there: > >> mount --bind /usr/bin $chroot/usr/bin > > It is better to make copies of the needed binaries and libraries, > and *only* them. Or symbolic links, of course. Also, wouldn't links prevent the process from puffing actual binaries in /usr/bin? ** Posted from http://www.teranews.com ** From rotlaus at gmail.com Thu Jun 26 07:06:53 2008 From: rotlaus at gmail.com (Rotlaus) Date: Thu, 26 Jun 2008 04:06:53 -0700 (PDT) Subject: extend getattr() Message-ID: <0d1da457-b026-4e38-824b-c8cbde172bf7@m36g2000hse.googlegroups.com> Hello, lets assume i have some classes: class A(object): def __init__(self): b = B() class B(object): def __init__(self): c = C() class C(object): def __init__(self): pass and now i wanna do something like this: a=A() c=getattr(a, 'b.c') I know this doesn't work, but what can i do to get this or a similar functionality to get it work for this sample and for even more nested classes? Kind regards, Andre From sir.heyhey at gmail.com Mon Jun 9 01:40:38 2008 From: sir.heyhey at gmail.com (Ivan Velev) Date: Sun, 8 Jun 2008 22:40:38 -0700 (PDT) Subject: need help with timezone conversion (unexpected side effect of time.mktime ??) References: <8ea566b6-9562-4ee1-8c1a-5dffea553825@j22g2000hsf.googlegroups.com> <3a6e930b-9652-48c5-89d7-1d0560687a21@d45g2000hsc.googlegroups.com> <4c8fb0bb-3e92-4b1b-b5c8-ec0b86e8934e@e53g2000hsa.googlegroups.com> Message-ID: <28654738-beac-443a-9c3e-677c17d442ad@f63g2000hsf.googlegroups.com> Thanks Paul, I have identified the "problem" - because of daylight change this particular timesamp was observed twice in Europe/Sofia. Here is the GMT-to-local-time conversion: +------------+---------------------+---------------------+ | gmt_stamp | gmt_time | local_time | +------------+---------------------+---------------------+ | 1130631000 | 2005-10-30 00:10:00 | 2005-10-30 03:10:00 | +------------+---------------------+---------------------+ | 1130634600 | 2005-10-30 01:10:00 | 2005-10-30 03:10:00 | +------------+---------------------+---------------------+ | 1130638200 | 2005-10-30 02:10:00 | 2005-10-30 04:10:00 | +------------+---------------------+---------------------+ | 1130641800 | 2005-10-30 03:10:00 | 2005-10-30 05:10:00 | +------------+---------------------+---------------------+ When you do local-time-to-GMT conversion you can expect any of those two timestamps. I missed that initially :( (I was sure that local time has "one hour gap" and not "one hour of overlapping time") > and I'd recommend the datetime module for any serious work with dates and times. Last time when I was playing with TZ conversions, I was not able to do anything using datetime module - it seems that one needs to define his own set of timezones (+ all the details) to get it working ... Am I wrong ? Can you show me how do accomplish the same conversion using datetime module ? Thanks again, Ivan From mensanator at aol.com Sun Jun 8 12:11:56 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 8 Jun 2008 09:11:56 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> <484ad07b$0$25721$607ed4bc@cv.net> <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> <484b3464$0$25724$607ed4bc@cv.net> <09d98480-c834-42bd-b97f-481133be9cb4@s50g2000hsb.googlegroups.com> <77d2d56a-7ab6-4d33-81d4-b15cc8fc63d6@u36g2000prf.googlegroups.com> Message-ID: On Jun 8, 4:04?am, Lie wrote: > On Jun 8, 8:56?am, Mensanator wrote: > > > > > > > On Jun 7, 8:22?pm, John Salerno wrote: > > > > Mensanator wrote: > > > > What I DID say was that how the builtins actually > > > > work should be understood and it APPEARED that the > > > > OP didn't understand that. Maybe he understood that > > > > all along but his example betrayed no evidence of > > > > that understanding. > > > > Well, the truth is that I know zip truncates to the shorter of the two > > > arguments, > > > Ok, sorry I thought otherwise. > > > > and also in my case the two arguments would always be the > > > same length. > > > Yes, because you're controlling the source code. > > But since lists are mutable, source code literals > > don't always control the length of the list. > > Since when source code literals ever control the length of a list? Isn't score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] considered a literal? > What controls the length of the list is the semantic meaning of the > list, Wha do you mean by that? The list contains 11 objects. How could the length be any different? > in some cases it just makes no sense that the list would ever > have different length. And in such case there won't be any problem, will there? Is that a good habit to teach a newbie? To write code that only works for special cases? > > (snip)- Hide quoted text - > > - Show quoted text - From Sengly.Heng at gmail.com Sat Jun 14 02:13:13 2008 From: Sengly.Heng at gmail.com (Sengly) Date: Fri, 13 Jun 2008 23:13:13 -0700 (PDT) Subject: Finding a sense of word in a text References: <6ea04a99-abb6-4de0-9867-7fec53d9fd68@2g2000hsn.googlegroups.com> Message-ID: <511ab811-0cb8-4b38-8cdc-aa9e44577413@i18g2000prn.googlegroups.com> Thanks a lot everyone. I appreciate your suggestion. But still, I could not find a simple way using wordnet since each term might have several part of speech and each one of them can have many senses. What I want is simply the list of synonyms of each term with their popularity score in English text. Once again, thank you. Best regards, Sengly From david at boddie.org.uk Mon Jun 23 16:12:08 2008 From: david at boddie.org.uk (David Boddie) Date: Mon, 23 Jun 2008 22:12:08 +0200 Subject: py2exe, PyQT, QtWebKit and jpeg problem References: <2b292f88-db2d-4fd3-a4b2-de72ff1b5387@c58g2000hsc.googlegroups.com> Message-ID: On Monday 23 June 2008 15:02, Carbonimax wrote: > If I copy the dll in the dist directory, and I use QPluginLoader() and > load(), > it does work in the .py but it doesn't in .exe made with py2exe > > my code : > dll = QPluginLoader(path_to_dll) > res = dll.load() > > res == true in the .py > res == false in the .exe > > :-/ Maybe py2exe builds executables that can't load DLLs in this way. In any case, it might be worth asking about this on the PyQt mailing list http://www.riverbankcomputing.com/mailman/listinfo/pyqt or on the py2exe mailing list https://lists.sourceforge.net/lists/listinfo/py2exe-users where there may well be people who have solved this problem independently. David From monika.modi85 at rediffmail.com Thu Jun 5 07:42:24 2008 From: monika.modi85 at rediffmail.com (monika) Date: Thu, 5 Jun 2008 04:42:24 -0700 (PDT) Subject: Update Message-ID: <1cce6d4a-a9a3-42d4-aa61-58597dbf5fd9@f24g2000prh.googlegroups.com> http://windowsxpprotips.blogspot.com/ windows xp pro tips http://thebesthealthtips.blogspot.com/ the best health tips http://unwealthyhabits.blogspot.com/ unwealthy habits http://beautytipsfornewu.blogspot.com/ beauty tips for new u http://datingattractivewomen.blogspot.com/ how to attract a women 4 date http://gta4-grandtheftauto.blogspot.com/ gta4 grand theft Auto http://tastyhealthrecipes4u.blogspot.com/ Tasty Healthy Recipes For Healthy Body and mind http://aboutreligionphilosophy.blogspot.com/ About religion and philosophy http://storiesbedtime4u.blogspot.com/ Naughty Bed Time Stories http://bollywoodhollywoodnews.blogspot.com/ Bollywood Hollywood News And Gossip From arslanburney at gmail.com Thu Jun 19 01:46:15 2008 From: arslanburney at gmail.com (J-Burns) Date: Wed, 18 Jun 2008 22:46:15 -0700 (PDT) Subject: Doc tests in Python Message-ID: <7d08373e-7b52-4c6a-a77f-29d3f9fc5672@59g2000hsb.googlegroups.com> Hello. Im new to using doctests in python. Could some1 tel me how to use doctests if i have a constructor in my code? From M8R-yfto6h at mailinator.com Sat Jun 7 10:24:57 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Sat, 7 Jun 2008 07:24:57 -0700 Subject: time module methods give an am or pm value ? References: <2309efff-5c6b-4434-a2cd-01c3fee86fee@l42g2000hsc.googlegroups.com> Message-ID: "dj" wrote in message news:2309efff-5c6b-4434-a2cd-01c3fee86fee at l42g2000hsc.googlegroups.com... > Hello again, > > Does anyone know which method in the time module will generate and am > or pm ? > If none of the method will do this for me. Can I produce the value on > my own ? > Any suggestions ? >>> from time import * >>> strftime('%I:%M:%S %p',localtime(time())) '07:23:24 AM' >>> strftime('%I:%M:%S %p',gmtime(time())) '02:23:39 PM' -Mark From mathieu.prevot at ens.fr Thu Jun 5 19:07:03 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Fri, 6 Jun 2008 01:07:03 +0200 Subject: gcc error in Mac OS X In-Reply-To: <3e473cc60806051545x5a7d89e4g3677fd84557cb1c6@mail.gmail.com> References: <12956470806041550k7e2815b4ga6823ee7967a8718@mail.gmail.com> <3e473cc60806051545x5a7d89e4g3677fd84557cb1c6@mail.gmail.com> Message-ID: <3e473cc60806051607v720938dbp55d4a3981e27e31d@mail.gmail.com> 2008/6/6 Mathieu Prevot : > 2008/6/5 Zhaojie Boulder : >> Hello, >> I am new to Mac and used python in linux before. What I am trying to do is >> to install "Ipython" and "PyCogent" in Mac OS X. >> For PyCogent, after entering the package path, I typed "python setup.py >> install". The results are as follows: >> Didn't find Pyrex - will compile from .c files >> running install >> running build >> running build_py >> running build_ext >> building 'cogent.align._compare' extension >> gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd >> -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DMACOSX >> -I/usr/include/ffi -DENABLE_DTRACE -arch i386 -arch ppc -pipe >> -I/Users/zhaojie/Downloads/PyCogent-1.0.1/include >> -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 >> -c cogent/align/_compare.c -o >> build/temp.macosx-10.5-i386-2.5/cogent/align/_compare.o -w >> unable to execute gcc: No such file or directory >> error: command 'gcc' failed with exit status 1 >> After google, I installed Xcode,but it did not help. Also, the Xcode folder >> is not within "applications" folder, but a separate one parallel with >> "applications". Dragging Xcode folder into the applications folder did not >> make a difference, either. >> Hope someone familiar with Mac can help me out. > > Normally gcc is installed in /usr/bin. If you type "which gcc", it > should return "/usr/bin/gcc". Xcode is an IDE that use gcc or another > compiler eg. icc the Intel compiler, hence if you move Xcode in the > application folfer it won't change anything. You install Xcode by > double clicking on a .pkg file from your Leopard DVD. > > You also can download gcc from the site and bootstrap/compile it. Note that you don't need to install Xcode in the "right place", it is normally installed in /Developer, and installs gcc and other files in /usr/bin /usr/share etc. In general, try "locate prog" to try to find where is prog, and check if the binary prog's path is in your PATH. eg. you can compile and install a gnu tool by ./configure --prefix=$HOME && make && make install, and the binaries will be installed in ~/bin/. If you don't have ~/bin/ in your PATH, it won't execute. Adding 'export PATH="$PATH:$HOME/bin:"' in your .bashrc will solve the problem (or 'setenv PATH "$PATH:$HOME/bin:' in your .tcshrc) Using --prefix=$HOME allow you to run and install your binaries and libraries. You can do this for a group of users without root access, so you can share, or preserve your OS bin/lib/include/share easily, or allow alternative use of several versions of libraries/binaries etc. Other possibilities are the chroot and the sophisticated FreeBSD jails. Google for them to know more. Hope that helps, Mathieu From eliben at gmail.com Fri Jun 20 15:41:08 2008 From: eliben at gmail.com (eliben) Date: Fri, 20 Jun 2008 12:41:08 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> <485bd4f8$0$30999$426a74cc@news.free.fr> Message-ID: > [1] except using compile to build a code object with the function's > body, then instanciate a function object using this code, but I'm not > sure whether it will buy you much more performance-wise. I'd personnaly > prefer this because I find it more explicit and readable, but YMMV. > How is compiling more readable than exec - doesn't it require an extra step ? You generate code dynamically anyway. Eli From nagle at animats.com Sat Jun 21 12:51:31 2008 From: nagle at animats.com (John Nagle) Date: Sat, 21 Jun 2008 09:51:31 -0700 Subject: urllib (54, 'Connection reset by peer') error In-Reply-To: References: <92ecee86-ba92-4f14-b4f8-05064ef5406c@f63g2000hsf.googlegroups.com> Message-ID: <485d2dd9$0$17222$742ec2ed@news.sonic.net> Tim Golden wrote: > chrispoliquin at gmail.com wrote: >> Thanks for the help. The error handling worked to a certain extent >> but after a while the server does seem to stop responding to my >> requests. >> >> I have a list of about 7,000 links to pages I want to parse the HTML >> of (it's basically a web crawler) but after a certain number of >> urlretrieve() or urlopen() calls the server just stops responding. >> Anyone know of a way to get around this? I don't own the server so I >> can't make any modifications on that side. > > I think someone's already mentioned this, but it's almost > certainly an explicit or implicit throttling on the remote server. > If you're pulling 7,000 pages from a single server you need to > be sure that you're within the Terms of Use of that service, or > at the least you need to contact the maintainers in courtesy to > confirm that this is acceptable. > > If you don't you may well cause your IP block to be banned on > their network, which could affect others as well as yourself. Interestingly, "lp.findlaw.com" doesn't have any visible terms of service. The information being downloaded is case law, which is public domain, so there's no copyright issue. Some throttling and retry is needed to slow down the process, but it should be fixable. Try this: put in the retry code someone else suggested. Use a variable retry delay, and wait one retry delay between downloading files. Whenever a download fails, double the retry delay and try again; don't let it get bigger than, say, 256 seconds. When a download succeeds, halve the retry delay, but don't let it get smaller than 1 second. That will make your downloader self-tune to the throttling imposed by the server. John Nagle From abalter at indiana.edu Mon Jun 9 20:16:52 2008 From: abalter at indiana.edu (Ariel Balter) Date: Mon, 09 Jun 2008 20:16:52 -0400 Subject: Which Python Wiki engine? Message-ID: <484DC7F4.80900@indiana.edu> Kenneth, I thought this was a very interesting set of requests. Did you ever find a solution? Thanks, Ariel I'm looking for a Wiki engine to set up for my company, so that we can incrementally add user documentation for a fairly complex program, plus allow users to add their own comments for the benefit of others. I'd strongly prefer a Python-based Wiki, since that allows me the chance to add plugins with minimal effort (being a python enthusiast and programmer). However, I'd also like something that can provide a little more structure than MoinMoin seems able to provide (correct me if I'm wrong.) Though there would be cross-references amongst various sections, the idea is that the structure of the wiki would be very much that of an outline, with topics divided into sub topics and then into sub sub topics, etc. A person at our company would be the "editor"; responsible for setting up the original structure, putting in the documentation we currently have, and periodically editing contributions from users. Here are some of the features I'd greatly like to have that I haven't seen provided by the (relatively few) wiki engines I've looked at. Mind you, I don't claim to have looked at even these few exhaustively. (No time!) MoinMoin is the one I've looked at the most. 1) Automatically generated table of contents, based on the outline structure. This would be regenerated periodically (probably nightly) 2) Ability for users to add new subsections, but not to change that part of the document structure which has been locked by the editor. 3) Clear visual distinction between material added by the users, and material added or approved by the editor. 4) Legal-style numbering of sections, subsections, etc. 5) Ability to have single pages containing both locked text (which users cannot edit or delete) and unlocked text. Such a page would consist of one or more locked blocks of text, interspersed with comments put in by users. Users could put comments anywhere except side a locked text block. Ideally, this would also be something that doesn't depend on a backend database or other things besides the web server and python packages. This is not likely to be a wiki where huge amounts of interactivity must be supported; there will probably be a moderate amount of reading, and a small amount of writing. If you know of any Python wiki engines which can satisfy (even partially) this list, please let me know. I'd strongly prefer to have a Python engine. On the other hand, if you know of another type of wiki that matches well with these requirements, I won't complain if you mention it :-) Thanks, Ken McDonald -- <>0<>0<>0<>0<>0<>0<>0<>0<>0<>0 Ariel Balter, PhD Swain Hall West 025 Department of Physics & Biocomplexity Institute Indiana University, Bloomington 737 E Third Street, 47404 abalter at indiana.edu Office: (812) 855-2441 Home: (812) 332-2721 http://www.physics.indiana.edu/~abalter From sspatz at kcnet.com Mon Jun 23 00:13:22 2008 From: sspatz at kcnet.com (Saul Spatz) Date: Sun, 22 Jun 2008 23:13:22 -0500 Subject: Trying to Learn Packages In-Reply-To: References: Message-ID: <7e6dneR5icd2v8LVnZ2dnUVZ_hCdnZ2d@posted.kcnet> C?dric Lucantis wrote: > Le Sunday 22 June 2008 16:07:37 Saul Spatz, vous avez ?crit : >> Hi, >> >> I'm making a project into my first package, mainly for organization, but >> also to learn how to do it. I have a number of data files, both >> experimental results and PNG files. My project is organized as a root >> directory, with two subdirectories, src and data, and directory trees >> below them. I put the root directory in my pythonpath, and I've no >> trouble accessing the modules, but for the data, I'm giving relative >> paths, that depend on the current working directory. >> >> This has obvious drawbacks, and hard-coding a directory path is worse. >> Where the data files are numbers, I can simply incorporate them in >> python scripts that initialize data structures , but what can I do with >> the image files? > > For a small project you can do the same with images or any kind of data, for > instance by serializing your objects with pickle in ascii mode and putting > the result in a string constant (well, I never did it and can't guarantee it > will work, this is only an example of what people do in many situations) > >> What is the usual way of dealing with this? >> > > A more conventional way is to provide a configure script to run before > compiling/installing. That script should let the user choose where to install > datafiles with a command line option such as --datadir=/path or provide a > reasonable default value. Then it will auto-generate some code defining this > value as a global variable, to make it accessible to the rest of your own > code. Ideally, your app would also provide a command line option or an > environment variable to override this hard-coded setting at runtime. > > But maybe the distutils tools have some features for this, I don't know enough > of them to tell that. > A couple of good ideas here. Thanks. From bignose+hates-spam at benfinney.id.au Sun Jun 8 06:28:42 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 08 Jun 2008 20:28:42 +1000 Subject: Code correctness, and testing strategies References: <18c1e6480805240534k1da68fc8rfbace233f0de6e40@mail.gmail.com> Message-ID: <87hcc4jk4l.fsf@benfinney.id.au> David writes: > I'm asking about this, because as suggested by various posters, I > have written my latest (small) app by following a Behaviour-Driven > Development style. Congratulations on taking this step. > That went well, and the code ended up much more modular than if I > hadn't followed BDD. And I feel more confident about the code > quality than before ;-) The testing module has about 2x the lines of > code as the code being tested. This ratio isn't unusual, and is in fact a little on the low side in my experience. If you get decent (well-founded!) confidence in the resulting application code, then it's certainly a good thing. > My problem is that I haven't run the app once yet during development > :-/ That might be an artifact of doing bottom-up implementation exclusively, leading to a system with working parts that are only integrated into a whole late in the process. I prefer to alternate between bottom-up implementation and top-down implementation. I usually start by implementing (through BDD) a skeleton of the entire application, and get it to the point where a single trivial user story can be satisfied by running this minimally-functional application. Then, I make an automated acceptance test for that case, and ensure that it is run automatically by a build infrastructure (often running on a separate machine) that: - exports the latest working tree from the version control system - builds the system - runs all acceptance tests, recording each result - makes those results available in a summary report for the build run, with a way to drill down to the details of any individual steps That automated build is then set up to run either as a scheduled job periodically (e.g. four times a day), or as triggered by every commit to the version control system branch nominated for "integration" code. > Should I go ahead and start manually testing (like I would have from > the beginning if I wasn't following TDD), or should I start writing > automated integration tests? In my experience, small applications often form the foundation for larger systems. Time spent ensuring their build success is automatically determined at every point in the development process pays off tremendously, in the form of flexibility in being able to use that small application with confidence, and time saved not needing to guess about how ready the small app is for the nominated role in the larger system. > Is it worth the time to write integration tests for small apps, or > should I leave that for larger apps? There is a threshold below which setting up automated build infrastructure is too much overhead for the value of the system being tested. However, this needs to be honestly appraised: can you *know*, with omniscient certainty, that this "small app" isn't going to be pressed into service in a larger system where its reliability will be paramount to the success of that larger system? If there's any suspicion that this "small app" could end up being used in some larger role, the smart way to bet would be that it's worth the effort of setting up automated build testing. > I've tried Googling for integration testing in the context of TDD or > BDD and haven't found anything. Mostly information about integration > testing in general. I've had success using buildbot (which is packaged as 'buildbot' in Debian GNU/Linux) for automated build and integration testing and reporting. > When following BDD or TDD, should one write integration tests first > (like the unit tests), or later? All the tests should proceed in parallel, in line with the evolving understanding of the desired behaviour of the system. This is why the term "behaviour driven development" provide more guidance: the tests are subordinate to the real goal, which is to get the developers, the customers, and the system all converging on agreement about what the behaviour is meant to be :-) Your customers and your developers will value frequent feedback on progress, so: - satisfying your automated unit tests will allow you to - satisfy your automated build tests, which will allow you to - satisfy automated user stories ("acceptance tests"), which will allow the customer to - view an automatically-deployed working system with new behaviour (and automated reports for behaviour that is less amenable to direct human tinkering), which will result in - the customers giving feedback on that behaviour, which will inform - the next iteration of behaviour changes to make, which will inform - the next iteration of tests at all levels :-) -- \ "[W]e are still the first generation of users, and for all that | `\ we may have invented the net, we still don't really get it." | _o__) -- Douglas Adams | Ben Finney From peter.sabaini at gmail.com Tue Jun 10 15:30:48 2008 From: peter.sabaini at gmail.com (peter) Date: Tue, 10 Jun 2008 12:30:48 -0700 (PDT) Subject: post-mortem from core dump References: Message-ID: <51f855d5-7d01-4874-9b3e-19881eca7ce1@d77g2000hsb.googlegroups.com> Bump Has noone ever needed this? On Jun 9, 10:58 am, peter wrote: > AFAIK pdb only can do postmortem debugging if fed a Python stack > trace. Is there any way to obtain such a stack trace if all you've got > is a core dump? > > Or, put another way: can I do post-mortem debugging from a core dump? > > Thanks, > peter. From chinagood018 at yahoo.cn Sun Jun 8 09:26:16 2008 From: chinagood018 at yahoo.cn (chinagood018 at yahoo.cn) Date: Sun, 8 Jun 2008 06:26:16 -0700 (PDT) Subject: china supply nike shoes oz,nike air max 95,dunk... Message-ID: "China (www.getvogue.com) supply Nike_Air_Max_87,Nike_Air_Max_95,Nike_Air_Max_360,Nike_Air_Max_Ltd,Nike_Air_Max_TN,Nike_Air_Max_Rift,Nike_Shoes_R3,Nike_Shoes_R4,Nike_Shoes_R5,Nike_Shoes_R6,Nike_Shoes_NZ,Nike_Shoes_OZ,Nike_Shoes_TL,Nike_Shoes_Monster,Nike_Sho?es_Energia,Nike_Shoes_Turob,Air_Force_1s etc.More please sign in My website! China supply LV Dunk shoes,UGG Boots,Lacoste Puma trainers,D&G Prada Hogan Dsquared2 etc.---------please sign in VIEW PROFILE----------- " From jfabiani at yolo.com Fri Jun 6 00:15:10 2008 From: jfabiani at yolo.com (John Fabiani) Date: Thu, 05 Jun 2008 21:15:10 -0700 Subject: Newb question: underscore References: Message-ID: Skye wrote: > What is this doing? > > print >> fd, _(__doc__) > > > I'm guessing line-splitting __doc__ into a list, but what's that > leading underscore do? > > Thanks! I think it is standard practice to use the underscore for unicode converts. From grante at visi.com Tue Jun 24 00:22:06 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 23 Jun 2008 23:22:06 -0500 Subject: 32-bit python memory limits? References: Message-ID: <3_idnZuDPpjz6_3VnZ2dnUVZ_u6dnZ2d@posted.visi> On 2008-06-24, Gary Robinson wrote: > I'm running a Python job on OS X 10.5.3 and the Python 2.5.2 > that's available as a binary download at python.org for OS X. > > I ran a python program tonight that ended up using much more > memory than anticipated. It just kept on using more and more > memory. Instead of killing it, I just watched it, using > Activity Monitor. I assumed that when it had 2GB allocated it > would blow up, because I thought 32-bit python could only > address 2GB. You assumed incorrectly. :) > But Activity Monitor reported that it had allocated 3.99GB of > virtual memory before it finally blew up with malloc errors. > Was my understanding of a 2GB limit wrong? I guess so! But I'm > pretty sure I saw it max out at 2GB on linux... You may have been using a Linux kernel with a 2GB user VM limit. > Anybody have an explanation, or is it just that my > understanding of a 2GB limit was wrong? Or was it perhaps > right for earlier versions, or on linux...?? In the past, it was pretty common for Linux kernels to be configured so that a user-space program had 2GB of virtual address space. For reasons that aren't really important here, doing so made it simpler to manage various kernel vs. user memory issues. Back when nobody could afford more than a few hundred MB of RAM, that made sense. These days, the Linux kernel can be built for 2GB, 3GB or 4GB of VM space. There's a tiny bit of extra overhead if you pick 3GB or 4GB, so users with 2GB or less of physical RAM still often configure kernels for a 2GB limit. http://kerneltrap.org/node/2450 -- Grant Edwards grante Yow! Can you MAIL a BEAN at CAKE? visi.com From thomasmallen at gmail.com Tue Jun 3 14:40:45 2008 From: thomasmallen at gmail.com (tmallen) Date: Tue, 3 Jun 2008 11:40:45 -0700 (PDT) Subject: New variable? Message-ID: <18105511-7ae1-45e9-8c43-f34c1c4f5aeb@c58g2000hsc.googlegroups.com> What's the proper way to instantiate a new variable? x = ""? From musiccomposition at gmail.com Mon Jun 23 21:51:13 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 23 Jun 2008 18:51:13 -0700 (PDT) Subject: tuple.index() and tuple.count() References: <0411a4b3-7b99-41f9-980e-dd81845101bd@y21g2000hsf.googlegroups.com> <7f00c3e1-15b2-4dad-b73b-c146568370dc@i76g2000hsf.googlegroups.com> Message-ID: <653f9249-f67a-4990-b326-754e3aa4ffe7@y38g2000hsy.googlegroups.com> On Jun 23, 3:13?pm, hall.j... at gmail.com wrote: > never mind... a coworker pointed me to this > > http://bugs.python.org/issue1696444 > > apparently they're there in py3k... and 2.6 From geoff.bache at jeppesen.com Tue Jun 17 10:51:30 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Tue, 17 Jun 2008 07:51:30 -0700 (PDT) Subject: Annoying message when interrupting python scripts Message-ID: Hi all, I find that I semi-frequently get the cryptic message import site failed; use -v for traceback printed on standard error when an arbitrary python script receives SIGINT while the python interpreter is still firing up. If I use -v for traceback I get something along the lines of 'import site' failed; traceback: Traceback (most recent call last): File "/usr/lib/python2.4/site.py", line 61, in ? import os File "/usr/lib/python2.4/os.py", line 683, in ? import copy_reg as _copy_reg File "/usr/lib/python2.4/copy_reg.py", line 5, in ? """ KeyboardInterrupt Is this a bug? I couldn't find any code, but I imagine something like try: import site except: sys.stderr.write("import site failed; use -v for traceback\n") which should surely allow a KeyboardInterrupt exception through? Regards, Geoff Bache From BprabhuB at gmail.com Sun Jun 8 06:36:17 2008 From: BprabhuB at gmail.com (prabhu) Date: Sun, 8 Jun 2008 03:36:17 -0700 (PDT) Subject: EARN DOLLARS AT HOME BASED BUSINESS Message-ID: <14905870-f212-49ea-8d51-23b2e9a17ef2@z24g2000prf.googlegroups.com> Join the EyeEarn Network, and get paid to drive your car, wear T- shirts, and more! Earn money effortlessly while you go about your day! It?s fun, easy, and no experience is necessary! http://www.ezinfocenter.com/10122618/CB From jack.jack6666 at gmail.com Sat Jun 7 02:34:29 2008 From: jack.jack6666 at gmail.com (jack) Date: Fri, 6 Jun 2008 23:34:29 -0700 (PDT) Subject: UR SCHOOL AND COLLEGE'S, PLEASE REGISTER UR SCHOOL AND COLLEGE NAME'S IN THIS SITE. "" IF U HAVE TIME THEN DO IT. PLEASE I REQUEST. """ Message-ID: <84ad5f69-caa5-4742-9d42-228863810f50@s33g2000pri.googlegroups.com> IF you want to meet your old school mate's & college mate's of your life there is a chance, just enter school or college details in the below site http://www.batchmates.com/institution/regform.asp?refid=1529710&reflink=31481 please forward to ur friend's tell to them forward this message to there friend's From gagsl-py2 at yahoo.com.ar Mon Jun 2 22:37:54 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 02 Jun 2008 23:37:54 -0300 Subject: Easy install / setuptools References: <5213E58D85BC414998FA553C701E386C0EF286455F@SGBD012511.dlrmail.ad.delarue.com> Message-ID: En Thu, 29 May 2008 06:29:00 -0300, escribi?: > I'm trying to figure out the "best" way to distribute my own python > packages. Basicly, what I want is to have something like an > "installer.exe" (on windows) which puts my package under > Python/Lib/site-packages (so that it can be found via the PYTHONPATH). > > I've played around a bit with "easy install" and "setuptools" and the > .egg format. I've already managed to create a "myPackage.egg" file with > setup tools and "install" (it's just a copying) it ito the site-packages > directory using "easy install". You don't need setuptools at all. Just write a setup.py file using the standard distutils module, and execute: python setup.py bdist_wininst It will create an executable installer. A simple setup.py script looks like this: ---begin setup.py--- from distutils.core import setup setup(name='My Package', version='1.0', description='This is the description of myPackage', packages=['myPackage'], ) ---end setup.py--- Read the "Distributing Python Modules" document in your Python installation, or at > What I was wondering now is if there's a way to actually EXTRACT the egg > file and put the extracted file (i.e. the .py file) under site-packages. > And not the .egg? Well... don't use an egg in the first place :) > The problem with egg files is that you can't use > "open(os.path.join(os.path.dirname(__file__),'myFile')" and I'd need to > rewrite such code which I'd like to avoid if possible. Also, I don't > know whether leaving the python scripts packed inside the egg file is > slower for execution or not... There are many other problems with egg files... (did I menction that I hate eggs?) -- Gabriel Genellina From johnjsal at NOSPAMgmail.com Thu Jun 26 16:30:04 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 26 Jun 2008 16:30:04 -0400 Subject: url.encore/quote References: <889c0e25-c1e0-415b-b6db-f9e633a7eabb@d45g2000hsc.googlegroups.com> <4863e539$0$28613$c3e8da3@news.astraweb.com> Message-ID: <4863fc62$0$14071$c3e8da3@news.astraweb.com> "ianitux" wrote in message news:ddbcbb13-053b-4a9b-bc5e-2929db5d7161 at l64g2000hse.googlegroups.com... >> and see if that works? I'm not sure if quote() will convert the %20 into >> +, >> though, but it may. > > This is what quot do. > >>>> import urllib >>>> u = urllib >>>> u.quote(u.urlencode({'page': 'i', 'order': 'desc', 'style': 'flex >>>> power'})) > 'style%3Dflex%2Bpower%26page%3Di%26order%3Ddesc' I know quote will convert spaces to %20, just wasn't sure if it would explicitly convert + to %20. But it seems the output isn't what the OP wants anyway, because he wanted the & and = symbols. From guibog at gmail.com Mon Jun 30 01:35:45 2008 From: guibog at gmail.com (Guillaume Bog) Date: Mon, 30 Jun 2008 13:35:45 +0800 Subject: How do web templates separate content and logic? In-Reply-To: <0ckg64hkkcjb7et08rv2hn5vb6nchkmbcl@4ax.com> References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <0ckg64hkkcjb7et08rv2hn5vb6nchkmbcl@4ax.com> Message-ID: On Mon, Jun 30, 2008 at 11:27 AM, Tim Roberts wrote: > John Salerno wrote: > > > > > If it seems out of place to you, then you shouldn't do it. In general, you > need to find a model that makes sense to you, and that allows you to write > readable, workable, maintainable code. Yes, and MVC is not the last word for it. I have seen enormous snake nests of PHP code done in MVC, most of the problem coming from a strict (mis)application of MVC model. On the opposite, I sometime write HTML code straight inside the SQL's SELECT, which is pure heresy, and still get clean code that works. For me MVC is like strict encapsulation, it is probably useful when one guy touch the database, the other the HTML/CSS, and a third glue things with a script, all of them knowing nearly nothing about the rest. We don't work like this, so I don't know... > > -- > Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From matthieu.brucher at gmail.com Thu Jun 5 16:12:55 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Thu, 5 Jun 2008 22:12:55 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> <4847d203$0$32733$426a74cc@news.free.fr> Message-ID: 2008/6/5 Russ P. : > On Jun 5, 12:20 pm, Roy Smith wrote: > > > All somebody has to do to get at the private data is: > > > > #define private public > > # include > > #undef private > > Well, that shows the weakness of the C/C++ header files. The "include" > directive merely does a simple text substitution, which is pretty lame > as far as I am concerned. As you say, Java has moved beyond that, and > Ada has always been more sophisticated than that. > > By the way, my recollection is that in C++ access defaults to private > if nothing is declared explicity. So normally the "private" > declaration is unnecessary. If it is left out, your little trick won't > work. But your point is still valid. > And also #define class struct #include "something.h" #undef class ;) Matthieu -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Tue Jun 24 09:45:58 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 24 Jun 2008 06:45:58 -0700 (PDT) Subject: Python 3000 vs Perl 6 References: <89fbe834-68b7-49e6-8136-62dee53c2f40@t54g2000hsg.googlegroups.com> <7bad9ebd-81ab-48c4-854b-05f085e9d936@27g2000hsf.googlegroups.com> Message-ID: On Jun 24, 1:19?pm, bearophileH... at lycos.com wrote: > Michele Simionato: > > > It is worth reminding that, in more than one sense, the most advanced > > language is the one with less features ... > > I don't agree, Scheme or Brainfuck may have less features, but this > doesn't make them more advanced, it just makes programming with them > slower and more difficult. An advanced language is one that already > contains the most useful abstractions. For example Python has > generators and other things that are possible if you use Assembly too, > but having them pre-built in Python avoids me to use my limited brain > power to re-implement them from scratch, and I can focus on the > complex algorithm I am trying to implement. Oh, you are taking my words too literally, relax and take them in the context of the thread. Also consider the famous Clinger's maxim ?Programming languages should be designed not by piling feature on top of feature, but by removing the weaknesses and restrictions that make additional features appear necessary.? Michele Simionato From deets at nospam.web.de Sat Jun 14 13:15:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 14 Jun 2008 19:15:00 +0200 Subject: Making HEAD/PUT/DELETE requests with urllib2? In-Reply-To: <3419b35b-b1fd-4449-9570-2cf4771e05b1@z66g2000hsc.googlegroups.com> References: <3419b35b-b1fd-4449-9570-2cf4771e05b1@z66g2000hsc.googlegroups.com> Message-ID: <6bickqF3bj2khU1@mid.uni-berlin.de> Phillip B Oldham schrieb: > Thanks for the info. That's working like a charm. Looks as though I'll > be able to handle all request types with that object. > > I got a little worried then that the python dev's had missed something > truly important! I've done that in urrlib2 like this: class MyRequest(urllib2.Request): def get_method(self): if alternate_http_method is not None: return alternate_http_method return urllib2.Request.get_method(self) THe alternate_http_method is part of a class-closure, but of course you could do that with an instance variable as well. I then use it like this: req = MyRequest() handlers = [] if USE_PROXY: handlers.append(urllib2.ProxyHandler({'http' : PROXY})) req = self._create_request(url, connector, urlparams, queryparams, alternate_http_method) opener = urllib2.build_opener(*handlers) Diez From george.sakkis at gmail.com Wed Jun 11 01:46:37 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 10 Jun 2008 22:46:37 -0700 (PDT) Subject: Producer-consumer threading problem References: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> Message-ID: On Jun 10, 11:47?pm, Larry Bates wrote: > > I had a little trouble understanding what exact problem it is that you are > trying to solve but I'm pretty sure that you can do it with one of two methods: Ok, let me try again with a different example: I want to do what can be easily done with 2.5 Queues using Queue.task_done()/Queue.join() (see example at http://docs.python.org/lib/QueueObjects.html), but instead of having to first put all items and then wait until all are done, get each item as soon as it is done. > 1) Write the producer as a generator using yield method that yields a result > every time it is called (something like os.walk does). ?I guess you could yield > None if there wasn't anything to consume to prevent blocking. Actually the way items are generated is not part of the problem; it can be abstracted away as an arbitrary iterable input. As with all iterables, "there are no more items" is communicated simply by a StopIteration. > 2) Usw somethink like Twisted insted that uses callbacks instead to handle > multiple asynchronous calls to produce. ?You could have callbacks that don't do > anything if there is nothing to consume (sort of null objects I guess). Twisted is interesting and very powerful but requires a different way of thinking about the problem and designing a solution. More to the point, callbacks often provide a less flexible and simple API than an iterator that yields results (consumed items). For example, say that you want to store the results to a dictionary. Using callbacks, you would have to explicitly synchronize each access to the dictionary since they may fire independently. OTOH an iterator by definition yields items sequentially, so the client doesn't have to bother with synchronization. Note that with "client" I mean the user of an API/ framework/library; the implementation of the library itself may of course use callbacks under the hood (e.g. to put incoming results to a Queue) but expose the API as a simple iterator. George From tjreedy at udel.edu Fri Jun 27 19:08:55 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 27 Jun 2008 19:08:55 -0400 Subject: Do I need "self" and "other"? In-Reply-To: <04e2afb7-b96c-446a-816a-ffac0ea81d5b@p25g2000hsf.googlegroups.com> References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> <04e2afb7-b96c-446a-816a-ffac0ea81d5b@p25g2000hsf.googlegroups.com> Message-ID: Kurda Yon wrote: > > > OK, I see. In the given example "self" is just a name which can be > replace by whichever (valid) name. Is that always like that? I mean, > does "slef" have a special meaning in some cases or it is always "just > a name like any other"? Yes. A method is a function bound to a class or instance thereof. Def statements create functions. Parameter names are arbitrary, as long as they do not conflict with any global names you want to access from within the function. Self (and other) are simply community conventions. They do have they advantage that if they are only used as function/method parameter names, then they will not conflict with any module globals. tjr From johnjsal at NOSPAMgmail.com Thu Jun 12 13:49:23 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 12 Jun 2008 13:49:23 -0400 Subject: Making wxPython a standard module? References: <3EEC30D2-4536-4CCA-9047-8542CFAF52EC@leafe.com> Message-ID: <485160d8$0$11191$c3e8da3@news.astraweb.com> "Andrea Gavana" wrote in message news:mailman.374.1213285362.1044.python-list at python.org... > Whether the wxPython style is "Pythonic" or not (whatever "Pythonic" > means), this is a one-degree-above-insignificant issue for me. What I > care is the eye pleasing look of my apps and how easy it is to code > with a GUI framework. wxPython gives me both, the rest is just > academic discussion. Don't worry, I love wxPython with an almost disturbing intensity! ;) From stefaan.himpe at gmail.com Sat Jun 7 00:57:55 2008 From: stefaan.himpe at gmail.com (stefaan.himpe) Date: Sat, 07 Jun 2008 06:57:55 +0200 Subject: Dynamically naming objects. In-Reply-To: <3d2a85b2-255d-4e93-8cfb-e2772f57b69a@u6g2000prc.googlegroups.com> References: <8a99c3fa-1eeb-49b3-a714-b6063ec1daab@d19g2000prm.googlegroups.com> <3d2a85b2-255d-4e93-8cfb-e2772f57b69a@u6g2000prc.googlegroups.com> Message-ID: Hello, You can use this as indicated by Hans: >> u = [user() for i in xrange(5)] where "user" is a class or a function returning an object. u then is a list of "user" objects. > or does it somehow work? how would I address them if they all have the > name 'u'? You'd access members of the list as u[0], u[1], ... etc. I think you'd benefit from reading an introductory programming book. Best regards, Stefaan. From cheapforwholesale555 at 126.com Wed Jun 4 00:27:21 2008 From: cheapforwholesale555 at 126.com (cheapforwholesale555 at 126.com) Date: Tue, 3 Jun 2008 21:27:21 -0700 (PDT) Subject: Supply, Cheap Dior Burberry Chanel Fendi Sunglasses & Sandals Message-ID: <21edbc49-b6a1-4598-91a2-55466726c234@l28g2000prd.googlegroups.com> Discount Coach Sandals, Dior Sandals, Prada Sandals, Chanel Sandals, Versace Sandals, Crocs Sandals, LV Sandals, ( G U C C I ) Sandals, Women's Sandals Men's Slippers From China Brand Sunglasses Wholesale: Discount, Prada Sunglasses Discount, D&G Sunglasses Discount, Fendi Sunglasses Discount, Burberry Sunglasses Discount, Chanel Sunglasses Discount, LV Sunglasses Discount, Dior Sunglasses Discount, (G U C C I ) Sunglasses Discount, Armani Sunglasses Discount, Versace Sunglasses Discount, A&F Sunglasses Discount, LV Sunglasses Wholesale, Prada Sunglasses Wholesale, D&G Sunglasses Wholesale, Fendi Sunglasses Wholesale, Burberry Sunglasses Wholesale, Chanel Sunglasses Wholesale, LV Sunglasses Wholesale, Dior Sunglasses Wholesale, ( G U C C I ) Sunglasses Wholesale, Armani Sunglasses Wholesale, Versace Sunglasses Wholesale, A&F Sunglasses Wholesale, LV Sunglasses ( www.c heapforwholesale.com ) From johnjsal at gmailNOSPAM.com Mon Jun 16 23:58:49 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Mon, 16 Jun 2008 23:58:49 -0400 Subject: How to catch StopIteration? In-Reply-To: <5f27181e-f558-4760-b6a8-4fb7ef4c5848@a9g2000prl.googlegroups.com> References: <5f27181e-f558-4760-b6a8-4fb7ef4c5848@a9g2000prl.googlegroups.com> Message-ID: <48573679$0$11597$607ed4bc@cv.net> ccy56781 at gmail.com wrote: > for i, x in enumerate(collatz(13)): > try: > last = x[:i+1] > print x[:i+1] > except StopIteration: > print last.appnd(1) My guess would be because StopIteration is raised when control returns to the for loop and sees that it has nothing else left. At that point, you aren't in the try statement and so the exception can't be caught that way. But I should let the experts answer. I need to go to bed anyway! :) From goldnery at gmail.com Tue Jun 17 13:59:44 2008 From: goldnery at gmail.com (Gandalf) Date: Tue, 17 Jun 2008 10:59:44 -0700 (PDT) Subject: text alignment References: <39d1c620-9923-46e7-999d-ed86c8b465ff@34g2000hsh.googlegroups.com> <114f3f4c-4004-488b-86c5-4bf6416e15bd@l42g2000hsc.googlegroups.com> Message-ID: <8d563101-53f0-41d3-a544-ee0ba1d58db5@m36g2000hse.googlegroups.com> On Jun 17, 7:49?pm, Mike Driscoll wrote: > On Jun 17, 11:45?am, Gandalf wrote: > > > On Jun 17, 6:43?pm, Gandalf wrote: > > > > Hi every one. What is the similar python WX style property for CSS > > >text-align? > > > > I need this item text to start from the right direction: > > > > aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60)) > > > ? ? ? ? aaa.LoadPage('../../aa.html') > > > > Thanks! > > > *right to the left direction... > > > And I'm using pythin 2.5 on XP (I forget to mention...) > > The HtmlWindow widget can only display simple html. So, while you > cannot use CSS, you should be able to use the simple html alignment > directives. Check out the following site for pointers: > > http://www.htmlite.com/lite008.php > > If you want to be able to use CSS and javascript, you'll want to use > the ActiveX_IEHtmlWindow (wx.lib.iewin) widget instead as it embeds > Internet Explorer. > > Mike well thanks it seems useful... My question is about general items in WX and how to position them inside an element without using CSS. It's only coincidence My item is HtmlWindow From kaushiknfs at gmail.com Mon Jun 9 10:54:12 2008 From: kaushiknfs at gmail.com (Kaushik) Date: Mon, 9 Jun 2008 07:54:12 -0700 (PDT) Subject: help on self._dir Message-ID: Hi, i'm new to python , and i came across a code like if ("on_%s" % handler ) in self._dir: i tried use the a similar method in my class it errors out like AttributeError: bot instance has no attribute '_dir' what am i doing wrong? Thanks, Kaushik From wizzardx at gmail.com Mon Jun 2 14:16:16 2008 From: wizzardx at gmail.com (David) Date: Mon, 2 Jun 2008 20:16:16 +0200 Subject: Better performance In-Reply-To: <14a9bf9c-1605-43a1-a6ad-8720c3df06d9@c58g2000hsc.googlegroups.com> References: <14a9bf9c-1605-43a1-a6ad-8720c3df06d9@c58g2000hsc.googlegroups.com> Message-ID: <18c1e6480806021116w724aa87rf99c3aa7838c381c@mail.gmail.com> On Mon, Jun 2, 2008 at 4:42 AM, Franck Y wrote: > Hello Folks, > > I am facing a problem where i need to parse around 200 files, i have a > bit of knowledge in PHP/Perl/Python (the magic P :-P) > Trite answer: Use whatever is going to work best in your circumstances. All 3 languages can do what you need. Strong points for the languages as related to your question: PHP: Easy to make web pages. Perl: Lots of libraries, good text processing support Python: Easy to read and maintain You could even use all 3, in their strong areas. eg, PHP for the web page, perl for quick & dirty text-processing utils, and Python for the longer, more complicated scripts which you have to maintain. David. From karsten.heymann at blue-cable.net Thu Jun 5 08:49:16 2008 From: karsten.heymann at blue-cable.net (Karsten Heymann) Date: Thu, 05 Jun 2008 14:49:16 +0200 Subject: Creating A Tuple From A List, Adding To Tuple As You Do References: Message-ID: <87skvsnj1v.fsf@ara.blue-cable.net> Jeff Nyman writes: > from glob import glob > DC_List = glob('\\\\vcdcflx006\\Flex\\Sites\\*\\') > DC_List = ['Baltimore', 'Birmingham', 'Cincinnati', 'Cleveland', > LosAngeles'] > The problem is that I need to pass this list to a list control in a > wxWidgets application. In order to do that, I need to pass in a list > like this: > > [ ('Baltimore', ''), ('Birmingham', ''), ('Cincinnati', ''), > ('Cleveland', ''), ('LosAngeles', '') ] That's not hard: [ (x,'') for x in DC_List ] Yours Karsten From chrisspen at gmail.com Tue Jun 17 01:55:52 2008 From: chrisspen at gmail.com (Chris) Date: Mon, 16 Jun 2008 22:55:52 -0700 (PDT) Subject: Pattern Matching Over Python Lists Message-ID: <21a9c996-75ff-4f7c-b7e9-c94247f65674@c58g2000hsc.googlegroups.com> Is anyone aware of any prior work done with searching or matching a pattern over nested Python lists? I have this problem where I have a list like: [1, 2, [1, 2, [1, 7], 9, 9], 10] and I'd like to search for the pattern [1, 2, ANY] so that is returns: [1, 2, [1, 2, [6, 7], 9, 9], 10] [1, 2, [6, 7], 9, 9] From jacksingleton1 at gmail.com Sat Jun 28 22:10:16 2008 From: jacksingleton1 at gmail.com (c0mrade) Date: Sat, 28 Jun 2008 19:10:16 -0700 (PDT) Subject: C++ or Python In-Reply-To: References: Message-ID: <18176708.post@talk.nabble.com> Kurda Yon wrote: > > I would like to know what are advantages of Python in comparison with C > ++? In which cases and why Python can be a better tool than C++? > Uh, code a trivial program in each language and you'll have a perfectly good idea. -- View this message in context: http://www.nabble.com/C%2B%2B-or-Python-tp18164968p18176708.html Sent from the Python - python-list mailing list archive at Nabble.com. From paddy3118 at googlemail.com Fri Jun 13 01:11:16 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 12 Jun 2008 22:11:16 -0700 (PDT) Subject: value is in list? References: Message-ID: On Jun 12, 11:46 pm, "Steven Clark" wrote: > > Hello , > > following scenario > > > list_current = [ "welcome", "search", "done", "result"] > > list_ldap = [ "welcome", "hello"] > > > result: > > > list_toadd = [ "hello"] > > > by words said , i want to check if list item from list_ldap exists in > > list_current if not i want to add it to list_toadd. > > > Thanks! > > > D. > > list_toadd = [i for i in list_ldap if i not in list_current] > seems to work. > > I'm sure there's a way to do it with set objects as well. > -Steven >>> list_current = [ "welcome", "search", "done", "result"] >>> list_ldap = [ "welcome", "hello"] >>> to_add = set(list_ldap) - set(list_current) >>> to_add set(['hello']) - Paddy. From geonomica at gmail.com Tue Jun 3 06:48:53 2008 From: geonomica at gmail.com (gianluca) Date: Tue, 3 Jun 2008 03:48:53 -0700 (PDT) Subject: printf in python References: <261cbf38-6f0d-4525-9b4a-11ddbb910b66@d45g2000hsc.googlegroups.com> Message-ID: <183dfd01-68a5-4ae8-a04a-c3689d77003e@m3g2000hsc.googlegroups.com> On 2 Giu, 20:51, gianluca wrote: > On 2 Giu, 17:54, Dennis Lee Bieber wrote: > > > > > On Mon, 2 Jun 2008 00:32:33 -0700 (PDT), gianluca > > declaimed the following in comp.lang.python: > > > > Hy, I've a problem with may python library generated with swig from C > > > code. I works and I can access all function but a sim?ple function > > > that print a string don't work's. > > > The function is like this: > > > int PrintTEST() > > > { > > > printf("TEST "); > > > return 1; > > > } > > > > If I call the function (myDLL.PrintTEST() ) the function print only > > > the returned value, not the string "TEST". Could anybody help me? > > > Are you running from a command shell? > > > If you are testing from inside something like IDLE (or PythonWin, or > > pretty much any other GUI development system) you may not have a stdout > > for display by C code... > > > The return value would be printed by the Python interpreter in > > interactive mode... > > -- > > Wulfraed Dennis Lee Bieber KD6MOG > > wlfr... at ix.netcom.com wulfr... at bestiaria.com > > HTTP://wlfraed.home.netcom.com/ > > (Bestiaria Support Staff: web-a... at bestiaria.com) > > HTTP://www.bestiaria.com/ > > Hy, > the problem exists both in command shell and in IDLE. The value is > correct returned in both envirnment. > > gianluca Anybody help me? From anjaligroups at gmail.com Sun Jun 8 15:17:22 2008 From: anjaligroups at gmail.com (PREETHI) Date: Sun, 8 Jun 2008 12:17:22 -0700 (PDT) Subject: PERSONAL BANKRUPTCY Message-ID: <9aee83ef-6262-432a-abf1-18cf9c8d4ede@u6g2000prc.googlegroups.com> http://onenesstemplenemam.blogspot.com http://bankruptcy5.blogspot.com/ http://filingbankruptcy1.blogspot.com/ http://bankruptcyattorney1.blogspot.com/ http://personalbankruptcy1.blogspot.com/ http://chapter13bankruptcy1.blogspot.com/ From ironfroggy at socialserve.com Sun Jun 15 23:22:43 2008 From: ironfroggy at socialserve.com (Calvin Spealman) Date: Sun, 15 Jun 2008 23:22:43 -0400 Subject: newbie: for loop within for loop question In-Reply-To: <1120b573-0dd3-49c1-ba7c-97619912b69d@g16g2000pri.googlegroups.com> References: <4ce96e03-d336-4c44-9d10-4a9418ce359d@w34g2000prm.googlegroups.com> <1120b573-0dd3-49c1-ba7c-97619912b69d@g16g2000pri.googlegroups.com> Message-ID: <0799A584-BBE2-43F9-B39F-4F930E86C52A@socialserve.com> The sets module is no longer needed, as we have the built-in sets type. Its even getting a literal syntax soon. As for the original problem, I agree on the homework smell. On Jun 15, 2008, at 9:31 PM, takayuki wrote: > Dennis, > > thanks for your reply. unfortunately i accidentally posted only half > of my question! the "real" post should be up now. > > my apologies. > > takayuki > > > On Jun 16, 10:15 am, Dennis Lee Bieber wrote: >> On Sun, 15 Jun 2008 17:18:54 -0700 (PDT), takayuki >> declaimed the following in comp.lang.python: >> >>> Hi everyone, >> >>> I'm studying python via the excellent "how to think like a python >>> programmer" book by Allen Downey. Noob question follows... >> >>> I have a txt file (animals.txt) which contains the following text >>> each >>> on a separate line: aardvark, bat, cat, dog, elephant, fish, >>> giraffe, >>> horse, inchworm, jackelope >> >>> I want to create a function that loops through the animals.txt file >>> and does *not* print the word if any of the user specified >>> letters are >>> in that word. >> >>> def hasnolet(x): >> >> Hope this wasn't a homework assignment... It gave me my >> first excuse >> to try the set module... >> >>>>> import sets >>>>> words = [ "aardvark", "bat", "cat", "dog", "elephant", "fish" ] >>>>> exclude = "want" >>>>> excludeset = sets.Set(exclude) >>>>> excludeset >> >> Set(['a', 't', 'w', 'n'])>>> for w in words: >> >> ... if not excludeset.intersection(w): >> ... print w >> ... >> dog >> fish >> >> -- >> Wulfraed Dennis Lee Bieber KD6MOG >> wlfr... at ix.netcom.com wulfr... at bestiaria.com >> HTTP://wlfraed.home.netcom.com/ >> (Bestiaria Support Staff: web- >> a... at bestiaria.com) >> HTTP://www.bestiaria.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list From musiccomposition at gmail.com Fri Jun 27 22:05:44 2008 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 27 Jun 2008 19:05:44 -0700 (PDT) Subject: surprising behaviour of os.environ.clear References: Message-ID: <463baf33-e2d5-41fd-839e-aae45ee5433e@b1g2000hsg.googlegroups.com> On Jun 27, 4:05?pm, "Joe P. Cool" wrote: > If I call os.environ.clear in a python program child processes still > see the deleted entries. But when I iterate over the keys like so > > names = ?os.environ.keys > for k in names: > ? ? del ?os.environ[k] > > then the entries are also deleted for the child processes. Where is > the difference? Is this a bug? > (Observed in Python 2.5.2) This is because of how os.environ is implement with a UserDict subclass. You should report this at bugs.python.org. > > -- > Joe From Lie.1296 at gmail.com Tue Jun 3 08:39:01 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 3 Jun 2008 05:39:01 -0700 (PDT) Subject: question References: <6a8o5pF34umpoU1@mid.individual.net> <13801bd3-50da-4773-a0aa-edcaf27e0c4d@34g2000hsf.googlegroups.com> Message-ID: On May 30, 5:41?am, Gandalf wrote: > On May 30, 12:14 am, John Henderson wrote: > > > > > Gandalf wrote: > > > how do i write this code in order for python to understand it > > > and print me the x variable > > > > x=1 > > > def aaaa(): > > > ? ? x++ > > > ? ? if x > 1: > > > ? ? ? ? print "wrong" > > > ? ? else : > > > ? ? ? ? print x > > > > aaaa() > > > Example: > > > x=1 > > def aaaa(x): > > ? ? x += 1 > > ? ? if x > 1: > > ? ? ? ? return "wrong" > > ? ? else : > > ? ? ? ?return x > > > print aaaa(x) > > > John > > mmm isn't their any global variable for functions? the global keyword is only needed if you're going to write to the variable, so this works: glob = 1 def pp(): print glob pp() print glob while in: glob = 1 def pp(): glob = 2 print glob pp() print glob the 'glob' inside pp is different than the global 'glob'. To use the global 'glob' glob = 1 def pp(): global glob glob = 2 print glob pp() print glob Using a global variable (whether with global keyword or not) is not a very good thing to do as it makes codes hard to read as some have already pointed out From bearophileHUGS at lycos.com Tue Jun 24 07:52:41 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 24 Jun 2008 04:52:41 -0700 (PDT) Subject: Bit substring search References: Message-ID: <5043fee7-444b-41dd-a419-77550595d273@79g2000hsk.googlegroups.com> Kris Kennaway: > I am trying to parse a bit-stream file format (bzip2) that does not have > byte-aligned record boundaries, so I need to do efficient matching of > bit substrings at arbitrary bit offsets. > Is there a package that can do this? You may take a look at Hachoir or some other modules: http://hachoir.org/wiki/hachoir-core http://pypi.python.org/pypi/construct/2.00 http://pypi.python.org/pypi/FmtRW/20040603 Etc. More: http://pypi.python.org/pypi?%3Aaction=search&term=binary Bye, bearophile From johnjsal at gmailNOSPAM.com Sat Jun 21 23:54:05 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sat, 21 Jun 2008 23:54:05 -0400 Subject: Buffer size when receiving data through a socket? In-Reply-To: References: <20080616202135.41c407de.johnjsal@NOSPAMgmail.com> <03985958$0$8452$c3e8da3@news.astraweb.com> <485913ac$0$28627$c3e8da3@news.astraweb.com> Message-ID: <485dcd17$0$7327$607ed4bc@cv.net> Dennis Lee Bieber wrote: > On Wed, 18 Jun 2008 09:56:29 -0400, "John Salerno" > declaimed the following in comp.lang.python: > >> Interesting point. I'm not sure if it works that way though. I *think* I >> tried sending an empty string from the server back to the client, and as >> expected it exited the loop and closed the client, which doesn't make sense >> to me, since an empty string could be perfectly valid return data. >> > Okay... I suppose socket could consider a transmission with 0 data > bytes as valid "data". The main key is that there had to be send of 0 > data -- opposed to just not receiving anything.. No, I think you're right. I read elsewhere that when I send() call returns 0 bytes, the connection is automatically closed. From washakie at gmail.com Sat Jun 14 01:33:05 2008 From: washakie at gmail.com (John [H2O]) Date: Fri, 13 Jun 2008 22:33:05 -0700 (PDT) Subject: numpy: handling float('NaN') different in XP vs. Linux In-Reply-To: <57318df6-13e4-454b-b168-51651791b0c5@u6g2000prc.googlegroups.com> References: <17835502.post@talk.nabble.com> <57318df6-13e4-454b-b168-51651791b0c5@u6g2000prc.googlegroups.com> Message-ID: <17836073.post@talk.nabble.com> John Machin wrote: > > > Avoid impolite astonishment; RTFloatingM instead: > """ > > HTH, > John > -- > > I guess the key here is that it is not an issue with Python, but C... can I change 'the underlying C code?' if so, WFM should I read for that!? :p -- View this message in context: http://www.nabble.com/numpy%3A-handling-float%28%27NaN%27%29-different-in-XP-vs.-Linux-tp17835502p17836073.html Sent from the Python - python-list mailing list archive at Nabble.com. From nick at craig-wood.com Mon Jun 23 06:32:06 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 23 Jun 2008 05:32:06 -0500 Subject: flock seems very unsafe, python fcntl bug? References: <9abe51c3-c022-42e9-9d7d-acba7391d007@79g2000hsk.googlegroups.com> <485e18be$0$90264$14726298@news.sunsite.dk> Message-ID: Jens Henrik Leonhard Jensen wrote: > Your problem is that open(...,'w') is not locked. > > Use something like: > lockf = open('aaa', 'a') > fnctl.flock(lockf,fnctl.LOCK_EX) > file = open('aaa', 'w') > file.write('asdf') > file.close() > lockf.close() I've not seen that trick before - it is a good one. It wouldn't work for mandatory locking though... The basic problem is getting the file open for read/write without destroying the contents before you have the lock. None of the arguments to open() do the right thing.... Using an append open is a nice solution to that, apart from the fact that you can only append data onto the file hence the other open. Here are some other possible solutions and a test harness! The low level open is probably the most unixy solution. If you could specify os.O_RDWR|os.O_CREAT to the python open() function then it would be the best, but none of the documented open strings do that $ strace python -c 'open("aaa", "r+")' 2>&1 | grep 'open("aaa"' open("aaa", O_RDWR|O_LARGEFILE) = 3 $ strace python -c 'open("aaa", "w+")' 2>&1 | grep 'open("aaa"' open("aaa", O_RDWR|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 3 $ strace python -c 'open("aaa", "wr+")' 2>&1 | grep 'open("aaa"' open("aaa", O_RDWR|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 3 $ strace python -c 'open("aaa", "a+")' 2>&1 | grep 'open("aaa"' open("aaa", O_RDWR|O_CREAT|O_APPEND|O_LARGEFILE, 0666) = 3 ------------------------------------------------------------ """ Testing writing stuff to a file with locking """ import os import sys import fcntl def method_0(data): """ Use an normal open This doesn't work because it truncates the data before it has the lock """ fd = open('aaa', 'w') fcntl.flock(fd,fcntl.LOCK_EX) fd.write(data) fd.close() def method_1(data): """ Use an additional append open to lock """ lock_fd = open('aaa', 'a') fcntl.flock(lock_fd,fcntl.LOCK_EX) fd = open('aaa', 'w') fd.write(data) fd.close() lock_fd.close() def method_2(data): """ Use a low level open """ fd = os.fdopen(os.open('aaa', os.O_CREAT|os.O_RDWR), "r+") fcntl.flock(fd, fcntl.LOCK_EX) fd.truncate() fd.write(data) fd.close() def method_3(data): """ Using high level functions only Possibly racy on open when file doesn't exist """ if not os.path.exists('aaa'): fd = open('aaa', 'w+') else: fd = open('aaa', 'r+') fcntl.flock(fd,fcntl.LOCK_EX) fd.truncate() fd.write(data) fd.close() def check(): fd = open('aaa', 'r') fcntl.flock(fd,fcntl.LOCK_EX) data = fd.read() fd.close() if data not in ("sausage", "potato"): raise AssertionError("Wrong data %r" % data) if os.path.exists("aaa"): os.unlink("aaa") if len(sys.argv) < 2: print "Syntax: %s " % sys.argv[0] raise SystemExit(1) method = globals()["method_"+sys.argv[1]] if os.fork(): while 1: method("sausage") check() else: while 1: method("potato") check() ------------------------------------------------------------ -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bruno.42.desthuilliers at websiteburo.invalid Fri Jun 20 03:17:23 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 20 Jun 2008 09:17:23 +0200 Subject: An idiom for code generation with exec In-Reply-To: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> Message-ID: <485b5977$0$9738$426a74cc@news.free.fr> eliben a ?crit : > Hello, > > In a Python program I'm writing I need to dynamically generate > functions[*] (snip) > [*] I know that each time a code generation question comes up people > suggest that there's a better way to achieve this, without using exec, > eval, etc. Just to make things clear: you do know that you can dynamically build functions without exec, do you ? > But in my case, for reasons too long to fully lay out, I > really need to generate non-trivial functions with a lot of hard-coded > actions for performance. Just out of curiousity : could you tell a bit more about your use case and what makes a simple closure not an option ? > And there's no problem of security > whatsoever. If someone is very interested in the application, I will > elaborate more. From pdl5000 at yahoo.com Wed Jun 4 18:07:00 2008 From: pdl5000 at yahoo.com (Paul Lemelle) Date: Wed, 4 Jun 2008 15:07:00 -0700 (PDT) Subject: Unable to write output from os.path.walk to a file. In-Reply-To: <82d28c40806041326m2a26695t233d019ffa583c8c@mail.gmail.com> Message-ID: <448464.52735.qm@web52903.mail.re2.yahoo.com> Jeff, Thanks for your reply. I would like to like the absolute path of a directory. I thought that os.listdir just returns the nam itself in a data list. I noticed that none was being return in my example. Do you think that I have the arguments misplaced? Thanks, Paul --- On Wed, 6/4/08, Jeff McNeil wrote: > From: Jeff McNeil > Subject: Re: Unable to write output from os.path.walk to a file. > To: pdl5000 at yahoo.com > Cc: python-list at python.org > Date: Wednesday, June 4, 2008, 3:26 PM > What exactly are you trying to accomplish? If you're > just looking for > the contents of a directory, it would be much easier to > simply call > os.listdir(dirinput) as that will return a list of strings > that > represent the entries in dirinput. > > As it stands, 'os.path.walk' will return None in > your example, thus > the reason f.writelines is failing, the error says > something about a > required iterable, no? > > You ought to look at os.walk anyways, as I believe it is > the preferred > approach when walking a directory hierarchy. It's a > generator that > will yield a tuple that contains (dirname, subdirectories, > filenames). > It seems that is what you're looking for? > > Thanks, > > Jeff > > > > > On Wed, Jun 4, 2008 at 2:54 PM, Paul Lemelle > wrote: > > I Am trying to output the os.path.walk to a file, but > the writelines method complains.... > > > > Below is the code, any helpful suggestions would be > appreciated. > > > > def visit(arg, dirnames, names): > > print dirnames > > > > > > > > > > dirinput = raw_input("Enter directory to read: > ") > > > > listdir = os.path.walk (dirinput, visit, None) > > > > f = open("walktxt", "w") > > > > f.writelines(listdir) > > > > f.close() > > > > > > > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > From Lie.1296 at gmail.com Wed Jun 18 06:21:10 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 18 Jun 2008 03:21:10 -0700 (PDT) Subject: Getting Python exit code when calling Python script from Java program References: Message-ID: On Jun 18, 3:54?pm, Quill_Patri... at emc.com wrote: > I have a Python script which is used to load data into a database. Up to > now this script has been run by customers from the Windows command > prompt using "python edg_loader.pyc". Any error messages generated are > written to a log file. ?A project team working in the same company as me > here would like to use this loading utility. They write UI applications > for Windows using Java. They were able to launch the Python script from > within Java by creating a Process using Java ProcessBuilder class. > However, the way the error handling is currently implemented isn't > really suitable for use in a UI application. As I'm sure you can > appreciate it's not really feasible to tell users of a UI program to > keep checking the log files while the loading is underway!!. Ideally > they would like the Python loading utility to return an error code and > error message - the error message could then be displayed on a message > box on the UI. > I seem to be having problems implementing this. I tried using the > sys.exit() method in my script and passed non -zero values. However the > value wasn't picked up the by Java Process.exitValue() method - it kept > picking up 0. On investigation it turned out that the exit value being > read is from python.exe process, not from the Python script. Is there > any way I can obtain the return value of a python script from a Java > program? > > I did manage to get some sort of return error message. I wrote a test > message to sys.stderr in the Python script and this was picked up by > Java Process.getErrorSteam() method. > However I would really like to get the return codes working if possible > and would appreciate any suggestions on how to implement this. > > Thanks, > Patricia Quill I'm not experienced in Java and Python, but if all else fails, you could always create a file (or append to the log file) a special string that indicates what the problem or whether it runs successfully. The GUI application would always check this file after script execution From __peter__ at web.de Fri Jun 13 10:28:21 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Jun 2008 16:28:21 +0200 Subject: Create list from string References: Message-ID: ericdaniel wrote: > I'm new to Python and I need to do the following: > > from this: s = "978654321" > to this : ["978", "654", "321"] Use a loop: >>> s = "978654321" >>> items = [] >>> for start in range(0, len(s), 3): ... items.append(s[start:start+3]) ... >>> items ['978', '654', '321'] or a list comprehension: >>> [s[start:start+3] for start in range(0, len(s), 3)] ['978', '654', '321'] Peter From goldnery at gmail.com Thu Jun 26 21:35:03 2008 From: goldnery at gmail.com (Gandalf) Date: Thu, 26 Jun 2008 18:35:03 -0700 (PDT) Subject: sqlite3 alternative option References: <3274f950-bfaf-4e3f-bb87-7ce205067557@m36g2000hse.googlegroups.com> Message-ID: <1cc5333a-d1a0-4f4d-87a9-63c332d81780@y38g2000hsy.googlegroups.com> you where right! thank you ! From dummy666 at mail.ru Mon Jun 30 23:59:29 2008 From: dummy666 at mail.ru (askel) Date: Mon, 30 Jun 2008 20:59:29 -0700 (PDT) Subject: Communication between Python and PHP References: <8cd5f9db-46bc-491a-a58a-4ccc7086fa72@z16g2000prn.googlegroups.com> Message-ID: On Jun 25, 6:59 pm, nicodotti2 wrote: > On Jun 25, 1:50 pm, Larry Bates wrote: > > > > > nicodotti2 wrote: > > > Don't ask me why, but we have a bunch of legacy code in PHP on a > > > server and a wee-bit of Python code for integrating GData google > > > calendar services. We now need to build a way of sending messages > > > between them. The general flow is: > > > > PHP Web Page(on apache) ---> Python Gdata Consumer -----> Gdata > > > and then json is returned back like: > > > PHP Web Page<----json data---- Pthon Gdata Consumer > > > > So I tried to convince my boss to let me use the python c extension to > > > write a native bridge but 'no dice'. He also does not want anything > > > 'experimental' so pyphp is out. He'd like me to basically have them > > > communicate by passing the json via http/apache - so in essence, I'll > > > have to make (what I feel) are very expensive calls between two > > > objects that, in a perfect world, would be on the same machine in the > > > same language! I see this as a potential bottleneck. Any suggestions? > > > I have to start prototyping this today so the sooner the better, um, > > > please ;) Thanks gurus out there. > > > Use sockets. They are efficient and both languages have good implementations. > > > -Larry > > Thanks Larry I'll look into going that route. I wouldn't even try to reinvent the wheel in such a case. You are going to use GData and yet consider HTTP over LAN to be expensive. Get real, man. Save yourself a time by not developing and supporting your own very special wheel. Your boss is not that stupid as he probably seems to you. From erokar at gmail.com Sat Jun 21 13:15:54 2008 From: erokar at gmail.com (erokar at gmail.com) Date: Sat, 21 Jun 2008 10:15:54 -0700 (PDT) Subject: Fast and easy GUI prototyping with Python References: <9c349bf0-ef63-4463-bd4e-cdbe331b58c3@z66g2000hsc.googlegroups.com> Message-ID: Thanks for your input. The prototype will be running on Windows only. Portability and being able to develop on other platforms would be a bonus, but is not a requirement. I guess the choice is going to be between Visual Studio and Qt. Of importance is: 1) Being able to develop and change (dummy) GUI prototypes very fast, i.e. drag and drop. I've tried Visual Studio's form designer -- it seems quite capable. Don't know about Qt's designer -- is it as easy and fast to use? 2) The Qt vs. .NET API. I have no experience with Qt's API and a rudimentary experience with the .NET API (seems powerfull but also big and complex). Michael: Interesting suggestion to just subclass C#, maybe that's the way to go. From tjreedy at udel.edu Tue Jun 24 15:06:35 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Jun 2008 15:06:35 -0400 Subject: binary representation of an integer In-Reply-To: <7c3ebcd1-709c-4763-987f-39c224a17dc0@m44g2000hsc.googlegroups.com> References: <14e14b5e-ce39-414a-a450-7c81baaabc3a@79g2000hsk.googlegroups.com> <7c3ebcd1-709c-4763-987f-39c224a17dc0@m44g2000hsc.googlegroups.com> Message-ID: cokofreedom at gmail.com wrote: > On Jun 24, 10:38 am, Mark Dickinson wrote: >> Interestingly, unlike hex and oct, bin doesn't add a trailing >> 'L' for longs: >> >>>>> bin(13L) >> '0b1101' >> >> I wonder whether this is a bug... > Strange in 2.6, but I know at least in 3.0 that all integers are C > Long's now, so the L is no longer required. In current 2.x, the trailing L is no longer required for long integer input; the lexer decides whether to make an int or long. Similarly, ints are automatically converted to longs as needed instead of raising overflow errors (as once happended). The trailing L on output would have been removed already except for backward compatibility. But there was no back-compatibility requirement for 0bxxxx strings. In 3.0, all integers are class 'int'. The internal representation as fixed or extended precision is entirely an internal implementation matter. From stef.mientki at gmail.com Wed Jun 25 15:44:26 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 25 Jun 2008 21:44:26 +0200 Subject: ANN: wxPython 2.8.8.0 In-Reply-To: <48629A74.2030109@alldunn.com> References: <48629A74.2030109@alldunn.com> Message-ID: <4862A01A.4060107@gmail.com> Robin Dunn wrote: > Announcing > ---------- > > The 2.8.8.0 release of wxPython is now available for download at > > Changes in 2.8.8.0 > ------------------ I read somewhere else that OGL was removed, is that correct ? cheers, Stef From bignose+hates-spam at benfinney.id.au Thu Jun 12 01:16:02 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 12 Jun 2008 15:16:02 +1000 Subject: Why does python not have a mechanism for data hiding? References: <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> <484e3526$0$30894$426a74cc@news.free.fr> <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> <783c55ec-a294-4600-91d9-4a0d78632c49@t12g2000prg.googlegroups.com> <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> <484f880c$0$6412$426a74cc@news.free.fr> Message-ID: <87iqwfgrn1.fsf@benfinney.id.au> Michele Simionato writes: > On Jun 12, 6:43 am, Dennis Lee Bieber wrote: > > Pardon, but I think you mean "experienced". > > > > Of course, GvR may qualify as "experimented" if one considers > > designing a language from scratch to be an experiment > > It looks like in French (as in Italian) *experimented* has the > meaning of "tried and tested on the field" when applied to a person. That would, in English, be "proven" (from similar ideas: "to prove" means "to determine the truth by a test or trial"). -- \ "I went over to the neighbor's and asked to borrow a cup of | `\ salt. 'What are you making?' 'A salt lick.'" -- Steven Wright | _o__) | Ben Finney From hat at se-162.se.wtb.tue.nl Wed Jun 18 07:09:58 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 18 Jun 2008 13:09:58 +0200 Subject: Getting Python exit code when calling Python script from Java program References: Message-ID: On 2008-06-18, Quill_Patricia at emc.com wrote: > I have a Python script which is used to load data into a database. Up to > now this script has been run by customers from the Windows command > prompt using "python edg_loader.pyc". Any error messages generated are > written to a log file. A project team working in the same company as me > here would like to use this loading utility. They write UI applications > for Windows using Java. They were able to launch the Python script from > within Java by creating a Process using Java ProcessBuilder class. > However, the way the error handling is currently implemented isn't > really suitable for use in a UI application. As I'm sure you can > appreciate it's not really feasible to tell users of a UI program to > keep checking the log files while the loading is underway!!. Ideally > they would like the Python loading utility to return an error code and > error message - the error message could then be displayed on a message > box on the UI. The first thing to do is decide whether this is a Java problem, a Python problem, or a OS problem. Then post the question in the appropiate forum. One simple experiment may be to write a C function that returns a non-zero exit code, and run that as job. > I seem to be having problems implementing this. I tried using the > sys.exit() method in my script and passed non -zero values. However the > value wasn't picked up the by Java Process.exitValue() method - it kept What did the OS say? Run a program like below in OS ('python x.py'), then query the OS about the exit code of the program. In that way, you can narrow down your search. > picking up 0. On investigation it turned out that the exit value being > read is from python.exe process, not from the Python script. Is there > any way I can obtain the return value of a python script from a Java This is not what I see happening here: x.py: import sys sys.exit(138) % python2.4 x.py % echo $? 138 as you can see, the mechanism works at my Linux system. > Java Process.getErrorSteam() method. > However I would really like to get the return codes working if possible > and would appreciate any suggestions on how to implement this. I'd suggest to first find out where in the Java->OS->Python->OS->Java chain things go wrong. As for how to handle a child-process from Java, try asking in a Java news group. Sincerely, Albert From szrRE at szromanMO.comVE Sun Jun 1 04:24:18 2008 From: szrRE at szromanMO.comVE (szr) Date: Sun, 1 Jun 2008 01:24:18 -0700 Subject: The Importance of Terminology's Quality References: <4840ab73$0$90274$14726298@news.sunsite.dk> <4841f0aa$0$90274$14726298@news.sunsite.dk> Message-ID: Peter Duniho wrote: > On Sat, 31 May 2008 23:27:35 -0700, szr wrote: > >> [...] >>> But the subthread Lew commente don was about Perl and Unix. That is >>> clearly off topic. >> >> I agree with and understand what you are saying in general, but >> still, isn't it possible that were are people in the java group (and >> others) who might of been following the thread, only to discover >> (probably not right away) that someone decided to remove the group >> they were reading the thread from? I know I would not like that, >> even if it wasn't on topic at the branch. > > All due respect, I don't really care if those people find the thread > gone. And no one should. I prefer to be considerate of others. > Each individual person has a wide variety of interests. A thread > that is off-topic in a newsgroup may in fact be concerning a topic of > interest for someone who just happened to be reading that newsgroup. Well if a thread has absolutely no relation to a group, then yes, cross-posting to said group is inappropiate, and setting follow ups may well be warrented. But when there is some relation, sometimes it may be better to mark it as [OT] i nthe subject line, a practice that is sometimes seen, and seems to suffice. > What if someone cross-posted a thread about motorcycle racing in the > Perl newsgroup as well as an actual motorcycle racing newsgroup? You are comparing apples and oranges now; sure, if you post about motorcycles (to use your example) it would be wildly off topic, but the thread in question was relating to programming (the naming of functions and such) in general. > Does that justify the thread continuing to be cross-posted to the Perl > newsgroup? No, of course not. but who decides this? And why does said individual get to decide for everyone? > So please. Quit trying to justify a thread being cross-posted to a > newsgroup that you aren't even reading You do not know what groups I read. And I am not attempting to justify cross posting at all. Rather I am arguing against deciding for a whole news group when a thread should be discontinued. -- szr From socyl at 987jk.com.invalid Wed Jun 11 17:49:16 2008 From: socyl at 987jk.com.invalid (kj) Date: Wed, 11 Jun 2008 21:49:16 +0000 (UTC) Subject: Strange bug doesn't occur in Pydb Message-ID: I'm running into a strange seg fault with the module cjson. The strange part is that it does not occur when I run the code under Emacs' Pydb. Here's an example: import sys, cjson d1 = {'a': 1, 'b': 2, 'c': 3} print sys.version j1 = cjson.encode(d1) print j1 # should print the string '{"a": 1, "c": 3, "b": 2}' The code above runs fine under Pydb, but segfaults at the call to cjson.encode when I run it from the command line in a standard Linux shell interaction. In the printed version strings are identical. I figure this must be a bug in cjson. I'd love to find a workaround for it, and hope that this strange difference between Pydb and the shell command line may be a clue to that. Any thoughts? TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From circularfunc at yahoo.se Wed Jun 18 17:42:00 2008 From: circularfunc at yahoo.se (cirfu) Date: Wed, 18 Jun 2008 14:42:00 -0700 (PDT) Subject: advanced listcomprehenions? Message-ID: <717129b5-d92f-4be2-ae6a-037870bfa407@2g2000hsn.googlegroups.com> I am wondering if it is possible to write advanced listcomprehensions. For example: """Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".""" Obv it doesnt have to be a list according tot hat definition but suppose i want to generate that list. >>> [["Fizzbuzz",x] for x in xrange(1,101) if x%3 == 0 and x%5 == 0] [['Fizzbuzz', 15], ['Fizzbuzz', 30], ['Fizzbuzz', 45], ['Fizzbuzz', 60], ['Fizzbuzz', 75], ['Fizzbuzz', 90]] is not what i want. the following does the trick but is ldo not a listcomprehension: for i in xrange(1,101): s = "" if i%3 == 0: s += "Fizz" if i%5 == 0: s += "Buzz" if s: print "%d : %s" % (i,s) else: print i or to generate a lisrt but not by listcomprehsnion: map(lambda x: (not x%3 and not x%5 and "FizzBuzz") or (not x%3 and "Fizz") or (not x%5 and "Buzz") or x, xrange(1,101)) From paddy3118 at googlemail.com Fri Jun 13 00:57:29 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 12 Jun 2008 21:57:29 -0700 (PDT) Subject: Mapping None. Why? References: Message-ID: On Jun 12, 9:36 pm, "Terry Reedy" wrote: > "Paddy" wrote in message > > news:a8874705-9f90-4acb-9930-b0afa03d4061 at 27g2000hsf.googlegroups.com... > | > | Iam wondering why the peculiar behavior of map when the function in > | given as None: > > The 'peculiar behavior' is the same as zip (except for padding short > iterators versus truncating long iterators. Map was added years before > zip. After that, map(None,...) was kept for back compatibility. > > In 3.0, the doc for map is > "Return an iterator that applies function to every item of iterable, > yielding the results. If additional iterable arguments are passed, function > must take that many arguments and is applied to the items from all > iterables in parallel. With multiple iterables, the iterator stops when the > shortest iterable is exhausted." > > Using a map defined with None raises > TypeError: 'NoneType' object is not callable > > tjr I really should get into the habit of reading the 3.0 docs before asking questions :-) My original question came about after answering this query: http://gmcnaughton.livejournal.com/27955.html?thread=70451#t70451 - Paddy. From spoier at gmail.com Mon Jun 9 18:02:31 2008 From: spoier at gmail.com (Skye) Date: Mon, 9 Jun 2008 15:02:31 -0700 (PDT) Subject: Question by someone coming from C... References: Message-ID: <70c02bf1-b26f-4fba-9a33-38e79e3e34eb@p25g2000pri.googlegroups.com> On Jun 9, 2:35?pm, Matimus wrote: > The only time to do that sort of thing (in python) is when interacting > with something else that isn't written in Python though. In general, > for logging, just use the standard logging module:http://docs.python.org/lib/module-logging.html Thanks! It looks like subclassing the logging module would be a much better idea :) Skye From george.sakkis at gmail.com Fri Jun 20 09:19:56 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 20 Jun 2008 06:19:56 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> Message-ID: On Jun 20, 8:03 am, eliben wrote: > On Jun 20, 9:17 am, Bruno Desthuilliers > 42.desthuilli... at websiteburo.invalid> wrote: > > eliben a ?crit :> Hello, > > > > In a Python program I'm writing I need to dynamically generate > > > functions[*] > > > (snip) > > > > [*] I know that each time a code generation question comes up people > > > suggest that there's a better way to achieve this, without using exec, > > > eval, etc. > > > Just to make things clear: you do know that you can dynamically build > > functions without exec, do you ? > > Yes, but the other options for doing so are significantly less > flexible than exec. > > > > But in my case, for reasons too long to fully lay out, I > > > really need to generate non-trivial functions with a lot of hard-coded > > > actions for performance. > > > Just out of curiousity : could you tell a bit more about your use case > > and what makes a simple closure not an option ? > > Okay. > > I work in the field of embedded programming, and one of the main uses > I have for Python (and previously Perl) is writing GUIs for > controlling embedded systems. The communication protocols are usually > ad-hoc messages (headear, footer, data, crc) built on top of serial > communication (RS232). > > The packets that arrive have a known format. For example (YAMLish > syntax): > > packet_length: 10 > fields: > - name: header > offset: 0 > length: 1 > - name: time_tag > offset: 1 > length: 1 > transform: val * 2048 > units: ms > - name: counter > offset: 2 > length: 4 > bytes-msb-first: true > - name: bitmask > offset: 6 > length: 1 > bit_from: 0 > bit_to: 5 > ... > > This is a partial capability display. Fields have defined offsets and > lengths, can be only several bits long, can have defined > transformations and units for convenient display. > > I have a program that should receive such packets from the serial port > and display their contents in tabular form. I want the user to be able > to specify the format of his packets in a file similar to above. > > Now, in previous versions of this code, written in Perl, I found out > that the procedure of extracting field values from packets is very > inefficient. I've rewritten it using a dynamically generated procedure > for each field, that does hard coded access to its data. For example: > > def get_counter(packet): > data = packet[2:6] > data.reverse() > return data > > This gave me a huge speedup, because each field now had its specific > function sitting in a dict that quickly extracted the field's data > from a given packet. It's still not clear why the generic version is so slower, unless you extract only a few selected fields, not all of them. Can you post a sample of how you used to write it without exec to clarify where the inefficiency comes from ? George From larry.bates at websafe.com` Tue Jun 10 23:47:53 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 10 Jun 2008 22:47:53 -0500 Subject: Producer-consumer threading problem In-Reply-To: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> References: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> Message-ID: George Sakkis wrote: > I'd like some feedback on a solution to a variant of the producer- > consumer problem. My first few attempts turned out to deadlock > occasionally; this one seems to be deadlock-free so far but I can't > tell if it's provably correct, and if so, whether it can be > simplified. > > The generic producer-consumer situation with unlimited buffer capacity > is illustrated at http://docs.python.org/lib/condition-objects.html. > That approach assumes that the producer will keep producing items > indefinitely, otherwise the consumer ends up waiting forever. The > extension to the problem I am considering requires the consumer to be > notified not only when there is a new produced item, but also when > there is not going to be a new item so that it stops waiting. More > specifically, I want a generator (or iterator class) with the > following generic signature: > > def iter_consumed(items, produce, consume): > '''Return an iterator over the consumed items. > > :param items: An iterable of objects to be `produce`()d and > `consume`()d. > > :param produce: A callable `f(item)` that produces a single item; > the return > value is ignored. What "produce" exactly means is application- > specific. > > :param consume: A callable `f()` that consumes a previously > produced item > and returns the consumed item. What "consume" exactly means is > application-specific. The only assumption is that if `produce` > is called > `N` times, then the next `N` calls to `consume` will > (eventually, though > not necessarily immediatelly) return, i.e they will not block > indefinitely. > ''' > > One straightforward approach would be to serialize the problem: first > produce all `N` items and then call consume() exactly N times. > Although this makes the solution trivial, there are at least two > shortcomings. First, the client may have to wait too long for the > first item to arrive. Second, each call to produce() typically > requires resources for the produced task, so the maximum resource > requirement can be arbitrarily high as `N` increases. Therefore > produce() and consume() should run concurrently, with the invariant > that the calls to consume are no more than the calls to produce. Also, > after `N` calls to produce and consume, neither should be left > waiting. > > I pasted my current solution at http://codepad.org/FXF2SWmg. Any > feedback, especially if it has to do with proving or disproving its > correctness, will be appreciated. > > George I had a little trouble understanding what exact problem it is that you are trying to solve but I'm pretty sure that you can do it with one of two methods: 1) Write the producer as a generator using yield method that yields a result every time it is called (something like os.walk does). I guess you could yield None if there wasn't anything to consume to prevent blocking. 2) Usw somethink like Twisted insted that uses callbacks instead to handle multiple asynchronous calls to produce. You could have callbacks that don't do anything if there is nothing to consume (sort of null objects I guess). I don't know if either of these help or not. -Larry From praveen.sunsetpoint at gmail.com Fri Jun 20 02:16:02 2008 From: praveen.sunsetpoint at gmail.com (Sallu) Date: Thu, 19 Jun 2008 23:16:02 -0700 (PDT) Subject: Regular expression References: Message-ID: <42396af0-29aa-45ea-8588-186b0ccbab58@z16g2000prn.googlegroups.com> On Jun 20, 10:58?am, Soltys wrote: > Hi, > Your post is not about re, but about encoding, next time > be more careful when choosing topic for your post! > Did you check what pep0263 says about encoding? > One of the first thins it says is: > > "(...) > Defining the Encoding > Python will default to ASCII as standard encoding if no other > ? ? ?encoding hints are given. > (...)" > > So when you're using non ASCII characters you should always > specify encoding. Here again, read pep0263 for how this can > be done, especially section Defining Encoding, where there > are multiple ways of doing that. > > Sallu pisze: > > > > > Hi All, > > here i have on textbox in which i want to restrict the user to not > > enter the 'acent character' like ( ? ) > > i wrote the program > > > import re > > value="this is Praveen" > > #value = 'rich? gerry' > > if(re.search(r"^[A-Za-z0-9]*$",value)): > > ? print "Not allowed accent character" > > else: > > ? print "Valid" > > > output : > > > sys:1: DeprecationWarning: Non-ASCII character '\xc3' in file regu1.py > > on line 3, but no encoding declared; seehttp://www.python.org/peps/pep-0263.html > > for details > > Valid > > > when i make comment #value="this is Praveen" and released comment > > value = 'rich? gerry' > > but still i am getting same output even it have accent character. > > -- > Soltys > > "Free software is a matter of liberty not price" I am sorry sotys..actually i am very much new to python.. import re import os, sys string = 'rich?' print string def strip_accents(string): import unicodedata return unicodedata.normalize('NFKD', unicode(string)).encode('ASCII', 'ignore') msg=strip_accents(string) print msg Output : sys:1: DeprecationWarning: Non-ASCII character '\xc3' in file regu.py on line 4, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details rich? Traceback (most recent call last): File "regu.py", line 13, in ? msg=strip_accents(string) File "regu.py", line 10, in strip_accents return unicodedata.normalize('NFKD', unicode(string)).encode('ASCII', 'ignore') UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128) From d.a.abernathy at gmail.com Mon Jun 9 16:39:25 2008 From: d.a.abernathy at gmail.com (dj) Date: Mon, 9 Jun 2008 13:39:25 -0700 (PDT) Subject: time module methods give an am or pm value ? References: <2309efff-5c6b-4434-a2cd-01c3fee86fee@l42g2000hsc.googlegroups.com> Message-ID: <1532ef61-c7fc-4724-83d8-1ef7a95a24dd@27g2000hsf.googlegroups.com> On Jun 7, 9:40 am, Scott David Daniels wrote: > dj wrote: > > Hello again, > > > Does anyone know which method in the time module will generate and am > > or pm ? > > If none of the method will do this for me. Can I produce the value on > > my own ? > > Any suggestions ? > > Read up about strftime (a function, not a method). > > Generally, if you know you'll be using something for more than a few > uses, it is worth reading the entire documentation for that module. > People put a fair amount of effort into documentation, and they do it > to reduce the number of questions they have to answer one user at a > time. Reading the results of that effort before asking shows courtesy. > Few people mind explaining unclear documentation when the confusing part > is identified (and they know the answer). Similarly, asking (5000?, a > million?) to each spend a second so you can save an hour is bad economics. > > --Scott David Daniels > Scott.Dani... at Acm.Org Hello Scott, Thank you very much. I did find this function after shortly after I posted this question. I appreciated your help :-). And you are right, I do need to be a better job of checking the documentation, before I post. Thank you again for your help. From george.sakkis at gmail.com Tue Jun 17 14:50:34 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 17 Jun 2008 11:50:34 -0700 (PDT) Subject: Removing inheritance (decorator pattern ?) References: <439e5f62-73d2-4d13-88b5-8d7afa16da09@w7g2000hsa.googlegroups.com> Message-ID: On Jun 16, 11:10 pm, Maric Michaud wrote: > Le Monday 16 June 2008 20:35:22 George Sakkis, vous avez ?crit : > > > > > On Jun 16, 1:49 pm, Gerard flanagan wrote: > > > George Sakkis wrote: > > > > I have a situation where one class can be customized with several > > > > orthogonal options. Currently this is implemented with (multiple) > > > > inheritance but this leads to combinatorial explosion of subclasses as > > > > more orthogonal features are added. Naturally, the decorator pattern > > > > [1] comes to mind (not to be confused with the the Python meaning of > > > > the term "decorator"). > > > > > However, there is a twist. In the standard decorator pattern, the > > > > decorator accepts the object to be decorated and adds extra > > > > functionality or modifies the object's behavior by overriding one or > > > > more methods. It does not affect how the object is created, it takes > > > > it as is. My multiple inheritance classes though play a double role: > > > > not only they override one or more regular methods, but they may > > > > override __init__ as well. Here's a toy example: > > > > I don't know if it will map to your actual problem, but here's a > > > variation of your toy code. I was thinking the Strategy pattern, > > > different classes have different initialisation strategies? But then you > > > could end up with as many Strategy classes as subclasses, I don't know. > > > (Also in vaguely similar territory > > > -http://bazaar.launchpad.net/~grflanagan/python-rattlebag/trunk/annota... > > > ) > > > > class MetaBase(type): > > > > def __init__(cls, name, bases, data): > > > cls.strategies = [] > > > cls.prefixes = [] > > > for base in bases: > > > print base > > > if hasattr(base, 'strategy'): > > > cls.strategies.append(base.strategy) > > > if hasattr(base, 'prefix'): > > > cls.prefixes.append(base.prefix) > > > super(MetaBase, cls).__init__(name, bases, data) > > > > class Joinable(object): > > > __metaclass__ = MetaBase > > > strategy = list > > > prefix = '' > > > > def __init__(self, words): > > > self._words = words > > > for strategy in self.strategies: > > > self._words = strategy(self._words) > > > > def join(self, delim=','): > > > return '%s %s' % (' '.join(self.prefixes), > > > delim.join(self._words)) > > > > class Sorted(Joinable): > > > strategy = sorted > > > prefix = '[sorted]' > > > > class Reversed(Joinable): > > > strategy = reversed > > > prefix = '[reversed]' > > > > class SortedReversed(Sorted, Reversed): > > > pass > > > > class ReversedSorted(Reversed, Sorted): > > > pass > > > > if __name__ == '__main__': > > > words = 'this is a test'.split() > > > print SortedReversed(words).join() > > > print ReversedSorted(words).join() > > > This doesn't solve the original problem, the combinatorial explosion > > of empty subclasses. At the end of the day, I'd like a solution that > > uses a (mostly) flat, single-inheritance, hierarchy, allowing the > > client say: > > Yes, and it fails to implement the strategy pattern as well... which would > have solved the problem as it is intended exactly for this purpose. As someone in another newsgroup demonstrated, it can be solved with a combination of strategy and decorator: http://tinyurl.com/5ulqh9 George From saluk64007 at gmail.com Mon Jun 2 20:45:29 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Mon, 2 Jun 2008 17:45:29 -0700 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <6ee28d40-c0ec-4b3e-aaf2-b6031bf20009@j22g2000hsf.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <6ee28d40-c0ec-4b3e-aaf2-b6031bf20009@j22g2000hsf.googlegroups.com> Message-ID: Can we plez not try and ruin my fave language with a useless concept? Strict data hiding is only necessary because textbooks say it is. Use method attributes or some other hack if you really must (people won't know it's there unless they look, and if they are looking, maybe they have a reason?) I heard a few emails back the argument that "you don't know how code might be used", in favor of data hiding. Um. Excuse me? You don't know how code might be used to me is a good reason not to overly protect anything. This lets people use code in different ways than you might think. Seriously, use java or some other such thing. It's not like there aren't plenty of other languages to choose from. We aren't against data hiding because we have python-colored glasses and are trying to stick up for our favorite language after all. For some of us, myself included, the lack of data hiding is one of the plusses of the language. I have done enough development with big locked down systems to know how frustrating it is when someone tells me how I am supposed to use them. If data hiding were to exist in python, someone would make a big system and use it excessively, and it would eventually get very irritating. Just like it is when working with big c++ or java systems. Please, just drop this topic. It's ridiculous. If you have customers who use your code in bad ways, and then complain when you change something they relied on you, I feel for you, but have you thought that maybe the way they are trying to use it makes more sense than the way you are trying to force them to? Ok, most likely your way is better. So hide the data a little better, but there is still no reason to ENFORCE it. Sorry for the rant, I don't usually rant, but this is a sore subject for me and one that keeps me using python. If the framework says I must do object.move(-5), but the move function does collision detection, then I want to be able to say object.x-=5 if I decide I don't need the collision detection. Maybe later the designer will decide that it is object.pos instead of object.x, object.y, which will break my code. My own damn fault. And if I don't feel like fixing it, I will subclass object, and make x a property that returns and sets pos[0]. Or maybe the designer was nice enough to do that for me himself. I'm serious, if data hiding were added, I would be looking around for another language. I wouldn't stop using python if no one used these features, but I would start looking for sure. -------------- next part -------------- An HTML attachment was scrubbed... URL: From joemacbusiness at yahoo.com Mon Jun 23 13:12:58 2008 From: joemacbusiness at yahoo.com (joemacbusiness at yahoo.com) Date: Mon, 23 Jun 2008 10:12:58 -0700 (PDT) Subject: Question: How do I format printing in python Message-ID: Hi All, How do I format printed data in python? I could not find this in the Python Reference Manual: http://docs.python.org/ref/print.html Nor could I find it in Matloff's great tutorial: http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf For example, how do I turn this: 512 Jun 5 2004 X11r6 22 Jan 17 2005 a2p 22 Jan 17 2005 acctcom 5374 Sep 15 2002 acledit 5664 May 13 2004 aclget 12020 May 13 2004 aclput 115734 Jun 2 2004 adb 46518 Jun 4 2004 admin 66750 Sep 16 2002 ali 1453 Sep 15 2002 alias 28150 Jun 4 2004 alog 15 May 12 2005 alstat into this: 512 Jun 5 2004 X11r6 22 Jan 17 2005 a2p 22 Jan 17 2005 acctcom 5374 Sep 15 2002 acledit 5664 May 13 2004 aclget 12020 May 13 2004 aclput 115734 Jun 2 2004 adb 46518 Jun 4 2004 admin 66750 Sep 16 2002 ali 1453 Sep 15 2002 alias 28150 Jun 4 2004 alog 15 May 12 2005 alstat Thank you From rent.lupin.road at gmail.com Fri Jun 27 00:58:47 2008 From: rent.lupin.road at gmail.com (James) Date: Thu, 26 Jun 2008 21:58:47 -0700 (PDT) Subject: Cyclic imports References: <1a5a1eb9-b4d1-4905-b60c-48fc93056e4d@k13g2000hse.googlegroups.com> Message-ID: <2588f7e0-ccbb-40cb-84da-d133349f5b72@u36g2000prf.googlegroups.com> > # a.py > import b > # refer to b.b > > # b.py > import a > # refer to a.a Thanks Dan, but that still doesn't work for me I'm afraid... I renamed the modules avoid name overloading -- a.py is now: import b class A(): print('b.b_mod:', b.b_mod) b is now defined, but b.b_mod isn't: File "main.py", line 1, in from a import a_mod File "/Users/james/tmp/python/a/a_mod.py", line 3, in class A(): File "/Users/james/tmp/python/a/a_mod.py", line 4, in A print('b.b_mod:', b.b_mod) AttributeError: 'module' object has no attribute 'b_mod' I must be missing something here - I've tried adding the modules to __all__ in __init__.py but that didn't help either. James From kyosohma at gmail.com Tue Jun 3 09:42:51 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 3 Jun 2008 06:42:51 -0700 (PDT) Subject: Books for programmers References: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> <78ef063d-7219-4ffa-bf8f-88dc24dd90bc@r66g2000hsg.googlegroups.com> Message-ID: On Jun 3, 5:45?am, V wrote: > Hi Matt, > > and thank you very much for your answer. > > > Hm, depends of course, how good your programming skills are in the > > languages you knwo already, but I rely on the book "Beginning Python - > > From Novice to Professional" by Magnus Lie Hetland, published by Apress. > > I think that I'm interested in a more advance book, ideally one that > talk of the Python gotchas, traps, pitfall, idioms, performance, > stile, and so on. I really like the style used from Scott Meyers in > his Effective C++ series, or from Herb Sutter's Exceptional C++, but > after a quick look I did not find anything similar for Python... > > Best regards. I agree with Rick. "Core Python Programming" by Chun is pretty good. However, Lutz's "Programming Python" is also very good and has a few big example programs to walk through. You might also find the Python Cookbooks handy. There's also "Python Power!" by Matt Telles, which is more of a reference book although not quite as dry as "Python Essential Reference" was. Mike From jurgenex at hotmail.com Mon Jun 30 13:44:13 2008 From: jurgenex at hotmail.com (Jürgen Exner) Date: Mon, 30 Jun 2008 17:44:13 GMT Subject: perl + python tutorial available for download References: <86c4090b-ed0b-4249-b3ee-517c94328741@z32g2000prh.googlegroups.com> Message-ID: Xah wrote: >my perl and python tutorial > >http://xahlee.org/perl-python/index.html > >is now available for download for offline reading. Why anyone would have the idea to mix two different langauges in one tutorial is beyond me. And calling that web page a tutorial is a large stretch of imagination. It is a random collection of primitve code samples, organized roughly by area. No learning goals, no explanation of concepts, ... Apparently you changed your ID to escape all the filters you have been a permanent guest to. This 'tutorial' confirms that this is the best place for you. So back you go again. jue From johnjsal at gmailNOSPAM.com Mon Jun 16 23:51:24 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Mon, 16 Jun 2008 23:51:24 -0400 Subject: Does '!=' equivelent to 'is not' In-Reply-To: <4857321f$0$11606$607ed4bc@cv.net> References: <4857321f$0$11606$607ed4bc@cv.net> Message-ID: <485734bd$0$11614$607ed4bc@cv.net> John Salerno wrote: > == and != test to see if the *value* of > two variables are the same. Let me just clarify this. It might seem like a picky point, but I think it's pretty important when learning Python. I don't really mean the value of the variables themselves, I mean the values that the variables refer to. The variables themselves aren't actually the objects, nor do they have values, exactly. Instead, they *refer* to objects in memory, and it is these objects that we are testing the values and identities of. For example, using that previous code: a ---> 'hello world' b ---> 'hello world' c ---\ ---> 'hello world' d ---/ a and b were assigned to two separate objects (it doesn't matter that they happen to be the same value). As you can see above, a and b refer to different things. c and d, however, were assigned simultaneously to the same object, and therefore refer to a single object in memory. This is why "c is d" is True, but "a is b" is False. From johnjsal at NOSPAMgmail.com Thu Jun 26 14:53:25 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 26 Jun 2008 14:53:25 -0400 Subject: url.encore/quote References: <889c0e25-c1e0-415b-b6db-f9e633a7eabb@d45g2000hsc.googlegroups.com> Message-ID: <4863e539$0$28613$c3e8da3@news.astraweb.com> "zowtar" wrote in message news:889c0e25-c1e0-415b-b6db-f9e633a7eabb at d45g2000hsc.googlegroups.com... > urlencode({'page': i, 'order': 'desc', 'style': 'flex power'}) > return: > page=1&order=desc&style=flex+power > > but I want: > page=1&order=desc&style=flex%20power > > and url.quote don't put the &'s and ='s > any idea guys? urlencode() uses quote_plus() when it creates a URL, which is why you are getting the plus signs. Unfortunately I don't have Python at work, so I can't try this, but maybe do: quote(urlencode({'page': i, 'order': 'desc', 'style': 'flex power'})) and see if that works? I'm not sure if quote() will convert the %20 into +, though, but it may. From windwiny.ubt at gmail.com Mon Jun 2 22:51:43 2008 From: windwiny.ubt at gmail.com (windwiny) Date: Mon, 2 Jun 2008 19:51:43 -0700 (PDT) Subject: =?GB2312?B?cHl0aHRvbiC199PDIHNvILmyz+2/4rK7xNzXqru7ss7K/cDg0M0=?= Message-ID: ???python ? ctypes, ?????? ubuntu 8.04, Python 2.5.2 (r252:60911, May 7 2008, 15:19:09) , gcc (GCC) 4.2.3 (Ubuntu 4.2.3-2ubuntu7) ?????? so ??? --------------------- #include double myfd(double x) { return x * 2;} float myff(float x) { return x * 3;} int myfi(int x) { return x * 4 ;} --------------------- ? gcc -shared a.c -o liba.so ?????? liba.so , ??? c ???????????????????? ?????python ?? --------------------- # coding:utf-8 import ctypes as dll p = dll.cdll.LoadLibrary("./liba.so") print p.myfi(8) # ?32,?? try: print p.myfd(0.3) # ?? except: print "except myfd()" try: print p.myff(0.4) # ?? except: print "except myff()" --------------------- ????? ctypes.ArgumentError: argument 1: : Don't know how to convert parameter 1 ??????? From bj_666 at gmx.net Mon Jun 30 15:12:09 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Jun 2008 19:12:09 GMT Subject: Looping-related Memory Leak References: <94312edc-babb-4c1b-8db1-233404aa4a02@i76g2000hsf.googlegroups.com> <0abf2145-231c-4189-a8ca-b1f327a735dd@a1g2000hsb.googlegroups.com> <1e36866c-4a94-40b6-9780-81e104286862@d1g2000hsg.googlegroups.com> Message-ID: <6cspg9F3hjks7U1@mid.uni-berlin.de> On Mon, 30 Jun 2008 10:55:00 -0700, Tom Davis wrote: > To me, this seems illogical. I can understand that the GC is > reluctant to reclaim objects that have many connections to other > objects and so forth, but once those objects' scopes are gone, why > doesn't it force a reclaim? For instance, I can use timeit to create > an object instance, run a method of it, then `del` the variable used > to store the instance, but each loop thereafter continues to require > more memory and take more time. 1000 runs may take .27 usec/pass > whereas 100000 takes 2 usec/pass (Average). `del` just removes the name and one reference to that object. Objects are only deleted when there's no reference to them anymore. Your example sounds like you keep references to objects somehow that are accumulating. Maybe by accident. Any class level bound mutables or mutable default values in functions in that source code? Would be my first guess. Ciao, Marc 'BlackJack' Rintsch From alexnbryan at gmail.com Wed Jun 11 17:01:15 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 11 Jun 2008 14:01:15 -0700 (PDT) Subject: problems with opening files due to file's path In-Reply-To: <16651e80806111342k1d2d0b3ay9a558452f48fc2d9@mail.gmail.com> References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> <77acc29a-fffa-44d6-b07b-6bcf8b5bdd74@h1g2000prh.googlegroups.com> <17786320.post@talk.nabble.com> <16651e80806111342k1d2d0b3ay9a558452f48fc2d9@mail.gmail.com> Message-ID: <17787168.post@talk.nabble.com> Well, I don't understand why I don't need to change anything because say I run that code, which goes straight from the entry box to the startfile() function. It doesn't work with some of the paths, that is the whole problem. the problem is when I enter a path with those certain characters next to each other. Everyone seems like there is some huge thing that I am missing... and I don't know what it is, because when I run that code, with that path I was talking about, I get an error, and it shows me that it is because of the \0. Jerry Hill wrote: > > On Wed, Jun 11, 2008 at 4:16 PM, Alexnb wrote: >> >> I posted the underlying code, but I haven't made the GUI code because if >> I >> can't get the underlying code right it doesn't matter, well in my eyes it >> doesn't but I am probably wrong. But it will look somehting like this: > > What you're missing is that all of the problems you're having with > escape characters *only apply to string literals inside your python > source code.* If you're getting the string from the console, you > don't need to escape or change anything. If you're getting the string > from a Tk text box, you don't need to escape or change anything. If > you're getting the string from the filesystem, you don't need to > escape or change anything. > > The only place you have to be careful is when you type out a literal > string inside your .py source code. When you do that, you need to > properly escape backslashes, either by putting them in raw strings, or > by doubling up your backslashes. > > If you haven't already, reread the section of the python tutorial > about string literals: http://docs.python.org/tut/node5.html. > > -- > Jerry > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17787168.html Sent from the Python - python-list mailing list archive at Nabble.com. From dullrich at sprynet.com Thu Jun 12 06:57:28 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 12 Jun 2008 05:57:28 -0500 Subject: re quiz Message-ID: True or False? (no fair looking it up) (*) If repl is a string then re.sub(pattern, repl, s) returns s with non-overlapping occurences of pattern replaced by repl. I assumed it was true - spent a few hours trying to figure out what was going on with a certain re.sub, then noticed that (*) is false: (**) "If repl is a string, any backslash escapes in it are processed. That is, "\n" is converted to a single newline character, "\r" is converted to a linefeed, and so forth." So I changed my r"\remark{Hint}" to r"\\remark{Hint}" and things were fine. A pointless question and then a practical one. Pointless question: There must be a good reason for (**). What would it be? Seems needlessly confusing to me (of course a lot of things seem confusing to me...) Maybe it's going to be confusing no matter what they do. But "\\n" looks like it doesn't contain a newline, but it gets converted to something that does. (Another fascinating question is how they could phrase the docs here so as to confuse nobody. Because "\n" _is_ a newline, or so it's going to look to many people; I'd spell it out:: "a string containing '\' followed by 'n' ".) Practical question: What's a _complete_ list of the escapes included in the "and so forth" in (**)? (Or is there a function somewhere that will convert r"\remark{Hint}" to r"\\remark{Hint}" for me, and do the same for precisely the escpapes referred to in the "and so forth"?) David C. Ullrich From lists at cheimes.de Thu Jun 12 20:13:55 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 13 Jun 2008 02:13:55 +0200 Subject: value is in list? In-Reply-To: References: Message-ID: David Hl??ik wrote: > Hello , > following scenario > > list_current = [ "welcome", "search", "done", "result"] > list_ldap = [ "welcome", "hello"] > > result: > > list_toadd = [ "hello"] > > by words said , i want to check if list item from list_ldap exists in > list_current if not i want to add it to list_toadd. Steven's example works but it won't scale for large lists. Sets are much faster if you don't require an ordered result. >>> list_current = [ "welcome", "search", "done", "result"] >>> list_ldap = [ "welcome", "hello"] >>> diff = set(list_ldap).difference(set(list_current)) >>> diff set(['hello']) >>> list_toadd = list(diff) >>> list_toadd ['hello'] Christian From google at mrabarnett.plus.com Thu Jun 26 14:47:42 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 26 Jun 2008 11:47:42 -0700 (PDT) Subject: Problems with file IO in a thread, and shutil References: <38f798c9-983f-4f0c-a281-d2a89e738590@v1g2000pra.googlegroups.com> Message-ID: On Jun 26, 8:06?am, Roopesh wrote: > Thanks for the reply. I did testing in a clean system, were anti virus/ > spyware is not installed. It still gave this problem, in say 1 out of > 1000 cases. > > By any chance would it be possible that the Windows OS has not > completed writing to the file even after file.flush() and file.close() > is called? > > Thanks > Roopesh Maybe it's a Windows service, eg the indexing service or generating thumbnails. Anyway, retrying after a delay would still be worth it. From laurent.ploix at gmail.com Mon Jun 23 02:56:19 2008 From: laurent.ploix at gmail.com (=?ISO-8859-1?Q?m=E9choui?=) Date: Sun, 22 Jun 2008 23:56:19 -0700 (PDT) Subject: How to request data from a lazily-created tree structure ? References: <6bo3ifF3dj7dmU1@mid.uni-berlin.de> <896f8600-4183-4147-96c9-64ab5a9ad753@x41g2000hsb.googlegroups.com> <6bp68jF3cv5c7U1@mid.uni-berlin.de> <6bqq4hF3bshiiU1@mid.uni-berlin.de> Message-ID: <31dbcfd4-3b5f-4fef-96e2-89c7340ef948@e53g2000hsa.googlegroups.com> On Jun 17, 11:54 pm, "Diez B. Roggisch" wrote: > > Do you know if there is suchXPathengine that can be applied to a DOM- > > like structure ? > > No. But I toyed with the idea to write one :) > > > One way would be to take anXPathengine from an existing XML engine > > (ElementTree, or any other), and see what APIs it calls... and see if > > we cannot create a DOM-like structure that has the same API. Duck > > typing, really... > > Why can't you create a *real* DOM? > > Diez I may have found sg: http://sourceforge.net/projects/pdis-xpath/ A XPath 1.0, in pure python, on top of ElementTree. I'll have a look. From jorgen.maillist at gmail.com Wed Jun 25 02:49:02 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Wed, 25 Jun 2008 08:49:02 +0200 Subject: Send output to printer In-Reply-To: <013c01c8d67f$869bfea0$1f01a8c0@RAZAK> References: <013c01c8d67f$869bfea0$1f01a8c0@RAZAK> Message-ID: <11e49df10806242349y41a8aa84u6ea2205729770095@mail.gmail.com> Hi, It depends on how your printer can be accessed. Is there a driver for it? The most simple way might be using ShellExecute (under windows) but I found no way to supress the print dialog. Another way is using win32com module and instantiate an IE automation object, which you feed a HTML page and issue a print. Be careful about printing too fast allow it 4-5 seconds to process or successive print jobs will fail. Here is a snippet of code to get you on your way; from win32com import client ie = client.Dispatch("InternetExplorer.Application") ie.Navigate(fn) # fn = filename (to temp file) to print time.sleep(2) ie.ExecWB(6, 2) time.sleep(2) ie.Quit() ie = None For successive prints it is better to instantiate one IE object per multiple print jobs, but once done, release it and set it up again. - Jorgen On Wed, Jun 25, 2008 at 6:54 AM, ajak_yahoo wrote: > Need some help from you all, > > I already manage to write a program to print a packaging label. > > The output on screen is as below, > > > Part Number : PWEE1111AA > Quantity : 100 pcs > Lot Number : 10A2008 > Customer : ABC Pte. Ltd. > > > My questions is how can I send this output to my Panasonic KX-P1121 dot > matric printer, > Is it a module that i can used, previously i wrote my program using foxpro > 2.6, i have no experience in python. > > > Regards, > Ajak > -- > http://mail.python.org/mailman/listinfo/python-list > From johnjsal at gmailNOSPAM.com Sat Jun 14 14:47:21 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sat, 14 Jun 2008 14:47:21 -0400 Subject: Creating a TCP/IP connection on already-networked computers In-Reply-To: <4853f269$0$11615$607ed4bc@cv.net> References: <4853f269$0$11615$607ed4bc@cv.net> Message-ID: <4854123f$0$5017$607ed4bc@cv.net> John Salerno wrote: > if the program I write actually works and allows the two > computers to speak to each other, will that be a result purely of the > program, or will it have anything to do with the fact that they are > already on a home network together? Here are the two programs. Server first, then client. They work, which in itself amazes me that it's so simple to create a network connection like this! But my basic question is this: would this connection work if the two computers (each running one of these scripts) were completely unrelated to one another? My two are on a home network, but if I were to run the server program and have a friend of mine (who lives somewhere else) run the client program, would it still work? ----- #!/usr/bin/env python from socket import * from time import ctime HOST = '192.168.1.100' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) tcpSerSock = socket(AF_INET, SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.listen(5) while True: print 'waiting for connection...' tcpCliSock, addr = tcpSerSock.accept() print '...connected from:', addr while True: data = tcpCliSock.recv(BUFSIZ) if not data: break tcpCliSock.send('[%s] %s' % (ctime(), data)) tcpCliSock.close() tcpSerSock.close() ----- ----- #!/usr/bin/env python from socket import * HOST = '192.168.1.100' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) tcpCliSock = socket(AF_INET, SOCK_STREAM) tcpCliSock.connect(ADDR) while True: data = raw_input('> ') if not data: break tcpCliSock.send(data) data = tcpCliSock.recv(BUFSIZ) if not data: break print data tcpCliSock.close() ----- From george.sakkis at gmail.com Sun Jun 22 09:36:51 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 22 Jun 2008 06:36:51 -0700 (PDT) Subject: Storing value with limits in object References: Message-ID: <2b0f1f77-98a2-4e1a-9427-7b7936ee7bf0@d77g2000hsb.googlegroups.com> On Jun 22, 5:44 am, "Josip" wrote: > I'm trying to limit a value stored by object (either int or float): > > class Limited(object): > def __init__(self, value, min, max): > self.min, self.max = min, max > self.n = value > def set_n(self,value): > if value < self.min: # boundary check > self.n = self.min > if value > self.max: > self.n = self.max > else: > self.n = value > n = property(lambda self : self._value, set_n) > > This works, I bet you didn't even try this, unless your definition of "works" includes a "RuntimeError: maximum recursion depth exceeded". Here's a a working version: class Limited(object): def __init__(self, value, min, max): self.min, self.max = min, max self.n = value n = property(lambda self : self._value, lambda self,value: self.__dict__.__setitem__('_value', max(self.min, min(value, self.max)))) def __int__(self): return int(self._value) def __float__(self): return float(self._value) a = Limited(11, 0, 9) print float(a) import math print math.sqrt(a) > except I would like the class to behave like built-in types, so > I can use it like this: > > a = Limited(7, 0, 10) > b = math.sin(a) > > So that object itself returns it's value (which is stored in a.n). Is this > possible? For (most) math.* functions it suffices to define __float__, so the above works. For making it behave (almost) like a regular number, you'd have to write many more special methods: http://docs.python.org/ref/numeric-types.html. Here's a possible start: import operator class Limited(object): def __init__(self, value, min, max): self.min, self.max = min, max self.n = value n = property(lambda self : self._value, lambda self,value: self.__dict__.__setitem__('_value', max(self.min, min(value, self.max)))) def __str__(self): return str(self.n) def __repr__(self): return 'Limited(%r, min=%r, max=%r)' % (self.n, self.min, self.max) def __int__(self): return int(self._value) def __float__(self): return float(self._value) def __add__(self, other): return self._apply(operator.add, self, other) def __sub__(self, other): return self._apply(operator.sub, self, other) # a few dozens more methods follow ... def __radd__(self, other): return self._apply(operator.add, other, self) def __rsub__(self, other): return self._apply(operator.sub, other, self) # a few dozens more methods follow ... @classmethod def _apply(cls, op, first, second): minmax = None if isinstance(first, cls): minmax = first.min,first.max first = first._value if isinstance(second, cls): if minmax is None: minmax = second.min,second.max second = second._value return cls(op(first,second), *minmax) a = Limited(11, 0, 9) print a+1 print 1+a print a-1 print 1-a Needless to say, this is almost two orders of magnitude slower than the builtin numbers, so you'd better not use it for any serious number crunching. HTH, George From floris.bruynooghe at gmail.com Mon Jun 16 06:48:29 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Mon, 16 Jun 2008 03:48:29 -0700 (PDT) Subject: Context manager for files vs garbage collection Message-ID: <74f25d98-a6a5-4034-b3b7-06a8ca40ce04@e39g2000hsf.googlegroups.com> Hi I was wondering when it was worthwil to use context managers for file. Consider this example: def foo(): t = False for line in file('/tmp/foo'): if line.startswith('bar'): t = True break return t What would the benefit of using a context manager be here, if any? E.g.: def foo(): t = False with file('/tmp/foo') as f: for line in f: if line.startswith('bar'): t = True break return t Personally I can't really see why the second case would be much better, I've got used to just relying on the garbage collector... :-) But what is the use case of a file as a context manager then? Is it only useful if your file object is large and will stay in scope for a long time? Regards Floris From maric at aristote.info Wed Jun 11 03:08:53 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 11 Jun 2008 09:08:53 +0200 Subject: catastrophic regexp, help! In-Reply-To: References: Message-ID: <200806110908.53682.maric@aristote.info> Le Wednesday 11 June 2008 06:20:14 cirfu, vous avez ?crit?: > pat = re.compile("(\w* *)*") > this matches all sentences. > if fed the string "are you crazy? i am" it will return "are you > crazy". > > i want to find a in a big string a sentence containing Zlatan > Ibrahimovic and some other text. > ie return the first sentence containing the name Zlatan Ibrahimovic. > > > patzln = re.compile("(\w* *)* zlatan ibrahimovic (\w* *)*") > should do this according to regexcoach but it seems to send my > computer into 100%CPU-power and not closable. This kind of regexp are quite often harmfull, while perfectly valid, if you take the time it will return, this check too many things to be practical. Read it, sequentially to make it sensible : for each sequence of word + space, trying with the longest first, does the string 'zlatan' follow ? "this is zlatan example.' compare with 'this is zlatan example', 'z'=='.', false compare with 'this is zlatan ', 'z'=='e', false compare with 'this is zlatan', 'z'==' ', false compare with 'this is ', "zlatan"=="zlatan", true compare with 'this is', 'z'==' ', false compare with 'this ', 'z'=='i', false compare with 'this', 'z'==' ', false ... ouch ! The most simple are your regex, better they are, two short regex are better then one big, etc... Don't do premature optimization (especially with regexp). In [161]: s="""pat = re.compile("(\w* *)*") this matches all sentences. if fed the string "are you crazy? i am" it will return "are you crazy". i want to find a in a big string a sentence containing Zlatan Ibrahimovic and some other text. ie return the first sentence containing the name Zlatan Ibrahimovic. patzln = re.compile("(\w* *)* zlatan ibrahimovic (\w* *)*") should do this according to regexcoach but it seems to send my computer into 100%CPU-power and not closable. """ In [172]: list(e[0] for e in re.findall("((\w+\s*)+)", s, re.M) if re.findall('zlatan\s+ibrahimovic', e[0], re.I)) Out[172]: ['i want to find a in a big string a sentence containing Zlatan\nIbrahimovic and some other text', 'ie return the first sentence containing the name Zlatan Ibrahimovic', 'zlatan ibrahimovic '] -- _____________ Maric Michaud From grante at visi.com Tue Jun 10 20:50:20 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 10 Jun 2008 19:50:20 -0500 Subject: problems with opening files due to file's path References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> Message-ID: On 2008-06-11, Alexnb wrote: > I am using GUI, Tkinter to be exact. But regardless of how the > path gets there, it needs to opened correctly. The problem I > am running into is that the program receives a path of a file, > either .wma or .mp3 and is supposed to open it. I run into > problems when there is either a ")" or a number next to the > backslash "\" in the file path. I am looking for a way to make > it work with a variable, I can make it work when I physically > type it in, but not with a variable that holds the path. You're going to have to show us code and example input and output. Your description of the problem is far too vague for anybody to help you. -- Grant Edwards grante Yow! With YOU, I can be at MYSELF... We don't NEED visi.com Dan Rather... From kyosohma at gmail.com Fri Jun 27 11:03:19 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 27 Jun 2008 08:03:19 -0700 (PDT) Subject: what is meaning of "@" in pyhon program. References: <88990b3d-1916-413f-83b9-796aabf43623@l28g2000prd.googlegroups.com> Message-ID: <19aa4978-242b-4732-b072-aa5ff16975b0@27g2000hsf.googlegroups.com> On Jun 27, 9:48?am, Evan wrote: > HI, > > When I check example of "cmd2" module (a enhancement of cmd module), I > can not understand all, for example: the ?character "@", > > +++++++++++++++++++++++++++++++++++++++++++++++++++++ > def options(option_list): > ? ? ?.................. > > class cmd(...): > ? ? ............................... > ? ? @options([make_option('-p', '--piglatin', action="store_true", > help="atinLay")]) > +++++++++++++++++++++++++++++++++++++++++++++++++++++ > > I do not understand what "@options" does, ? most time, I know what the > meaning of character "*" and character "**", but I was not use "@" > before. > > Thanks for your help. The "@" sign is there to signify that what follows is a decorator. They're kind of cool and kind of confusing. Basically they dynamically alter a function, method or class and gives them additional functionality. It's kind of like calling a function recursively. Check out the following links: http://www.python.org/dev/peps/pep-0318/ http://wiki.python.org/moin/PythonDecorators http://www.ibm.com/developerworks/linux/library/l-cpdecor.html Mike From madhav.bnk at gmail.com Fri Jun 27 03:03:15 2008 From: madhav.bnk at gmail.com (madhav) Date: Fri, 27 Jun 2008 00:03:15 -0700 (PDT) Subject: Email Bounce Detection Message-ID: Hello everybody, I need a mechanism to detect email bounces. I tried browsing through smtplib implementation and found not helpful in this case. Actually it is said in the documentation that if a mail is sent to say: "somerandomname at randomorg.com", then "_send()" in the SMTPConnection class returns 550(Unknown recceipient). I checked the same but its not returning 550 and return 250(receipient ok). Later, I tried getting the smtp error code from the mail body of a bounced msg. the "Message" class doesnot have any error code attribute by default. We need to get it from the mailbody(by regex ing), which i think is not a valid solution, as "550" can occur anywhere in the body of any message otherthan the bounced msg also. Please help me regarding this. Thanks in advance. From mr.opus.penguin at gmail.com Fri Jun 13 17:23:38 2008 From: mr.opus.penguin at gmail.com (mr.opus.penguin at gmail.com) Date: Fri, 13 Jun 2008 14:23:38 -0700 (PDT) Subject: Python 3000 vs. Python 2.x References: <2c299cdc-adcd-4540-b09f-43b4147e10ca@y21g2000hsf.googlegroups.com> <5087e578-ef11-48c5-97ec-68c4d9d95024@a1g2000hsb.googlegroups.com> Message-ID: <8fd3c5f8-6eff-4e96-917c-e869abcfeb9d@c65g2000hsa.googlegroups.com> On Jun 13, 4:13 pm, Mensanator wrote: > On Jun 13, 4:04 pm, mr.opus.peng... at gmail.com wrote: > > > As a new comer to Python I was wondering which is the best to start > > learning. I've read that a number of significant features have > > changed between the two versions. Yet, the majority of Python > > programs out in the world are 2.x and it would be nice to understand > > those as well. Thanks for all the help. > > > Creosote, > > What 3rd party modules are you planning to use? > > You won't be able to use them until their developers release > Python 3000 versions. > > In my research, I heavily depend on the gmpy module for > fast, number theoretic functions. Last time I checked, > it was only available for v2.5. > > So, I could install v2.6 or v3.0, but I wouldn't be able > to run any of my programs, so what would be the point? Thanks for the advice. I guess I don't really know about what kind of modules I'm going to be using as I'm new to this whole style of programming. The only other languages I've used are Fortran, C, and Lisp. I venture to say that I'd probably be using math, and graphics modules. From admin at vaticans.org Mon Jun 16 15:07:25 2008 From: admin at vaticans.org (vaticans.org) Date: Mon, 16 Jun 2008 12:07:25 -0700 (PDT) Subject: President Bush Meets Pope Before Heading to Paris Message-ID: <4d1becb5-3c8a-40f5-b14a-47430f56c891@w34g2000prm.googlegroups.com> U.S. President George Bush has met with Pope Benedict at the Vatican, as he continues his week-long European trip. After his talks with the pontiff, Mr. Bush was traveling to Paris, France, where he is to give a speech later Friday on the strong relationship between the U.S. and Europe. U.S. National Security Advisor Stephen Hadley said Mr. Bush will urge European leaders to work even more closely with the U.S. to help bring peace to the Middle East. Mr. Hadley said the trans-Atlantic relationship has been strengthened by the current leaders in Italy, Britain, Germany, and France. The White House says Mr. Bush's speech will also commemorate the 60th anniversary of the Marshall Plan - the U.S. aid program that helped rebuild Europe after the devastation caused by World War II. The president and Mrs. Bush are then scheduled to have dinner with the French president and Mrs. Sarkozy at the Elysee Palace. Mr. Bush and Mr. Sarkozy hold formal talks on Saturday. On Thursday President Bush met with Italian Prime Minister Silvio Berlusconi and the two leaders agreed to to work together on trying to convince Iran to give up its uranium enrichment program. Mr. Berlusconi said Italy has a trading relation with Iran and knows that country from the inside. President Bush said he will consider Italy's request to join the five permanent U.N. Security Council members and Germany in working on the Iran nuclear issue. But Mr. Hadley said it is always a problem when a country's commercial ties clashes with its national security requirements. Mr. Bush's European trip will also take him to Britain and Northern Ireland. Earlier, he stopped in Germany and attended the annual U.S.- European Union summit in Slovenia. http://www.vaticans.org/index.php?/archives/1175-Pope-Benedict-XVI-hosted-US-President-George-W.-Bush-at-the-Vatican.html From robert.kern at gmail.com Fri Jun 27 20:14:45 2008 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 27 Jun 2008 19:14:45 -0500 Subject: warning for unused packages/modules/objects In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > How difficult would it be to implement a system in python that would > warn if there are unnecessarily imported packages/modules/objects in > the code? I mean that when developing some code one frequently imports > stuff, deletes the import, changes stuff here and there, imports other > stuff, later decides to change things and consequently delete the line > with the import, etc, etc. As a result there can stay > packages/modules/objects that are in the end not used. It would be > great if python would issue a warning once the program finishes. Style-checkers will help with this. pylint, pychecker, and pyflakes are all good tools. I tend to use pyflakes most often. It's small and doesn't do as much as the others, but it does unused imports and undefined name checks much faster than the others. I can run it compulsively on my file. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From circularfunc at yahoo.se Tue Jun 3 09:14:37 2008 From: circularfunc at yahoo.se (circularfunc at yahoo.se) Date: Tue, 3 Jun 2008 06:14:37 -0700 (PDT) Subject: Webpy vs Django? Message-ID: <7db4dfb2-1e50-4a89-a47b-7356119b2741@r66g2000hsg.googlegroups.com> i have been trying to get Django running for 2 days now and it drives me crazy. i played with webpy a bit and it is easy to get going with. but django seems like once you have it all up and running it will be easier. just that the barrier of entry is much higher. is django worth it? seems so ridicoulusly hard to get it running. i run into trouble every time i advance a little, firstin the installationa nd now in the tutorial(creating polls). what do you think of webpy for big projects that need performance? From frank at chagford.com Mon Jun 9 10:06:15 2008 From: frank at chagford.com (Frank Millman) Date: Mon, 9 Jun 2008 07:06:15 -0700 (PDT) Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: <41de7980-749a-4f46-add1-12010b6e95d9@b1g2000hsg.googlegroups.com> On Jun 9, 3:07?pm, Mel wrote: > Frank Millman wrote: > > > class Number(object): > > ? ? def __init__(self,value,scale): > > ? ? ? ? self.factor = 10.0**scale > > ? ? ? ? if isinstance(value,Number): > > ? ? ? ? ? ? value = value.value / value.factor > > I think this could lead to trouble. ?One complaint against binary floating > point is that it messes up low-order decimal digits, and this ensures that > all calculations are effectively done in binary floating point. ?Better, I > think would be > > ? ? ? ? if isinstance (value, Number): > ? ? ? ? ? ? self.value = value.value > ? ? ? ? ? ? self.scale = scale + value.scale > > and be done with it. > Thanks for the reply, Mel. I don't quite understand what you mean. Bear in mind my next line, which you did not quote - if isinstance(value,Number): value = value.value / value.factor --> self.value = long(round(value * self.factor)) I do understand that binary floating point does not always give the expected results when trying to do decimal arithmetic. However, given a float f1 and a scaling factor s, I thought that if I did the following - i1 = long(round(f1 * s)) # scale up to integer f2 = i1 / s # reduce back to float i2 = long(round(f2 * s)) # scale up again then i2 would always be equal to i1. If you are saying that there could be situations where this is not guaranteed, then I agree with you that what I have written is dangerous. I will do some more testing to see if this could happen. I suppose that if the scaling factor is very high it could cause a problem, but I cannot envisage it exceeding 6 in my application. Thanks Frank From chrispoliquin at gmail.com Mon Jun 23 20:26:10 2008 From: chrispoliquin at gmail.com (chrispoliquin at gmail.com) Date: Mon, 23 Jun 2008 17:26:10 -0700 (PDT) Subject: very large graph Message-ID: <135bba90-a9dd-4fcd-9220-6271e5a7c876@59g2000hsb.googlegroups.com> I need to represent the hyperlinks between a large number of HTML files as a graph. My non-directed graph will have about 63,000 nodes and and probably close to 500,000 edges. I have looked into igraph (http://cneurocvs.rmki.kfki.hu/igraph/doc/ python/index.html) and networkX (https://networkx.lanl.gov/wiki) for generating a file to store the graph, and I have also looked into Graphviz for visualization. I'm just not sure which modules are best. I need to be able to do the following: 1) The names of my nodes are not known ahead of time, so I will extract the title from all the HTML files to name the nodes prior to parsing the files for hyperlinks (edges). 2) Every file will be parsed for links and nondirectional connections will be drawn between the two nodes. 3) The files might link to each other so the graph package needs to be able to check to see if an edge between two nodes already exists, or at least not double draw connections between the two nodes when adding edges. I'm relatively new to graph theory so I would greatly appreciate any suggestions for filetypes. I imagine doing this as a python dictionary with a list for the edges and a node:list paring is out of the question for such a large graph? From code at pizzashack.org Tue Jun 17 08:09:41 2008 From: code at pizzashack.org (Derek Martin) Date: Tue, 17 Jun 2008 08:09:41 -0400 Subject: Does '!=' equivelent to 'is not' In-Reply-To: References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> Message-ID: <20080617120941.GE7349@dragontoe.org> On Tue, Jun 17, 2008 at 04:33:03AM -0300, Gabriel Genellina wrote: > > Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)' > > and 'not(id(a) == id(b))' > > No. Sure it is... he said "similar"... not identical. They are not the same, but they are similar. Saying a flat "no" alone, without qualifying your statement is generally interpreted as rude in English... It's kind of like how you talk to children when they're too young to understand the explanation. Yucky. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From Lie.1296 at gmail.com Sun Jun 8 04:11:23 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 8 Jun 2008 01:11:23 -0700 (PDT) Subject: File-writing not working in Windows? References: <80a7b951-591b-41a2-b76c-f97d75db0dad@25g2000hsx.googlegroups.com> Message-ID: <5c4313fb-3672-4b03-9d62-58fd6e3a76bd@w34g2000prm.googlegroups.com> On Jun 6, 10:18?pm, tda... at gmail.com wrote: > All, > > I have the following code: > ? ? ? ? ? ?for fileTarget in dircache.listdir("directory"): > ? ? ? ? ? ? ? ? (dirName, fileName) = os.path.split(fileTarget) > ? ? ? ? ? ? ? ? f = open(fileTarget).readlines() > ? ? ? ? ? ? ? ? copying = False > ? ? ? ? ? ? ? ? for i in range(len(f)): > ? ? ? ? ? ? ? ? ? ? for x in range (0,24,1): > ? ? ? ? ? ? ? ? ? ? ? ? if (re.search(self.Info[x][3], f[i])): > #If we have a match for our start of section... > ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (self.Info[x][2] == True): > #And it's a section we care about... > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? copying = > True ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?#Let's start copying the lines out > to the temporary file... > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (os.name == "posix"): > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (self.checkbox25.GetValue() == > False): > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? tempfileName = "tempdir/" + > self.Info[x][0] + "_tmp_" + fileName + ".txt" > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? tempfileName = > self.textctrl07.GetValue() + "/" + self.Info[x][0] + "_xyz.txt" > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (self.checkbox25.GetValue() == > False): > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? tempfileName = "tempdir\\" + > self.Info[x][0] + "_tmp_" + fileName + ".txt" > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? tempfileName = > self.textctrl07.GetValue() + "\\" + self.Info[x][0] + "_xyz.txt" > ? ? ? ? ? ? ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? copying = False > ? ? ? ? ? ? ? ? ? ? ? ? if (re.search(self.Info[x][4], f[i])): > #Now we've matched the end of our section... > ? ? ? ? ? ? ? ? ? ? ? ? ? ? copying = > False ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #So let's stop copying out to > the temporary file... > ? ? ? ? ? ? ? ? ? ? if (copying == True): > ? ? ? ? ? ? ? ? ? ? ? ? g = open(tempfileName, > 'a') ? ? ? ? ? ? ? ? ? ? #Open that file in append mode... > > g.write(f[i]) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #Write the line... > ? ? ? ? ? ? ? ? ? ? ? ? g.close() > > This code works PERFECTLY in Linux. ?Where I have a match in the file > I'm processing, it gets cut out from the start of the match until the > end of the match, and written to the temporary file in tempdir. > > It does not work in Windows. ?It does not create or write to the > temporary file AT ALL. ?It creates the tempdir directory with no > problem. > > Here's the kicker: it works perfectly in Windows if Windows is running > in VMware on a Linux host! ?(I assume that that's because VMware is > passing some call to the host.) > > Can anyone tell me what it is that I'm missing which would prevent the > file from being created on Windows natively? > > I'm sorry I can't provide any more of the code, and I know that that > will hamper your efforts in helping me, so I apologise up front. > > Assumptions: > You can assume self.checkbox25.GetValue() is always false for now, and > self.Info[x][0] contains a two character string like "00" or "09" or > "14". ?There is always a match in the fileTarget, so self.Info[x][2] > will always be true at some point, as will self.Info[x][4]. ?I am > cutting an HTML file at predetermined comment sections, and I have > control over the HTML files that are being cut. ?(So I can force the > file to match what I need it to match if necessary.) > > I hope however that it's something obvious that a Python guru here > will be able to spot and that this n00b is missing! > > Thanks! Well, not to be rude, but that's quite a spaghetti code, some of the guilt, however, was for the mailing program that cuts 80+ lines. Others was the use of things like "for i in range(len(f)):" or "if (a == True)". Try checking whether you're trying to write to a path like r"\dir \file.txt" or r"dir\file.txt" instead of r"C:\dir\file.txt" in Windows. If that doesn't solve the problem, tell us a few things: - Any error messages? Or simply nothing is written out? - Has a blank file get created? From ayushi.mehra at gmail.com Wed Jun 11 03:44:09 2008 From: ayushi.mehra at gmail.com (Ayushi Mehra) Date: Wed, 11 Jun 2008 00:44:09 -0700 (PDT) Subject: Asus F5RL 99D Notebook(Laptop) Message-ID: <781a7864-aba6-40d1-adbe-219046db75b2@z24g2000prf.googlegroups.com> This laptop comes with Intel 1.6GHz Dual Core Processor, 1GB RAM and 120GB HDD. It has a DVD Writer, 15.4-inch widescreen display with a resolution of 1280 x 800 dpi. The laptop also has an integrated ATI X300 video card, integrated modem and sound card, Wifi, Touchpad mouse, in-built speakers, 4 USB ports and 4 in 1 Digital Media Reader. The laptop comes with an inbuilt 1.3 megapixel camera powered by Lithium Ion battery. To buy this Asus F5RL 99D Notebook(Laptop) please visit: http://www.naaptol.com/buy-online/WO-best-deals-shopping-W12021O/computers_-_peripherals/laptops/asus_f5rl_99d_notebook.html4g.html From fetchinson at googlemail.com Mon Jun 23 19:00:29 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 23 Jun 2008 16:00:29 -0700 Subject: Connecting a Desktop App to a Web App In-Reply-To: References: <61460E55-28FD-42A3-85EB-4D352E21CC30@gmail.com> Message-ID: >>> Okay, well I wouldn't be creating the app, so, any hints on how to >>> figure out the API of a web app I don't know super well? >> >> Is it something like google, youtube, facebook, etc? These have >> publicly available API specifications. >> >> If it's just a random website without a well maintained public API you >> would look at the html source of the upload page and see what >> name:value pairs are sent along with the file from the form that does >> the upload. Then you would create such a POST request from python. >> >> Cheers, >> Daniel >> -- >> Psss, psss, put it down! - http://www.cafepress.com/putitdown > Okay, well I looked into it a little more, and found out that this > site already has an upload client so I am not going to make this. > Instead something I really have wanted to figure out for a while would > be an app where the user inputs a series of words and then they are > submitted into dictionary.com or something like that and then the > definitions are returned. How would you suggest going about this? Please keep the discussion on the list. You would go to dictionary.com, see (1) how the words are entered by a user who is using a web browser, what the names are of each field the browser is submitting, then (2) look at the returned html page and see how the actual definition is embedded in there. Then from your knowledge of (1) you would create an appropriate http request in python, send it to dictionary.com, get the response and once you know (2) you write a parser (using elementtree for example) that parses the response and gets your definition. HTH, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From __peter__ at web.de Wed Jun 18 03:21:38 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 18 Jun 2008 09:21:38 +0200 Subject: Save turtle state? References: Message-ID: Allen wrote: > I'm using the turtle module in Python. Is there a way to save the turle > state at any moment for recursive algorithms to easily return the turtle > to an earlier point for another branch/etc? Just copying the turtle seems to work: import turtle from copy import copy def rec(t, n): t.forward(n) n = (n*4)/5 u = copy(t) u.color("red") u.right(45) if n > 10: rec(u, n) def main(): t = turtle.Turtle() t.color("green") for i in range(12): t.left(30) rec(t, 50) main() raw_input() Peter From agus at cs.its.ac.id Wed Jun 4 09:45:23 2008 From: agus at cs.its.ac.id (agus at cs.its.ac.id) Date: Wed, 4 Jun 2008 20:45:23 +0700 (WIT) Subject: How to make one program connect to more than one TCP? Message-ID: <1361.222.124.226.218.1212587123.squirrel@webmail.its.ac.id> The questions: I am using twisted to make program that can download IMAP email. after that, downloaded email is parsed, then posted to nntp server. my problem is how to make one progam connect to more than one tcp? From sawmyaaa at gmail.com Sat Jun 7 09:44:07 2008 From: sawmyaaa at gmail.com (sawmyaa) Date: Sat, 7 Jun 2008 06:44:07 -0700 (PDT) Subject: You can earn Rs.25000 very month from internet. This is easy form filling jobs. Work less than 1 hr daily. No investment. Please visit the website http://mahesbiotech.googlepages.com/You can earn Rs.25000 very month from internet. This is easy form filling jobs. Work less than 1 hr daily. No investment. Please visit the website http://mahesbiotech.googlepages.com/ Message-ID: <1aba1ce9-5d24-47b5-920c-56f629283f12@v26g2000prm.googlegroups.com> You can earn Rs.25000 very month from internet. This is easy form filling jobs. Work less than 1 hr daily. No investment. Please visit the website http://mahesbiotech.googlepages.com/ From johnjsal at gmailNOSPAM.com Mon Jun 23 17:51:50 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Mon, 23 Jun 2008 17:51:50 -0400 Subject: Using Python to run SSH commands on a remote server In-Reply-To: References: <03a078c8$0$3229$c3e8da3@news.astraweb.com> <86adnQ8H4MFYdcLVnZ2dnUVZ_sHinZ2d@cablespeedwa.com> <03a08853$0$3220$c3e8da3@news.astraweb.com> Message-ID: <48601b32$0$7361$607ed4bc@cv.net> Jeffrey Froman wrote: > Also note that "all .py files on my web server" is not necessarily > restricted to CGI scripts -- and therein lies the real gist of my > cautionary note. > Yeah, I realized that afterwards. Good point. I was assuming all my executable files would be CGI, but that's not a good assumption to make! :) From zephyrfalcon!NO_SPAM! at gmail.com Fri Jun 6 18:12:19 2008 From: zephyrfalcon!NO_SPAM! at gmail.com (Hans Nowak) Date: Fri, 06 Jun 2008 18:12:19 -0400 Subject: Newbie question, list comprehension In-Reply-To: <3rooh5xmap.ln2@joeserver.homelan.net> References: <3rooh5xmap.ln2@joeserver.homelan.net> Message-ID: Johannes Bauer wrote: > Hello group, > > I'm currently doing something like this: > > import time > localtime = time.localtime(1234567890) > fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % (localtime[0], localtime[1], > localtime[2], localtime[3], localtime[4], localtime[5]) > print fmttime > > For the third line there is, I suppose, some awesome python magic I > could use with list comprehensions. I tried: > > fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % ([localtime[i] for i in > range(0, 5)]) The % operator here wants a tuple with six arguments that are integers, not a list. Try: fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % tuple(localtime[i] for i in range(6)) > As it appearently passed the while list [2009, 02, 14, 0, 31, 30] as the > first parameter which is supposed to be substituted by "%04d". Is there > some other way of doing it? In this case, you can just use a slice, as localtime is a tuple: fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % localtime[:6] Hope this helps! ^_^ -- Hans Nowak (zephyrfalcon at gmail dot com) http://4.flowsnake.org/ From socyl at 987jk.com.invalid Sun Jun 8 12:52:54 2008 From: socyl at 987jk.com.invalid (kj) Date: Sun, 8 Jun 2008 16:52:54 +0000 (UTC) Subject: Need help porting Perl function References: <379fb630-5a4c-44e6-920e-3de7acd6bfd4@z24g2000prf.googlegroups.com> <8bb0b0ce-e840-416f-b9c1-4092fd5fa771@56g2000hsm.googlegroups.com> <7248c81b-0ff9-45f5-acb5-63a8b2d41817@f24g2000prh.googlegroups.com> Message-ID: In kj writes: >In <7248c81b-0ff9-45f5-acb5-63a8b2d41817 at f24g2000prh.googlegroups.com> John Machin writes: >>It's nothing to do with list comprehensions, which are syntactical >>sugar for traditional loops. You could rewrite your list comprehension >>in the traditional manner... >>and it would still fail for the same reason: mutating the list over >>which you are iterating. >I normally deal with this problem by iterating backwards over the >indices. Here's how I coded the function (in "Python-greenhorn >style"): ***BLUSH*** Somehow I missed that John Machin had posted almost the exact same implementation that I posted in my reply to him. Reading too fast. Reading too fast. Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From jr9445 at ATT.COM Tue Jun 3 16:13:51 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Tue, 3 Jun 2008 15:13:51 -0500 Subject: New variable? In-Reply-To: <18105511-7ae1-45e9-8c43-f34c1c4f5aeb@c58g2000hsc.googlegroups.com> References: <18105511-7ae1-45e9-8c43-f34c1c4f5aeb@c58g2000hsc.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of tmallen > Sent: Tuesday, June 03, 2008 2:41 PM > To: python-list at python.org > Subject: New variable? > > What's the proper way to instantiate a new variable? x = ""? I've always used X = None in those cases where I need to pre-declare a variable to set scope. ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA623 From george.sakkis at gmail.com Mon Jun 9 16:37:07 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 9 Jun 2008 13:37:07 -0700 (PDT) Subject: Web Crawler - Python or Perl? References: Message-ID: <0a2b1cf7-4f47-41aa-8cdf-901eb3c3a820@f63g2000hsf.googlegroups.com> On Jun 9, 1:48 pm, disappeare... at gmail.com wrote: > Hi all, > I am currently planning to write my own web crawler. I know Python but > not Perl, and I am interested in knowing which of these two are a > better choice given the following scenario: > > 1) I/O issues: my biggest constraint in terms of resource will be > bandwidth throttle neck. > 2) Efficiency issues: The crawlers have to be fast, robust and as > "memory efficient" as possible. I am running all of my crawlers on > cheap pcs with about 500 mb RAM and P3 to P4 processors > 3) Compatibility issues: Most of these crawlers will run on Unix > (FreeBSD), so there should exist a pretty good compiler that can > optimize my code these under the environments. > > What are your opinions? You mentioned *what* you want but not *why*. If it's for a real-world production project, why reinvent a square wheel and not use (or at least extend) an existing open source crawler, with years of development behind it ? If it's a learning exercise, why bother about performance so early ? In any case, since you said you know python but not perl, the choice is almost a no-brainer, unless you're looking for an excuse to learn perl. In terms of performance they are comparable, and you can probably manage crawls in the order of 10-100K pages at best. For million-page or larger crawls though, you'll have to resort to C/C++ sooner or later. George From kretik at yahoo.com Tue Jun 17 01:29:47 2008 From: kretik at yahoo.com (kretik) Date: Mon, 16 Jun 2008 22:29:47 -0700 Subject: string.Template.delimiter cannot be overriden? In-Reply-To: <35e212be-e85b-41fd-90c2-f90959053232@l28g2000prd.googlegroups.com> References: <4rH5k.2032$to3.1384@newsfe15.phx> <35e212be-e85b-41fd-90c2-f90959053232@l28g2000prd.googlegroups.com> Message-ID: Raymond Hettinger wrote: > On Jun 16, 9:53 pm, kretik wrote: >> I've been trying to coax this class to use something other than the >> default '$' but it seems setting it to something else has no discernible >> effect. Is it necessary to inherit from the class to do this? > > Yes, subclassing is the intended way to produce variants of Template > with a different delimiter. OK, that makes no sense but I guess it's some sort of pythonistic thing or something =) Thanks a lot for the response. From bignose+hates-spam at benfinney.id.au Tue Jun 3 23:50:42 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 04 Jun 2008 13:50:42 +1000 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> Message-ID: <873antn9il.fsf@benfinney.id.au> alex23 writes: > So the basic answers I'm seeing that "do just fine" are: > > 1. Don't test private functions. > 2. Add functionality _to_ the private functions for testing. > 3. Change the interface for the purpose of testing. > > All of which seem exceptionally inefficient and run counter to the > whole purpose of unit testing. It seems you have a different idea of what unit testing is for from me. Isn't the entire point of encapsulation to separate internal components from the external interface? Why would a unit test, the whole purpose of which is to assert some aspect of the external behaviour of the unit of code, care about how that code unit is implemented internally? If changing the internal, encapsulated components of a unit causes its external behaviour to change, that's a bug; either in the change made (it shouldn't have altered the external behaviour), or in the unit test asserting the wrong thing (it shouldn't be asserting anything about internal state of the code). -- \ ?Try to become not a man of success, but try rather to become | `\ a man of value.? ?Albert Einstein | _o__) | Ben Finney From circularfunc at yahoo.se Thu Jun 19 18:31:37 2008 From: circularfunc at yahoo.se (cirfu) Date: Thu, 19 Jun 2008 15:31:37 -0700 (PDT) Subject: Google-like "Did you mean... ?" search algorithm References: <7a8313a1-1536-4754-ab4d-9cce4fa1b31a@y38g2000hsy.googlegroups.com> Message-ID: <3aa72024-7429-4e42-88d0-565e6014b2d5@34g2000hsh.googlegroups.com> On 20 Juni, 00:14, miller.pau... at gmail.com wrote: > This is a wee bit OT, but I am looking for algorithms to implement > search suggestions, similar to Google's "Did you mean... ?" feature. > Can anyone point me to web pages, journal articles, implementations > (preferably in Python!), or any other resources in this area? > > Thanks! if you mean a spellchecker check peter norvigs homepage. http://norvig.com/spell-correct.html From python at rcn.com Wed Jun 4 07:24:43 2008 From: python at rcn.com (Raymond Hettinger) Date: Wed, 4 Jun 2008 04:24:43 -0700 (PDT) Subject: defaultdict.fromkeys returns a surprising defaultdict References: Message-ID: <5cf9282c-73f3-4df6-9cff-f0cca717e91e@w34g2000prm.googlegroups.com> On Jun 3, 1:11?pm, Matthew Wilson wrote: > I used defaultdict.fromkeys to make a new defaultdict instance, but I > was surprised by behavior: > > ? ? >>> b = defaultdict.fromkeys(['x', 'y'], list) > > ? ? >>> b > ? ? defaultdict(None, {'y': , 'x': }) > > ? ? >>> b['x'] > ? ? > > ? ? >>> b['z'] > ? ? ------------------------------------------------------------ > ? ? Traceback (most recent call last): > ? ? ? File "", line 1, in > ? ? KeyError: 'z' > > I think that what is really going on is that fromdict makes a regular > dictionary, and then hands it off to the defaultdict class. Nope. It works like this: def fromkeys(iterable, value): d = defaultdict(None) for k in iterable: d[k] = value return d Use fromkeys() to set all entries to a single specific value. Remember that setting an entry never triggers the default factory; instead, it is triggered on the *lookup* of a missing key. To do what you likely intended, don't use fromkeys(). Instead write something like: d = defaultdict(list) for elem in iterable: d[elem] # factory triggered by lookup of missing key > I find this confusing, because now I have a defaultdict that raises a > KeyError. It is only confusing because you had already convinced yourself that the second argument in fromkeys() was the default factory function. Of course, its real meaning is the single value assigned by fromkeys for every insertion (the same way it works for regular dicts). Once you realize that the second argument was the single assigned value, it is easy to understand that the default factory function is None and that its documented behavior is to raise a KeyError when a missing key is looked-up. The confusion is mostly based on a misunderstanding of how defaultdicts work (calling a factory whenever a missing key is looked- up, not when it is inserted). It is alo based on a misunderstanding of what fromkeys does (assign the same value over and over for each key in the input interable). Given those two misconceptions, confusion over the result was inevitable. > Would it be better if defaultdict.fromkeys raised a > NotImplementedException? No. It is a dict subclass and should provide all of those methods. Also, it is useful in its current form. > Or would it be better to redefine how defaultdict.fromkeys works, so > that it first creates the defaultdict, and then goes through the keys? > > All comments welcome. ?If I get some positive feedback, I'm going to try > to submit a patch. No need. The patch would be rejected. It would break existing code that uses default.fromkeys() as designed and documented. Raymond From Scott.Daniels at Acm.Org Sat Jun 28 11:00:43 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 28 Jun 2008 08:00:43 -0700 Subject: where is the error? In-Reply-To: <6a8b6c1c-c74c-448d-89c7-01dd5c3b4a40@m45g2000hsb.googlegroups.com> References: <8f8e1bf7-78b0-4292-9d56-396527b9dfb1@z66g2000hsc.googlegroups.com> <15ea1cb1-76a3-4fd3-8e4c-521b9aefcca2@m3g2000hsc.googlegroups.com> <6a8b6c1c-c74c-448d-89c7-01dd5c3b4a40@m45g2000hsb.googlegroups.com> Message-ID: <_OydnWnp8Psi0vvVnZ2dnUVZ_hninZ2d@pdx.net> lajam at caramail.com wrote: > ... And my problem was that the commands worked on windows but not on > linux. > >> By the way, shouldn't you be using numpy? I thought numarray was going >> away by mid-2008 i.e. now. > I know, but i'm not sure that it's the problem. It's your job to get certain of some things, and what people are proposing are experiments you can do to find the answer. The problem is yours, the benefit of having the code work will be yours, and you, unlike us, are in a position to perform experiments. Don't be as vague as "the commands worked on windows but not on linux." That kind of statement is usually a flag that you _think_ you typed the same thing. Write a complete, small test program that demonstrates your success on XP. Move the program to Ubuntu (remembering about line endings) via flash drive or something. Run _exactly_ the same program on Ubuntu. If you get a failure, keep trimming the program on Ubuntu til you find the smallest program that breaks. Take it back to XP and make sure it still runs there. Don't give partial version information. I know you have two systems: Ubuntu (who knows what version), python 2.4.3, numarray who knows. The Windows box is running XP, but what service pack? what version of Python on XP? What version of numarray on XP? In collecting all of this information _before_ you ask, you often discover the answer to your question without needing to ask anyone else. If numpy might solve your problem, why avoid trying it simply because it might not do so? Sorry, this a long form of "read smart questions," but it did include some suggestions about how you could find the problem in your particular case. --Scott David Daniels Scott.Daniels at Acm.Org From cwitts at gmail.com Wed Jun 11 04:47:28 2008 From: cwitts at gmail.com (Chris) Date: Wed, 11 Jun 2008 01:47:28 -0700 (PDT) Subject: can't assign to literal References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> <1a244dc4-4d10-491d-8ec7-224f3a1f0df5@m73g2000hsh.googlegroups.com> Message-ID: <8264ea7d-50ce-4fac-9b59-1acbcbafcbb2@w7g2000hsa.googlegroups.com> On Jun 11, 10:32?am, MRAB wrote: > On Jun 10, 10:57 pm, "Steven Clark" wrote: > > > > for 1 in oids, vals head_oids: > > > SyntaxError: can't assign to literal > > > -- > > > 1 is a literal, you can't assign it to something. Are you trying to > > use it as a variable name? > > Slightly OT, but is there an editor that can display digits in a > different colour to letters? SciTE and Notepad++ which are just 2 of the editors installed on my PC currently. From gagsl-py2 at yahoo.com.ar Fri Jun 13 20:35:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Jun 2008 21:35:36 -0300 Subject: Subclassing list, what special methods do this? References: <7ba7e964-2d34-4594-8cfc-79dbf904df18@f63g2000hsf.googlegroups.com> Message-ID: En Fri, 13 Jun 2008 15:38:15 -0300, Mike Kent escribi?: > For Python 2.5 and new-style classes, what special method is called > for mylist[2:4] = seq and for del mylist[2:4] (given that mylist is a > list, and seq is some sequence)? > > I'm trying to subclass list, and I'm having trouble determining what > special methods I have to override in my class for the above two > operations. From my testing, it seems to be __setslice__ for both, > but the docs say __setslice__ and brethren are deprecated. I would > have thought that __setitem__ and __delitem__ would be what was > called, but again, my testing says otherwise. __setslice__ and __delslice__, *and* __setitem__/__delitem__ for extended slice notation. The first two are deprecated, but since the list type implements them you have to do the same, because the interpreter invokes those methods when they exist, even if found in a base class. -- Gabriel Genellina From fc14301589 at icqmail.com Sat Jun 14 05:51:36 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Sat, 14 Jun 2008 17:51:36 +0800 Subject: Debuggers References: <485220ca_1@news.tm.net.my> Message-ID: <485394a8_1@news.tm.net.my> On 19:21, venerd? 13 giugno 2008 R. Bernstein wrote: > I'm not completely sure what you mean, but I gather that in > post-mortem debugging you'd like to inspect local variables defined at the > place of error. Yes, exactly. This can be seen with pdb, but not pydb. If I'm testing a piece of code and it breaks, then I'd like to see the variables and find which of them doesn't go as expected. > Python as a language is a little different than say Ruby. In Python > the handler for the exception is called *after* the stack is unwound I'm not doing comparison with other languages. I'm simply curious to know why pydb don't keep variables like pdb. Final, I agreed the idea to restart the debugger when an exception is trow. It could be feasible to let reload the file and restart. Some time I can re-run the program , as the error is fixed, but sometime pdb doesn't recognize the corrections applied. I mean that after a post-mortem event, the debugger should forget all variables and reload the program, which meanwhile could be debugged. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From ebgssth at gmail.com Sun Jun 15 12:01:47 2008 From: ebgssth at gmail.com (js) Date: Mon, 16 Jun 2008 01:01:47 +0900 Subject: The best way to package a Python module? Message-ID: Hi list, I'm trying to build a package for python modules. When I just wanted to have a package for Python2.5, this is an easy task, but in most cases, it's not enough. Sometimes I need python2.4, 2.5, 2.6 or 3.0 etc. The problem is coming from the fact that python installs its modules into version-independent place as follow. $prefix/lib/python2.4/site-package/ $prefix/lib/python2.5/site-package/ For this, I have to create a package for each version. Let's say if I need a module called "spam" and installed spam with python2.5. The files would be installed in $prefix/lib/python2.5/site-package/. It only usable from python2.5. When I need it for python2.4, I have to prepare the same package for python2.4, the only difference is the place it installed. This is the problem I'm having now. How can I avoid this redundant work? Any advice, suggestions would be greatly appreciated. Thanks! From joe.p.cool at googlemail.com Sat Jun 28 17:06:46 2008 From: joe.p.cool at googlemail.com (Joe P. Cool) Date: Sat, 28 Jun 2008 14:06:46 -0700 (PDT) Subject: surprising behaviour of os.environ.clear References: <463baf33-e2d5-41fd-839e-aae45ee5433e@b1g2000hsg.googlegroups.com> Message-ID: <52ecaa6c-b476-4720-9fd4-362471c2686e@k13g2000hse.googlegroups.com> On 28 Jun., 04:05, Benjamin wrote: > On Jun 27, 4:05 pm, "Joe P. Cool" wrote: > This is because of how os.environ is implement with a UserDict > subclass. You should report this at bugs.python.org. issue 3227: os.environ.clear has no effect on child processes -- Joe From serbulentu at gmail.com Mon Jun 23 14:52:48 2008 From: serbulentu at gmail.com (python_newbie) Date: Mon, 23 Jun 2008 11:52:48 -0700 (PDT) Subject: insertion sorts... Message-ID: <06adb999-c7e2-4475-a49f-dbfbe042f4fd@r66g2000hsg.googlegroups.com> I don't know this list is the right place for newbie questions. I try to implement insertion sort in pyhton. At first code there is no problem. But the second one ( i code it in the same pattern i think ) doesn't work. Any ideas ? ------------------------------------------------------------ def insertion_sort(aList): for i in range(len(aList)): for j in range(i): if aList[i] < aList[j]: aList.insert(j,aList[i]) del aList[i+1] if __name__ == "__main__": MyList = [7,3,5,19,8,2,9,4,15,6,8,3,19] insertion_sort(MyList) print MyList ------------------------------------------------------------- def insertion_sort(aList): for iterator in aList: for number in range(aList.index(iterator)): if iterator < number: aList.insert(aList.index(number),iterator) del aList[aList.index(iterator)+1] if __name__ == "__main__": MyList = [7,3,5,19,8,2,9,4,15,6,8,3,19] insertion_sort(MyList) print MyList From ram.rachum at gmail.com Sun Jun 15 07:29:01 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Sun, 15 Jun 2008 04:29:01 -0700 (PDT) Subject: 32 bit or 64 bit? Message-ID: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> Quick question: I have python code that does a lot of floating point arithmetic. How do I make it do the arithmetic in 64 bit? (I have a 64 bit CPU.) If I'll install a 64-bit operating system, will that do the trick? From mensanator at aol.com Fri Jun 6 21:01:45 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 6 Jun 2008 18:01:45 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> Message-ID: On Jun 6, 1:40?pm, The Pythonista wrote: > On Thu, 05 Jun 2008 23:42:07 -0400, John Salerno wrote: > > Is it possible to write a list comprehension for this so as to produce a > > list of two-item tuples? > > > base_scores = range(8, 19) > > score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] print zip(base_scores, > > score_costs) > > score_costs = [(base_scores[i], score_costs[i]) for i in range (len > (base_scores))] What happens if your iterables aren't the same length? > > But, I'd rather just use zip. :-) And with zip() you won't get an error, but it won't be correct, either. > > -- > code.py: A blog about life, the universe, and Python > > http://pythonista.wordpress.com > ** Posted fromhttp://www.teranews.com** From maric at aristote.info Fri Jun 27 23:09:29 2008 From: maric at aristote.info (Maric Michaud) Date: Sat, 28 Jun 2008 05:09:29 +0200 Subject: Do I need "self" and "other"? In-Reply-To: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> Message-ID: <200806280509.30591.maric@aristote.info> Le Saturday 28 June 2008 00:17:33 Kurda Yon, vous avez ?crit?: > class Vector: > ? def __add__(self, other): > ? ? data = [] > ? ? for j in range(len(self.data)): > ? ? ? data.append(self.data[j] + other.data[j]) > ? ? return Vector(data) > > In this example one uses "self" and "other". Does one really need to > use this words? Yes, he does, because one really need to follow the conventions of a language, which belong to the language even they don't belong to its syntax. You should have a look to the PEP 8 : http://www.python.org/dev/peps/pep-0008/ self is the good name for the implicit argument of instancemethod. other is the name widely used for rvalue in binary operators definition. As for convention, your constructor, Vector(iterable), is expected to be a copy constructor, that means the Vector's __init__ method is somewhat like this : def __init__(self, iterable=()) : self.data=list(iterable) # create a copy of the parmeter First, self.data should be renamed to self._data, see PEP 8 for details, because data will probably not be part of the API of your object. Then, this make your code a bit curious, you create a list to add the two vectors, then copy it to create the resultiing vector, consuming two times the memory needed. Finally, you would probably gain in inheriting directly from the builtin type list. Here is my proposal for your Vector class (wth some other enhancements) : class Vector(list) : def __init__(self, iterable=()) : def __init__(self, iterable=()) : list.__init__(self, iterable) def __repr__(self) : return 'Vector(%s)' % list.__repr__(self) def __add__(self, other) : res = Vector() for i, elt in enumerate(self) : res.append(elt + other[i]) return res Note that I don't know how you want to deal vectors of different dimensions, you should probably raise a ValueError. Also use enumerate, "i in xrange(len(iterable))" was required before enumerate was done a builtin but is rather ugly. Finally, to come to a more functionnal style the method could have been written like this : from itertools import izip ... def __add__(self, other) : return Vector(x + y for x, y in izip(self, other)) -- _____________ Maric Michaud From grante at visi.com Wed Jun 4 10:41:07 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 04 Jun 2008 09:41:07 -0500 Subject: can python do some kernel stuff? References: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> <48366cfa$0$15168$607ed4bc@cv.net> <28c432f0-657c-4272-8cd4-a9081b013279@w5g2000prd.googlegroups.com> <69nigsF3499pqU2@mid.uni-berlin.de> <4836994e$0$11625$607ed4bc@cv.net> <69nls3F344g2cU1@mid.uni-berlin.de> <4836a876$0$11623$607ed4bc@cv.net> Message-ID: >> The answer is yes. IPC and py-pf are examples. If you don't >> think of packet filtering as kernel coding, I can understand. >> But clearly the Python interfaces to fork(), waitpid(), >> signal(), alarm() and so forth are forays into the once >> private garden of C. The routines listed above aren't in the kernel. They're in libc just like routines such as printf, memcpy, etc. The above libc routines do make system calls into the kernel to perform the desired functions, but those routines are not in the kernel, and calling them is certainly not "kernel coding". Yes, Python provides specific wrappers for many C library functions. Yes, the ctypes module provides a generic method for calling foreign library functions. No, using those wrappers is not what anybody I know would call "kernel coding". > Being able to call routines in the kernel is *not* the same as > kernel coding. As far as I know, Python doesn't provide the user with the ability to make system calls into the kernel. Even if it did, that isn't really "kernel coding" either. It's just making system calls. > Calling C routines is *not* the same as kernel coding. > Actually writing the routines that are to be called, and that > constitute the kernel itself, *is* kernel coding. And as > wonderful as Python is, it is *not* for kernel coding. > > Having just looked at Py-PF, it is *managing* the firewall, > not implementing it. Again, not kernel coding. Didn't somebody once demonstrate how to put a VM into kernel space so that you could write kernel code in Python? Maybe it was just a discussion about how it could be done in theory. There have been a few JVM-in-hardware projects, so I suppose you could use Jython to write kernel code for those machines. -- Grant Edwards grante Yow! I have accepted at Provolone into my life! visi.com From danielk at featherbrain.net Tue Jun 3 20:42:04 2008 From: danielk at featherbrain.net (Daniel Klein) Date: Tue, 03 Jun 2008 20:42:04 -0400 Subject: Help need with subprocess communicate References: <0312b7e9-bffe-4360-bf3a-f5b3b26d243d@l64g2000hse.googlegroups.com> Message-ID: On Tue, 3 Jun 2008 14:04:10 -0700 (PDT), rdabane at gmail.com wrote: >I'm trying to perform following type of operation from inside a python >script. >1. Open an application shell (basically a tcl ) >2. Run some commands on that shell and get outputs from each command >3. Close the shell > >I could do it using communicate if I concatenate all my commands >( separated by newline ) and read all the output in the end. So >basically I could do following sequence: >1. command1 \n command2 \n command 3 \n >2. Read all the output > >But I want to perform it interactively. >1. command1 >2. read output >3. command2 >4. read output ...... > >Following is my code: > >from subprocess import * >p2 = Popen('qdl_tcl',stdin=PIPE,stdout=PIPE) >o,e = p2.communicate(input='qdl_help \n qdl_read \n >qdl_reg_group_list ') > >Please suggest a way to perform it interactively with killing the >process each time I want to communicate with it. Use stdin.write(command + '\n') to 'send' data to the sub-process. Use stdout.readline() to 'receive' data from the sub-process. But to use this requires you open the subprocess with: universal_newlines = True It assumes that 'command' will be sent with '\n' and received data will come in a line at a time. Your Python program needs to know what to expect; you are in control. Alternatively, you can use std.write() and stdout.read() (without universal_newlines) but this means you need to create your own IPC protocol (like netstrings). Hope this helps, Daniel Klein From grante at visi.com Sat Jun 14 16:43:35 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 14 Jun 2008 15:43:35 -0500 Subject: Making wxPython a standard module? References: <6bidd7F3bg8usU1@mid.uni-berlin.de> <87fxrfx0h0.fsf@physik.rwth-aachen.de> Message-ID: On 2008-06-14, Torsten Bronger wrote: >> I've never used any of the designers, but I agree 100% that >> wxPython code is nasty ugly. wxPython has a very un-Pythonic >> API that's is, IMO, difficult to use. > > I know that such requests may start a never-ending thread but > I'd really like to know what you mean with this. [...] Well, if we want this thread to be never ending, I'd better put a little dramatic hyperbole into my answer, so here goes... ;) IMO, a few of the "un-Pythonic" things about wxPython are: 1) Window ID numbers. "You don't need to know what it's for, just pass a -1." Their very existence at the user level feels wrong. I'm told that for approximately 3 uber-sophisticated wxWidgets programmers window IDs can be useful in some rare situations. Meanwhile everybody else working under "normal" conditions has to pass a useless positional parameter every time they instantiate a widget. Things that are useful only in exceptional situations should only be visible in exception situations. 2) the "flags" parameter. "1975 called, and they want their bit-masks back." The mashing together of a several dozen different, completely unrelated attributes into the "flags" parameter is a trick left over from C/assembly language programming on machines who's memory size was measure in KB. Rather than OR-ing together a bunch of bit-patterns to make the window act the way you want, you should be setting individually named object attributes or passing optional, named parameters to the class method. 3) the parent/child tree "the only thing less well understood than Window IDs" I've been writing wxPython apps for about 9 years now, and I still have only a very vague idea what the parent/child tree is for. Everybody I know just makes everything the child of the first panel they put in the application frame. The same people who specify Window IDs other than -1 probably use complex parent/child trees for something. 4) sizers "they're like aspirin -- they work, but nobody knows exactly how" OK, that's a bit out-of-date since I seem to recall that somebody did finally figure out how aspirin works a couple years back. The way sizers work seems pretty complex compared to other GUI toolkits I've used, and the extra complexity doesn't seem to provide any extra capability. The one thing that seems to me to be particular complicated is controlling which objects "stretch" in what axis when a window is resized. I've been using them for many years, but I've never gotten them more than about 90% figured out. Every time I write a wxPython apps, I'm initially surprised at its behavior when the window is resized and have to spend some trial-and-error time fiddling with the sizer parameters. I don't remember having to do that in tkInter or in Trestle: things "just worked". 5) binding "What? you wanted a button that _did_ something when you clicked it?" Binding has actually improved a bit in the past few years. It's not as obscure as it used to be, but it's still an extra explicit step that shouldn't be required. It should only take one line of code to create a button widget that calls a specified callable when it's clicked. Something like this: b = wx.Button(label="Click Me", action=myCallable) Instead you used to have to create a button and then call some utility function in some other object to bind that button to a callable (IIRC this was one place where Window IDs could be used). Now, the button actually has a method you can use. It's still an extra step... 6) Thousands of wx.UPPER_CASE_INTEGER_HEX_CONSTANTS "After all, everything is really just a base-2 integer." Since we don't have objects or attributes or named parameters or strings, all information must be passed into and out of the library as arbitrary integers constants. The really great thing about that sort of API is it's versatility: you can pass any value any where! Pass a width in pixels where a bitmask of window attributes is expected? No problem! Well, the build I was running has finished, so that's probably enough... -- Grant Edwards grante Yow! Those people look at exactly like Donnie and visi.com Marie Osmond!! From stefan_ml at behnel.de Sun Jun 29 01:26:05 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 29 Jun 2008 07:26:05 +0200 Subject: HTML Parsing In-Reply-To: <2760a17a-63f9-4700-b31a-b1b60108a26e@m44g2000hsc.googlegroups.com> References: <2760a17a-63f9-4700-b31a-b1b60108a26e@m44g2000hsc.googlegroups.com> Message-ID: <48671CED.1090607@behnel.de> disappearedng at gmail.com wrote: > I am trying to build my own web crawler for an experiement and I don't > know how to access HTTP protocol with python. > > Also, Are there any Opensource Parsing engine for HTML documents > available in Python too? That would be great. Try lxml.html. It parses broken HTML, supports HTTP, is much faster than BeautifulSoup and threadable, all of which should be helpful for your crawler. http://codespeak.net/lxml/ Stefan From lists at cheimes.de Fri Jun 13 21:53:53 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 14 Jun 2008 03:53:53 +0200 Subject: Python 3000 vs. Python 2.x In-Reply-To: <2c299cdc-adcd-4540-b09f-43b4147e10ca@y21g2000hsf.googlegroups.com> References: <2c299cdc-adcd-4540-b09f-43b4147e10ca@y21g2000hsf.googlegroups.com> Message-ID: mr.opus.penguin at gmail.com wrote: > As a new comer to Python I was wondering which is the best to start > learning. I've read that a number of significant features have > changed between the two versions. Yet, the majority of Python > programs out in the world are 2.x and it would be nice to understand > those as well. Thanks for all the help. My advice from the perspective of a Python core developer: Stick to the 2.x series. It's going to take a couple of years until third party extensions and books have adopted to Python 3.x. Christian From zapwireDASHgroups at yahoo.com Thu Jun 19 00:29:08 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Wed, 18 Jun 2008 21:29:08 -0700 Subject: ˇ¶python in a nutshellˇ·andˇ¶programming pythonˇ· References: Message-ID: "yps" wrote in message news:g3cfhn$8g9$1 at news.cn99.com... > as a new learner of python,which book in and > is more suitable? I don't have "Python in a Nutshell," but let me ask... do you have a strong programming background in C++, Java, etc.? If so, you'll probably find "Programming Python" a little too basic. > and recommend several books? For those with prior programming experience, I'd recomment "Python: Essential Reference." "Python Pocket Reference" is worth having regardless of your background. A similar document is the freely download quick reference here: http://rgruet.free.fr/#QuickRef ---Joel From timr at probo.com Mon Jun 9 01:15:20 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 09 Jun 2008 05:15:20 GMT Subject: time.clock() or Windows bug? References: Message-ID: <0uep44hpn8rupgr15a135f37q346tif9v2@4ax.com> Nick Craig-Wood wrote: > >time.clock() uses QueryPerformanceCounter under windows. There are >some known problems with that (eg with Dual core AMD processors). > >See http://msdn.microsoft.com/en-us/library/ms644904.aspx > >And in particular > > On a multiprocessor computer, it should not matter which processor > is called. However, you can get different results on different > processors due to bugs in the basic input/output system (BIOS) or > the hardware abstraction layer (HAL). To specify processor > affinity for a thread, use the SetThreadAffinityMask function. That's an extremely arrogant statement on their part, because the fault here is entirely within Windows. Through Windows 2000, the operating system actually synchronized the cycle counters on the additional processors as they came out of reset at boot time. (The cycle counter is, after all, a writable register.) As a result, the cycle counters were rarely off by more than about 20 cycles. Beginning with XP, they stopped doing that. As a result, the cycle counters on multiprocessor machines can vary by millions or even tens of millions of cycles. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From Scott.Daniels at Acm.Org Wed Jun 25 09:11:05 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 25 Jun 2008 06:11:05 -0700 Subject: Bit substring search In-Reply-To: References: <5043fee7-444b-41dd-a419-77550595d273@79g2000hsk.googlegroups.com> <5135a9f6-d8a5-4812-88b5-bc5fa28ece71@25g2000hsx.googlegroups.com> Message-ID: Kris Kennaway wrote: > Thanks for the pointers, I think a C extension will end up being the way > to go, unless someone has beaten me to it and I just haven't found it yet. Depending on the pattern length you are targeting, it may be fastest to increase the out-of-loop work. For a 40-bit string, build an 8-target Aho-Corasick machine, and at each match check the endpoints. This will only work well if 40 bits is at the low end of what you are hunting for. Roughly: targets[0] = 5-byte string as byte-aligned targets[N in 1..7] = 4-byte strings representing the lead four bytes after discarding the high-order N bits m = AhoCorasick(targets) def hunt(m, source): m.state = 0 old_block = None for n, block in enumerate(source): for recognized, where in m.search(block): if recognized: if : yield block, where, recognized else: yield block, where, 0 --Scott David Daniels Scott.Daniels at Acm.Org From nick at craig-wood.com Mon Jun 23 05:32:05 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 23 Jun 2008 04:32:05 -0500 Subject: how to export functions by name for ctype References: <8f76bf6e-08b1-4af9-a739-bdc018553374@a1g2000hsb.googlegroups.com> Message-ID: rych wrote: > I'm on Windows with VS2005 testing ctypes on a very simple dll > I create a test.dll project which exports a function fntest(). I don't > touch anything in the autogenerated source and build it. I can load > the dll but can't access the function by its name fntest. Only by > ordinal number or calling getattr with "?fntest@@YAHXZ". How do I > export functions by name? It's probably rather a VS2005 question, but > I'm a bit disappointed ctypes doesn't work with a default export > convention. I guess you've compiled your DLL with C++ and the above is a C++ mangled name. Either compile it with C, or export the names in an extern "C" { } block. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From ivan.illarionov at gmail.com Wed Jun 11 10:00:02 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 11 Jun 2008 14:00:02 +0000 (UTC) Subject: Dynamic HTML from Python Script References: <484f151c$0$5009$607ed4bc@cv.net> <484f21aa$1@dnews.tpgi.com.au> <484f24e9$0$5020$607ed4bc@cv.net> Message-ID: On Wed, 11 Jun 2008 01:05:45 +0000, asdf wrote: >> Well, there's a few ways you could approach it. >> >> You could create a cgi program from your script - this is probably the >> solution you're looking for. >> >> > Output from the script does come up very often. There is a new output > every 10 secs and it's possible that the script might be run > indefinitely. Basically I want all that output displayed in a web > browser Here's a simplified Django and AJAX solution: 1. Install Django http://www.djangoproject.com/documentation/install/ and choose the place to strore your Django apps 2. Run 'python django-admin.py startproject YOURPROJECTNAME' 3. Create views.py file inside YOURPROJECTNAME directory with something like this: from datetime import datetime from django.http import HttpResponse # import your script here def myscript(request): output = """\
""" return HttpResponse(output) def ajax(request): output = """

Hello World from Django and AJAX

Current time is: %s

""" % str(datetime.now())[11:19] return HttpResponse(output, mimetype="text/plain") Note, that refresh time is in 'setTimeout('ajaxFunction();', 1000);' in this example it is 1 second. 3. edit urls.py inside YOURPROJECTNAME directory to something like this: from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^myscript/$', 'YOURPROJECTNAME.views.myscript'), (r'^ajax/$', 'YOURPROJECTNAME.views.ajax'), ) 4. run 'python manage.py runserver' inside YOURPROJECTNAME directory 5. point your browser to 'http://127.0.0.1:8000/myscript/' and you'll see the result. 6. Deploy your app to Apache web server http://www.djangoproject.com/documentation/modpython/ http://www.djangoproject.com/documentation/fastcgi/ Hope this Django/AJAX introduction is helpfull Please note that this code is extremely simplified you probably need to learn more about Django and AJAX/Javascript by yourself Ivan From torppa at staff.megabaud.fi Tue Jun 10 01:53:08 2008 From: torppa at staff.megabaud.fi (Jarkko Torppa) Date: Tue, 10 Jun 2008 05:53:08 GMT Subject: 65K length limitation in MySQLdb? References: <4e79050f-ee50-42f0-9b84-4571faa30ee5@a32g2000prf.googlegroups.com> Message-ID: On 2008-06-10, TT wrote: > I'm trying to using the following code insert a long string into a > MySQL table, the data type is of that column is TEXT. When the length > of the content is longer than 65K, it get truncated in the database. > Any idea about this? Thanks It's limitation on your sql engine, use longtext. http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html -- Jarkko Torppa From kyrie at uh.cu Fri Jun 27 20:15:51 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Fri, 27 Jun 2008 20:15:51 -0400 Subject: Do I need "self" and "other"? In-Reply-To: <04e2afb7-b96c-446a-816a-ffac0ea81d5b@p25g2000hsf.googlegroups.com> References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> <04e2afb7-b96c-446a-816a-ffac0ea81d5b@p25g2000hsf.googlegroups.com> Message-ID: <200806272015.53248.kyrie@uh.cu> On Friday 27 June 2008 06:41:22 pm Kurda Yon wrote: > OK, I see. In the given example "self" is just a name which can be > replace by whichever (valid) name. Is that always like that? I mean, > does "slef" have a special meaning in some cases or it is always "just > a name like any other"? I am asking that because "self" is highlighted > in my text editor, so I assume that it can have a special meaning. I > also heard that "self" refers to a object and I am not sure what that > "refers" means. It's a name, like any other. It only has special meaning on the minds of most python programmers. That name is used, by convention (and only because of convention) to refer the the ... erm... 'self' object. That said, of all python conventions, it is perhaps the one most zealously followed. That's why your editor highlights it. So, code will not break if you use any other valid name instead of self. But you shouldn't. Everything will work perfectly - except the readability. Cheers, -- Luis Zarrabeitia (aka Kyrie) Fac. de Matem?tica y Computaci?n, UH. http://profesores.matcom.uh.cu/~kyrie From ptmcg at austin.rr.com Thu Jun 19 06:40:11 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 19 Jun 2008 03:40:11 -0700 (PDT) Subject: Pyparsing performance boost using Python 2.6b1 Message-ID: I just ran my pyparsing unit tests with the latest Python 2.6b1 (labeled internally as Python 2.6a3 - ???), and the current 1.5.0 version of pyparsing runs with no warnings or regressions. I was pleasantly surprised by the improved performance. The most complex parser I have is the Verilog parser, and I have just under 300 sample input files, so the test gets a chance to run over a range of code and source inputs. Here are the lines/second parsing for the Verilog data (higher numbers are better): Python V2.5.1 Python V2.6b1 base 209.2 307.0 with packrat optimization enabled 349.8 408.0 This is a huge percentage improvement, anywhere from 15-50%! I do not know what it is about 2.6 that runs so much faster, but given that packratting achieves somewhat less improvement, I would guess that the 2.6 performance comes from some optimization in making function calls, or in GC of local variables when functions are completed (since packratting is a form of internal memoization of parse expressions, which thereby avoids duplicate calls to parsing functions). Using psyco typically gives another 30-50% performance improvement, but there is no psyco available for 2.6 yet, so I skipped those tests for now. -- Paul From remy.blank at pobox.com Tue Jun 3 17:49:01 2008 From: remy.blank at pobox.com (Remy Blank) Date: Tue, 03 Jun 2008 23:49:01 +0200 Subject: ANN: Sydebar 1.0 - A browser sidebar generator for Python documentation Message-ID: Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: quoted-printable I am pleased to announce the first release of Sydebar, a browser sidebar = generator for Python documentation. For the impatient, sample outputs=20 for all Python versions ever released can be found here: http://c-space.org/download/Sydebar/samples/ The program generates a single, self-contained XHTML file for a specific = Python documentation URL, which can be local or remote. The generated=20 file is loaded into the sidebar of some popular browsers (tested on=20 Firefox and Opera, Mozilla should work as well), and presents a tabbed=20 interface with one page for each of the following documentation sections:= * Tutorial * Language reference * Library reference * Python/C API * Extending and embedding * Global module index Each page shows a collapsible tree of chapters, with links opening the=20 corresponding section in the main browser pane. The global module index=20 features an incremental search functionality with fast keyboard navigatio= n. Moreover, a search page allows performing searches on various subsets of = python.org (specific parts of the website, PEPs, newsgroups, PyPI and=20 the issue tracker). The documentation and PyPI entry can be found here: http://c-space.org/software/Sydebar.html http://pypi.python.org/pypi/Sydebar I would like to mention that Sydebar was inspired by python-sidebar from = Daniel Lundin at Edgewall Software, and even though I didn't borrow any=20 code from there, the layout does bear quite some resemblance. Feedback is very welcome. Thanks for reading! -- Remy -------------- next part -------------- Content-Type: application/pgp-signature; name="signature.asc" Content-Description: OpenPGP digital signature Content-Disposition: attachment; filename="signature.asc" -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.9 (GNU/Linux) iEYEARECAAYFAkhFvFEACgkQCeNfIyhvXjISEACgmUXSorHaZ7JjNC2AqTuJtWod BAgAn3g/97+9cI9m5n2QBpvcmtxQnGB0 =IQ6Q -----END PGP SIGNATURE----- From evidentemente.yo at gmail.com Wed Jun 25 03:15:14 2008 From: evidentemente.yo at gmail.com (evidentemente.yo) Date: Wed, 25 Jun 2008 00:15:14 -0700 (PDT) Subject: calling a .exe from Python References: Message-ID: Hey, thank you very much!!!:D Would it matter if my .exe doesn't return any value? would it return like an "ok" or something??? On 24 jun, 14:32, Nick Craig-Wood wrote: > evidentemente.yo wrote: > > ?Hi, i am trying to call a .exe from my .py file, i have found the exec > > ?function, but i'm not sure of how to use it:S > > > ?would it be f.e.: > > > ?execl (mypath/myfile.exe,myfile,arg1,arg2,...) > > > ????? > > > ?Another question is, when i call my .exe with exec, i understand that > > ?my .py file will stop running, and instead the new process will be > > ?launched instead of it. Is it true? > > ?Is there a way to launch my .exe without finishing my .py file?? > > > ?thank you very much:) > > Probably what you want is this... > > from subprocess import call > > rc = call(["mypath/myfile.exe",arg1,arg2]) > > rc will contain the exit status > > See the subprocess module for more things you can do > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick From jon at ffconsultancy.com Thu Jun 5 06:37:48 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Thu, 05 Jun 2008 11:37:48 +0100 Subject: The Importance of Terminology's Quality References: Message-ID: Robert Maas, http://tinyurl.com/uh3t wrote: >> From: dkco... at panix.com (David Combs) >> Lisp is *so* early a language (1960?), preceeded mainly only by >> Fortran (1957?)?, and for sure the far-and-away the first as a >> platform for *so many* concepts of computer-science, eg lexical vs >> dynamic ("special") variables, passing *unnamed* functions as >> args ... maybe is still the only one in which program and data >> have the same representation -- that it'd seem logical to use it's >> terminology in all languages. > > Yeah, but why did you cross-post to so many newsgroups? Are you > trying to run a flame war between advocates of the various > languages? What would be the point? We all know that Java, Perl, Python and Lisp suck. They don't even have pattern matching over algebraic sum types if you can imagine that. How rudimentary... -- Dr Jon D Harrop, Flying Frog Consultancy http://www.ffconsultancy.com/products/?u From xdicry at gmail.com Thu Jun 19 03:57:18 2008 From: xdicry at gmail.com (Evan) Date: Thu, 19 Jun 2008 00:57:18 -0700 (PDT) Subject: [SMTPLIB] how to send a "Multiline" mail with smtplib? Message-ID: Hello - I'm new with Python, I try to do a mail problem, the code likes below: +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ import smtplib import mimetypes from email.Encoders import encode_base64 from email.MIMEAudio import MIMEAudio from email.MIMEBase import MIMEBase from email.MIMEImage import MIMEImage from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText msg = MIMEMultipart() msg['From'] = 'ab at xx.net' msg['To'] = 'ab at xx.net' msg['Subject'] = 'test subject' body=MIMEText('hello,\r\n ok',_subtype='html',_charset='windows-1255') msg.attach(body) server = smtplib.SMTP('mail.xx.net') server.sendmail('ab at xx.net', 'ab at xx.net', msg.as_string()) server.quit() +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ I try to use "\r\n" or "\n", but no luck, nothing with them, I still get a Single-line text in the mail. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ hello, ok ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ So how do I send a multiline mail? such as : +++++++++++++++++++++++++++++++++++++++++++ Hello, 1, 2, ok +++++++++++++++++++++++++++++++++++++++++++ I would like to get help from you, thanks so much. From bruno.desthuilliers at gmail.com Fri Jun 20 16:47:44 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 20 Jun 2008 13:47:44 -0700 (PDT) Subject: sublassing as a verb References: Message-ID: On 20 juin, 22:34, davidj411 wrote: > docs on urllib module say this about the FancyUrlOpener: > "class FancyURLopener( ...) > > FancyURLopener subclasses URLopener providing default handling > for ..." > > does that mean the FancyURLopener is a subclass of URLopener? You could easily find out by yourself, you know ?-) Python 2.5.1 (r251:54863, Apr 6 2008, 17:20:35) [GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from urllib import URLopener, FancyURLopener >>> issubclass(FancyURLopener, URLopener) True From henryar2 at gmail.com Sun Jun 22 06:56:22 2008 From: henryar2 at gmail.com (Henry Read) Date: Sun, 22 Jun 2008 18:56:22 +0800 Subject: Learning Python in a group In-Reply-To: <507738ef0806220343r3e9ea053neeec0baf0ccfdbe6@mail.gmail.com> References: <507738ef0806220343r3e9ea053neeec0baf0ccfdbe6@mail.gmail.com> Message-ID: I'm a beginner, too.But python wasn't my first programming language. On Sun, Jun 22, 2008 at 6:43 PM, Jonathan Roberts wrote: > Hi all, > > I'm looking to learn Python (as my first programming language) and I'm > pretty sure I'd be more successful doing this with a group of other > people. > > I've currently got one other person to learn with me, and we plan to > work remotely over the net using tools such as IM/VoiP/Gobby/WIkis > etc. We'd still like a few others to work with us, with a group of > about 5 or 6 being seen as ideal. We'd also like to find somebody to > act as a mentor/guide who might be happy to meet with us once every > couple of weeks to help keep us moving in the right direction and find > solutions to problems when we get really stuck! > > Wondered if there was anybody here who might be interested in working > with us in either of these roles? We both have differing goals, but > ultimately we'd just like to get more familiar so that we can provide > some simple fixes to packages we maintain/scratch a few itches of our > own. Any one is welcome, no matter what your own aim :) > > Would love to hear feedback, especially from anyone who's interested > in working with us... > > Best, > > Jon > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 16 05:06:58 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 16 Jun 2008 11:06:58 +0200 Subject: Best way to make a number of tests against an object('s attributes) with absence of switch statement? In-Reply-To: <15aaceb5-2f9c-4891-98c2-fe7ac3e19f1c@k37g2000hsf.googlegroups.com> References: <15aaceb5-2f9c-4891-98c2-fe7ac3e19f1c@k37g2000hsf.googlegroups.com> Message-ID: <48562d32$0$1281$426a34cc@news.free.fr> Phillip B Oldham a ?crit : > What would be the optimal/pythonic way to subject an object to a > number of tests (based on the object's attributes) and redirect > program flow? > > Say I had the following: > > pets[0] = {'name': 'fluffy', 'species': 'cat', 'size': 'small'} > pets[1] = {'name': 'bruno', 'species': 'snake', 'size': 'small'} > pets[2] = {'name': 'rex', 'species': 'dog', 'size': 'large'} > > What I'd like to do is loop through 'pets', and test each object. Some > of the tests I'd like to perform are: > > Is the size 'small' and species not 'dog'? > Is the species 'cat' and name 'fluffy'? > Is the species not 'dog' or 'cat'? > > In PHP I'd use a switch statement similar to the following: > > foreach( $pets as $pet) { > switch(true) { > case ( $pet['size'] === 'small' && $pet['species'] !== 'dog' ): > // do something > break; > // etc... > } > } > > Now, I understand from a bit of googling that python doesn't have a > switch statement, and because of this people rely on python's > polymorphism. You could also put it the other way round : Python doesn't have a switch statement because peoples use polymorphism !-) (nb : not that my "reversed" statement is in any way more true than yours - but the fact is that procedural switch statement vs OO polymorphic dispatch is not such a new topic...) > Thats great, but I've yet to come across a decent > example which make a "click". > > Any thoughts on how to proceed? The braindead canonical OO solution would be to make a specific class for each species each implementing it's own version of do_something(). The problem is that it would only dispatch on species, not other attributes (size etc). Which is a inherent limitation of the canonical OO type-based single dispatch mechanism. A more elaborate canonical OO solution would be to use the visitor pattern to overcome the single dispatch limitation. A yet more elaborate (but way less canonical) solution is to use predicate-based dispatch (cf Philip Eby's work). Anyway, and while each dispatch mechanism (from basic branching to complex predicate-based systems) has it's pros and cons, I'd first think twice (or more) about whether my current dispatch problem has some relative stability wrt/ the domain - IOW, it's structurally part of the domain and won't change anytime soon - or if it's one of those ad-hoc short-lived illogical "business rule" that is potentially subject to unpredictable change any other day. Because the appropriate solution really depends on this kind of considerations. Now wrt/ your concrete example: truth is that, while expressed as a switch statement, it's in fact really a if/elif/.../, since the condition is not a constant (so you don't gain any performance gain from using a switch). So the simplest translation in Python is to use an if/elif/... for pet in pets: if pet['size'] == 'small' and pet['species'] !== 'dog': // do something elif (other complex condition): // etc From nick at craig-wood.com Wed Jun 4 10:30:21 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 04 Jun 2008 09:30:21 -0500 Subject: ctypes, function pointers and a lot of trouble References: <832f57f4-7d26-44a5-8abe-567165cc532f@f36g2000hsa.googlegroups.com> Message-ID: Matt wrote: > Hm, thanks, now I can access my data in the functions and also write > them but the program keeps terminating right at the point when the > "open" function finishes. Unfortunately everything closes and I get no > error messages. > > I did some additional work in the meantime and changed my code so it has > the correct datatypes now: > > > def pystreamopen (contextH, mode, pErr): > print "opening..." > print contextH.contents.dwBufferSize #just to check the structure > print mode #tells about what the DLL wants to do with this stream You program is crashing somewhere after here since mode is printed but nothing else is > contextH.contents.mode = c_byte(5) #5=Permission to read and write > contextH.contents.lPos = c_uint(0) #start position > > print pErr.contents > pErr.contents = c_uint(0) Try commenting out these lines and see if it works, then uncomment one at a time. Also is that supposed to be returning something? > Anyway, meanwhile decided to try a different approach. Maybe I have > more luck by having the function write the data directly into a file on > the HDD. > Doe anyone know how to translate the following into Python/ctypes? > > I googled quite a lot before but all topic-related I found was my own > posting here in this NG :S > > pFilStrm->hFile = CreateFile( pFilStrm->szFileName, > dwDesiredAccess, dwShareMode, NULL, > dwCreationDisposition, > FILE_ATTRIBUTE_NORMAL, > NULL ); use os.read os.write and os.open which will give you OS handles rather than python file objects, ie I think these are a fairly direct interface to CreatFile etc (but I could be wrong - I'm not a windows expert!) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From Russ.Paielli at gmail.com Fri Jun 6 14:56:26 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Fri, 6 Jun 2008 11:56:26 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <4847d39d$0$7614$426a74cc@news.free.fr> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <8f68b4a0-8f0f-42d6-8e96-53a97433f708@v26g2000prm.googlegroups.com> <48495745$0$26543$426a74cc@news.free.fr> Message-ID: <819c8708-95ca-4640-b305-39826c09c06a@t12g2000prg.googlegroups.com> On Jun 6, 8:28 am, Bruno Desthuilliers wrote: > Russ P. a ?crit : > > > > > On Jun 5, 2:27 pm, Dennis Lee Bieber wrote: > >> On Thu, 5 Jun 2008 11:36:28 -0700 (PDT), "Russ P." > >> declaimed the following in comp.lang.python: > > >>> would need to use a "mangled" name to access private data or methods. > >>> But you will be using the name many times, you can reassign your own > >>> name, of course, so the mangled name need not appear more than once > >>> where it is needed. > >> Which will break the first time the "innards" rebind a value to the > >> mangled name, as the "simplified" external name will still be bound to > >> the previous value. > > > I'm not sure you understood what I meant. In current Python, if I need > > access to data element __XX in class YourClass, I can use > > ZZ._YourClass__XX, but if I don't want to clutter my code with that > > mangled name, I can just write > > > XX = ZZ._YourClass__XX > > > and refer to it from that point on as XX. > > > Obviously if the meaning of > > __XX changes within class ZZ, this will break, but that's why you are > > supposed to avoid using private data in the first place. > > AFAICT, What Dennis meant is that the binding of ZZ._YourClass__XX > changes between the moment you bind it to local XX and the moment you > use it, then you're out. Perhaps I should have stipulated that this should be done only in a local scope and in an application that is not multi-threaded. Then I don't see how you can have a problem. From xucs007 at gmail.com Sat Jun 21 19:54:03 2008 From: xucs007 at gmail.com (xucs007 at gmail.com) Date: Sat, 21 Jun 2008 16:54:03 -0700 (PDT) Subject: flock seems very unsafe, python fcntl bug? Message-ID: <9abe51c3-c022-42e9-9d7d-acba7391d007@79g2000hsk.googlegroups.com> I ran following 2 programs (lock1, lock2) at almost same time, to write either "123456", or "222" to file "aaa" at the same time. But I often just got "222456" in "aaa" . Is this a bug of python fcntl module ? See 2 programs I ran: #!/usr/bin/env python import fcntl, time file = open('aaa', "w") fcntl.flock(file, fcntl.LOCK_EX) file.write('123456') time.sleep(10) file.close() #!/usr/bin/env python import fcntl, time file = open('aaa', "w") fcntl.flock(file, fcntl.LOCK_EX) file.write('222') time.sleep(10) file.close() From benjamin.kaplan at case.edu Thu Jun 19 17:15:59 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 19 Jun 2008 17:15:59 -0400 Subject: Noob: finding my way around the docs... In-Reply-To: References: Message-ID: On Thu, Jun 19, 2008 at 5:06 PM, kj wrote: > > > > I'm a Python noob, and haven't yet figured out my way around the > Python documentation. > > For example, suppose I learn about some great module foo.bar.baz, > and when I run the python interpreter and type "import foo.bar.baz", > lo and behold, it is already installed on our system, which means > that (knowing that our system is pretty bare-bones as far as python > goes) most likely foo.bar.baz is part of the standard python > installation. > > So, if I were an experienced Pythonista, how would I go about > finding the documentation for foo.bar.baz? > > This situation happened most recently to me, if we replace foo.bar.baz > with xml.dom.ext. It was indeed installed on our system, but I > could find no mention of it in docs.python.org. > > Somehow I have the feeling that there's some major stash of > documentation that I haven't learned about yet... > > FWIW, I'm a Perlhead, and I'm very used (maybe too used) to the > fact that if the Perl module Foo::Bar::Baz is installed on our > system, all I need to do to read its full-blown documentation in > all its glory is to type "perldoc Foo::Bar::Baz" at the command > line. Is there anything like this in Python? > > TIA! > > kj > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. > -- > http://mail.python.org/mailman/listinfo/python-list > To get the docs, just open up the shell and type: >>> import module >>> help(module) -------------- next part -------------- An HTML attachment was scrubbed... URL: From boris.smirnov at gmail.com Thu Jun 12 06:08:00 2008 From: boris.smirnov at gmail.com (boriq) Date: Thu, 12 Jun 2008 03:08:00 -0700 (PDT) Subject: suppress opening command window after using os.system command References: Message-ID: <8ad19472-bbb4-4283-88bf-2bcf6b91790c@26g2000hsk.googlegroups.com> On 12 Jun., 11:51, "Gabriel Genellina" wrote: > En Thu, 12 Jun 2008 05:28:13 -0300, boriq ? > escribi?: > > > I'm using in my script command os.system('command') on Windows XP. > > Each time the os.system command is used, python opens an empty ms-dos > > command window (the black one) and then closes it. So when in one > > script the os.system command 50 times is used, I see 50 black windows. > > > Is there a way of how to suppress this unnecessary command windows to > > be opened? > > Use the subprocess module instead of os.system > > -- > Gabriel Genellina I'm on version 2.2.1 because of a program we use and it uses this version. and the subprocess module was implemented in version 2.4 Any possibility to do it with the old stuff in ver 2.2.1? Thx From apardon at forel.vub.ac.be Wed Jun 4 08:02:01 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Jun 2008 12:02:01 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> Message-ID: On 2008-06-04, NickC wrote: > On May 26, 7:32 am, "Joe P. Cool" wrote: >> I saw this "don't need it" pattern in discussions about the ternary >> "if..else" expression and about "except/finally on the same block >> level". >> Now Python has both. > > if/else was added solely because people kept coming up with ways of > embedding a pseudo conditional inside expressions and writing buggy > code in the process. All it really saves you in practice is a bit of > vertical whitespace, so, no, you still don't need it - but if you > insist on doing it, at least there's now an easy way to do it > correctly. If I remember correctly it was added because one of the python developers was bitten by a bug in the standard library code that was caused by the use of the and-or emulation, mentioned in the FAQ. And although one indeed doesn't need this. There are a lot of things in Python one doesn't need. Python could be limited to single operator expressions. You don't need: x = a * b + c You can write it just like this: x = a * b x = x + c And if you want a list comprehension like the following: ls = [ x * x + 4 for x in xrange(10)] You can of course write it as follows: def sqrplus4(a): rs = a * a return rs + 4 ls = [sqrplus4(x) for x in xrange(10)] Now of course noone would defend such a limitation on the grounds that one doesn't need the general case and that the general case will only save you some vertical space. But when it came to the ternary operator that was exactly the argument used, to defend the lack of it. >> > In Python, the philosophy "we're all consenting adults here" applies. >> >> Please don't sell a missing feature as a philosophy. Say you don't >> need/want >> it. But don't call it philosophy. > > Gosh, and here I thought treating programmers as non-idiots was > actually one of the guiding philosophies in the discussion on python- > dev. I have heard the argument: "Such a feature will be abused too easily" and similar too many times to find this credible. -- Antoon Pardon From rhamph at gmail.com Sat Jun 14 13:10:10 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Sat, 14 Jun 2008 10:10:10 -0700 (PDT) Subject: best way to create a timer References: Message-ID: On Jun 12, 11:42 pm, Alexnb wrote: > I am wondering what is the best way to create a timer, like an alarm, once it > reaches a time, it triggers an event. I have a way of doing this but it > seems like it isn't good at all. If it helps at all I am using a Tkinter, > but that probably doesn't mean much. The way I was doing it was using a > while loop, and just saying while current time is not = to trigger time, do > nothing, and when it is, do event. Tkinter makes a big difference here. Like most (all?) event loops, it provides a way to call a function after a specified amount of time. Here's two pages I found: http://mail.python.org/pipermail/python-list/2001-August/101233.html http://www.astro.washington.edu/owen/TkinterSummary.html#After Note that it only fires once. If you want it to fire again you're callback will have to setup another timer. From bj_666 at gmx.net Fri Jun 6 05:34:56 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Jun 2008 09:34:56 GMT Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> <769c54bf-8664-4179-bd17-c18705320606@27g2000hsf.googlegroups.com> Message-ID: <6aselvF38p22kU1@mid.uni-berlin.de> On Thu, 05 Jun 2008 23:56:40 -0700, dwahli wrote: > On Jun 6, 8:44?am, "Terry Reedy" wrote: >> >> Of course, enumerate(iterable) is just a facade over zip(itertools.count(), >> iterable) > > So you could write: > gen = (x for x in itertools.izip(itertools.count(8), [0, 1, 1, 1, 1, > 1, 1, 2, 2, 3, 3])) > print list(gen) Useless use of a generator expression. This: gen = itertools.izip(itertools.count(8), [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3]) print list(gen) has the same effect without the intermediate generator that does nothing but passing the items. Ciao, Marc 'BlackJack' Rintsch From lucaberto at libero.it Fri Jun 6 04:59:28 2008 From: lucaberto at libero.it (luca72) Date: Fri, 6 Jun 2008 01:59:28 -0700 (PDT) Subject: import cherrypy2 References: Message-ID: <0853b1cc-33bb-416e-9b2e-0fa146ede1c1@79g2000hsk.googlegroups.com> On 6 Giu, 10:31, Chris wrote: > On Jun 6, 10:22 am, luca72 wrote: > > > > > Hello i can't import cherrypy2 but i don't know why this is the sys > > path: > > > '', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > setuptools-0.6c7-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg', '/home/pirataja/ > > opo.net/python/lib/python2.5/site-packages/TurboKid-1.0.4-py2.5.egg', > > '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > TurboJson-1.1.2-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > python2.5/site-packages/TurboCheetah-1.0-py2.5.egg', '/home/pirataja/ > > opo.net/python/lib/python2.5/site-packages/simplejson-1.9.1-py2.5- > > linux-i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site- > > packages/RuleDispatch-0.5a0.dev_r2306-py2.5-linux-i686.egg', '/home/ > > pirataja/opo.net/python/lib/python2.5/site-packages/PasteScript-1.6.2- > > py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > FormEncode-1.0.1-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > python2.5/site-packages/DecoratorTools-1.7-py2.5.egg', '/home/pirataja/ > > opo.net/python/lib/python2.5/site-packages/configobj-4.5.2-py2.5.egg', > > '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > CherryPy-2.3.0-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > python2.5/site-packages/kid-0.9.6-py2.5.egg', '/home/pirataja/opo.net/ > > python/lib/python2.5/site-packages/Cheetah-2.0.1-py2.5-linux- > > i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > PyProtocols-1.0a0dev_r2302-py2.5-linux-i686.egg', '/home/pirataja/ > > opo.net/python/lib/python2.5/site-packages/PasteDeploy-1.3.1- > > py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > Paste-1.7-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > python25.zip', '/home/pirataja/pirata-jacopo.net/python/lib/ > > python2.5', '/home/pirataja/opo.net/python/lib/python2.5/plat- > > linux2', > > '/home/pirataja/opo.net/python/lib/python2.5/lib-tk', > > '/home/pirataja/opo.net/python/lib/python2.5/lib-dynload', '/home/ > > pirataja/opo.net/python/lib/python2.5/site-packages'] > > > For my is all ok but whe i do import cherrypy2 i get no mudule name > > cherrypy2 > > > Regards > > > Luca > > because it's "import cherrypy" and not "import cherrypy2" sorry but from another python installation i import cherrypy2 as cherrypy and all works Regards Luca From Quill_Patricia at emc.com Wed Jun 18 04:54:13 2008 From: Quill_Patricia at emc.com (Quill_Patricia at emc.com) Date: Wed, 18 Jun 2008 04:54:13 -0400 Subject: Getting Python exit code when calling Python script from Java program Message-ID: <102AF37FC3CE794DB52B45646265EC9602387CF9@CORPUSMX30B.corp.emc.com> I have a Python script which is used to load data into a database. Up to now this script has been run by customers from the Windows command prompt using "python edg_loader.pyc". Any error messages generated are written to a log file. A project team working in the same company as me here would like to use this loading utility. They write UI applications for Windows using Java. They were able to launch the Python script from within Java by creating a Process using Java ProcessBuilder class. However, the way the error handling is currently implemented isn't really suitable for use in a UI application. As I'm sure you can appreciate it's not really feasible to tell users of a UI program to keep checking the log files while the loading is underway!!. Ideally they would like the Python loading utility to return an error code and error message - the error message could then be displayed on a message box on the UI. I seem to be having problems implementing this. I tried using the sys.exit() method in my script and passed non -zero values. However the value wasn't picked up the by Java Process.exitValue() method - it kept picking up 0. On investigation it turned out that the exit value being read is from python.exe process, not from the Python script. Is there any way I can obtain the return value of a python script from a Java program? I did manage to get some sort of return error message. I wrote a test message to sys.stderr in the Python script and this was picked up by Java Process.getErrorSteam() method. However I would really like to get the return codes working if possible and would appreciate any suggestions on how to implement this. Thanks, Patricia Quill From sjmachin at lexicon.net Sun Jun 8 04:36:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 8 Jun 2008 01:36:47 -0700 (PDT) Subject: simple question on list manipulation from a newbie References: <76ccc0a8-90de-4717-9e6f-06836827b1e1@i18g2000prn.googlegroups.com> <6hD2k.4836$co7.3109@nlpi066.nbdc.sbc.com> <9ab9cb3f-787f-4552-9dc2-3f36c4c2ebe1@j33g2000pri.googlegroups.com> Message-ID: <2e2e11fc-881f-427a-9618-33c1577dd4be@d19g2000prm.googlegroups.com> On Jun 8, 4:42 pm, Sengly wrote: [snip] > Thank you all for your help. I found a solution as the following: The following is a solution to what? > > alist = [ > {'noun': 'dog', 'domestic_dog', 'Canis_familiaris'}, That is not yet valid Python. You will get a syntax error pointing to the comma after 'domestic_dog'. Do you mean: (1) alist = [ {'noun': ('dog', 'domestic_dog', 'Canis_familiaris')}, {'noun': ('frump', 'dog')}, # etc ] or (2) alist = [ ('dog', 'domestic_dog', 'Canis_familiaris'), ('frump', 'dog'), # etc ] or (3) something else? > {'noun': 'frump', 'dog'}, > {'noun': 'dog',}, > {'noun': 'cad', 'bounder', 'blackguard', 'dog', 'hound', 'heel'}, > {'noun': 'frank', 'frankfurter', 'hotdog', 'hot_dog', 'dog', > 'wiener', 'wienerwurst', 'weenie'}, > {'noun': 'pawl', 'detent', 'click', 'dog'}, > {'noun': 'andiron', 'firedog', 'dog', 'dog-iron'}, > ] > > def getAll(alist): > list=[] > for i in range(0,len(alist)): > list.extend(alist[i][:]) Note: the use of [:] to copy the contents of each element indicates that you think that each element is a sequence (list/tuple/whatever) i.e. option (2) above. > return list > Whatever that is solving, it could be written much more clearly as: answer = [] # don't shadow the builtin list function # and use meaningful names for sublist in alist: answer.extend(sublist[:]) return answer Aside: Why do you think you need to copy sublist? Does the plot involve later mutation of alist? And it can be done even more clearly using a list comprehension: [element for sublist in alist for element in sublist] HTH, John From space.captain.face at gmail.com Sat Jun 7 18:36:44 2008 From: space.captain.face at gmail.com (Kalibr) Date: Sat, 7 Jun 2008 15:36:44 -0700 (PDT) Subject: Dynamically naming objects. References: <8a99c3fa-1eeb-49b3-a714-b6063ec1daab@d19g2000prm.googlegroups.com> <3d2a85b2-255d-4e93-8cfb-e2772f57b69a@u6g2000prc.googlegroups.com> <15z2k.1218$LL4.885@bignews7.bellsouth.net> Message-ID: <69ba93e1-c1fe-4471-8feb-fa636e9a3a56@d19g2000prm.googlegroups.com> On Jun 8, 2:58 am, Hans Nowak wrote: > Kalibr wrote: > > On Jun 7, 1:20 pm, Hans Nowak wrote: > >> Kalibr wrote: > >>> I've been developing a small script to fiddle with classes, and came > >>> accross the following problem. Assuming I get some user input asking > >>> for a number, how would I spawn 'n' objects from a class? > >>> i.e. I have a class class 'user' and I don't know how many of them I > >>> want to spawn. > >>> Any ideas? > >> Sure. This will give you a list of n instances of user: > > >> [user() for i in range(n)] > > >> Of course, you could also use a good old for loop: > > >> for i in range(n): > >> u = user() > >> ...do something with u... > > >> Hope this helps! > > >> -- > >> Hans Nowak (zephyrfalcon at gmail dot com)http://4.flowsnake.org/ > > > whoops, replied to author.... > > > What I wanted to ask before was won't 'u' be overwritten with a new > > object each time the loop ticks over? > > Yes, so you have to store it somewhere, if you want to keep the object around. > The list comprehension mentioned above stores all the objects in a list, after > which they can be accessed at will via indexing. > > > what I want to do is have, say 5 users in a game, so I'd have to spawn > > 5 objects. I can't do that because I have'nt hardcoded any object > > names for them. > > > or does it somehow work? how would I address them if they all have the > > name 'u'? > > users = [user() for i in range(n)] > > # use: users[0], users[1], etc > > -- > Hans Nowak (zephyrfalcon at gmail dot com)http://4.flowsnake.org/ Ok, wait, I see where this is going. I just did the list comprehension. I was under some misguided idea that you actually had to have a unique variable name for all the new objects you spawned. Thanks for all you help guys! From kretik at yahoo.com Wed Jun 18 02:18:51 2008 From: kretik at yahoo.com (kretik) Date: Tue, 17 Jun 2008 23:18:51 -0700 Subject: Ternary operator alternative in Ptyhon Message-ID: I'm sure this is a popular one, but after Googling for a while I couldn't figure out how to pull this off. Let's say I have this initializer on a class: def __init__(self, **params): I'd like to short-circuit the assignment of class field values passed in this dictionary to something like this: self.SomeField = \ params.has_key("mykey") ? params["mykey"] : None) Obviously I know this is not actual Python syntax, but what would be the equivalent? I'm trying to avoid this, basically: if params.has_key("mykey"): self.SomeField = params["mykey"] else: self.SomeField = None This is not a big deal of course, but I guess my main goal is to try and figure out of I'm not missing something more esoteric in the language that lets me do this. Thanks in advance. From kyosohma at gmail.com Wed Jun 25 14:43:50 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 25 Jun 2008 11:43:50 -0700 (PDT) Subject: how to give focus to another application References: Message-ID: <5e7909fb-eed2-45a8-9e94-94b8ee1f9c91@m3g2000hsc.googlegroups.com> On Jun 25, 1:23?pm, "massimo s." wrote: > Hi, > > I would like to know if 1)there is a Python way to tell under which > terminal process a Python command-line application is running 2)there > is a Python way to tell the OS to give focus to another window. > > Solutions for Windows, Linux and OS X are welcome, even if OS-specific > (of course general solutions are better, but I can kludge & check the > platform). > > Thanks, > M. On Windows, you can use the pywin32 modules to assist you. There's a sub-module in them called win32gui that has a SetForegroundWindow method. I usually use win32gui.EnumWindows() to loop through all the open processes and then use both win32gui.ShowWindow() and win32gui.SetForegroundWindow() to make the window I want appear. I'm guessing that each OS has their own methods for this as you would almost certainly have to use some kind of low-level calls to get handles on processes you didn't create. Thus, the likelihood that there are cross-platform methods is pretty low. ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org From Lie.1296 at gmail.com Sun Jun 8 02:08:38 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 7 Jun 2008 23:08:38 -0700 (PDT) Subject: New variable? References: <18105511-7ae1-45e9-8c43-f34c1c4f5aeb@c58g2000hsc.googlegroups.com> Message-ID: On Jun 4, 1:40?am, tmallen wrote: > What's the proper way to instantiate a new variable? x = ""? You don't need to. The reason why you need to "declare" variable when doing something like a += 1 is because this is actually a shorthand for a = a + 1 (unless you override __radd__), the a on the right-hand side is not yet assigned to any objects (remember that python use the "name tag" model instead of "variable" model). From hat at se-162.se.wtb.tue.nl Wed Jun 18 08:50:39 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 18 Jun 2008 14:50:39 +0200 Subject: dict order References: <4804032a-adef-4973-ae21-acc4ad2dce37@z72g2000hsb.googlegroups.com> <411fc353-dd54-4bbc-a72e-ddee66408313@c58g2000hsc.googlegroups.com> <1a7a2dc6-4acf-473d-a51c-4715ca9c7068@c19g2000prf.googlegroups.com> Message-ID: On 2008-06-18, Robert Bossy wrote: > Lie wrote: >>> Whoops, I think I misunderstood the question. If what you're asking >>> whether two dictionary is equal (equality comparison, rather than >>> sorting comparison). You could do something like this: >>> > Testing for equality and finding differences are trivial tasks indeed. > It is the sort order I'm interested in. The meaning of the order is not > really an issue, I'm rather looking for a consistent comparison function > (in the __cmp__ sense) such as: > if d1 > d2 and d2 > d3, > then d1 > d3 > > I'm not sure the hashing method suggested by Albert guarantees that. I read the post as the desire to test equality between dictionary-like data structures. With some care (see below) (and the ability to compute the hash fast), you could use hashing as way to decide that two such structures are not equal. Afaik you cannot use hashing for testing order ('<' or '>'). If I gave that impression, sorry; it was not my intention. In the equality case, you need special care with computing the hash value of the keys (and values), since you want to have the same hash result of the dictionary independent of the order of the keys. One way of achieving that is to use XOR (^) to combine hash-values of the elements. Unfortunately, XOR may not always produce good hash values. If you want ordered dictionaries (as in you can compare dictionaries with each other, and decide which is larger), I'd suggest to keep the keys of the dictionaries sorted. Dictionary comparing can then be done by comparing keys in increasing order (for example). If you encounter two non-equal keys, you immediately can use the order of those two keys as the order of the dictionaries. (ie the order of two dictionaries is decided by the order of the first non-equal keys). This gives you the transitive property (d1 > d2 and d2 > d3 implies d1 > d3). (and len() is a cheap first order filter here; dictionaries are ordered by length first, and by first non-equal keys second then.) I have used this trick to define ordered sets (which are basically dictionaries without value part). It worked like a charm. Sincerely, Albert From usenet at janc.be Fri Jun 6 16:59:47 2008 From: usenet at janc.be (Jan Claeys) Date: Fri, 06 Jun 2008 20:59:47 GMT Subject: Python is slow References: <4836772e$0$6097$426a74cc@news.free.fr> <89be7f59-4c08-4739-ab07-d310e0c6aef3@2g2000hsn.googlegroups.com> Message-ID: Op Fri, 23 May 2008 14:00:33 -0700, schreef bruno.desthuilliers at gmail.com: > Now this I can tell is false. The problem is not that it's difficult to > "make a native compiler for" dynamic languages, the problem is that it's > difficult to write native compiler for dynamic languages that generates > code that beats the VM/byte-code interpreter/whatever you name it to be > wotrh the effort. Well, it would be much easier if there would be hardware that was designed for object oriented & dynamic programming... ;-) (Most current hardware is designed for use with C & similar languages, or sometimes for massively parrallel computing (e.g. GPUs), but the last tries to design hardware to fit something like Python date back to the 1980s AFAIK...) -- JanC From johnjsal at gmailNOSPAM.com Sun Jun 15 23:11:08 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sun, 15 Jun 2008 23:11:08 -0400 Subject: newbie question: for loop within for loop confusion In-Reply-To: References: Message-ID: <4855d9d1$0$11629$607ed4bc@cv.net> takayuki wrote: > for letter in avoid: > if letter in word: > break > else: > print word Take the word 'dog', for example. What the above loop is doing is basically this: 1. for letter in avoid uses 'a' first 2. is 'a' in 'dog'? 3. no, so it prints 'dog' 4. go back to for loop, use 'b' 5. is 'b' in 'dog'? 6. no, so it prints 'dog' again 7. go back to for loop..... Since it goes sequentially through 'abcd', it will say that the first three letters are not in 'dog', and therefore print it three times. Then it finally sees that 'd' *is* in dog, so it skips it the fourth time through the loop. From cwitts at gmail.com Fri Jun 13 03:53:20 2008 From: cwitts at gmail.com (Chris) Date: Fri, 13 Jun 2008 00:53:20 -0700 (PDT) Subject: Comments on my first script? References: <7e3a7c92-6204-46dd-8df8-90218f2fb314@26g2000hsk.googlegroups.com> <4016716e-0ff7-41aa-951a-ed9562ff2ac8@m44g2000hsc.googlegroups.com> <7bb26acf-8b58-4d29-8e64-05a75eb5e584@d45g2000hsc.googlegroups.com> Message-ID: On Jun 13, 9:38?am, Phillip B Oldham wrote: > Thanks guys. Those comments are really helpful. The odd semi-colon is > my PHP background. Will probably be a hard habbit to break, that > one! ;) If I do accidentally drop a semi-colon at the end of the line, > will that cause any weird errors? > > Also, Chris, can you explain this: > a, b = line.split(': ')[:2] > > I understand the first section, but I've not seen [:2] before. That's slicing at work. What it is doing is only taking the first two elements of the list that is built by the line.split. From eliben at gmail.com Sat Jun 21 09:46:15 2008 From: eliben at gmail.com (eliben) Date: Sat, 21 Jun 2008 06:46:15 -0700 (PDT) Subject: Fast and easy GUI prototyping with Python References: <9c349bf0-ef63-4463-bd4e-cdbe331b58c3@z66g2000hsc.googlegroups.com> Message-ID: <2ad5ed9b-b813-4a8c-8aa5-cd87f02c2b27@s50g2000hsb.googlegroups.com> On Jun 21, 3:36 pm, ero... at gmail.com wrote: > Which tools would you use? I want the interface design to be as easy > and fast as possible, all ideology aside. I'm considering either > IronPython+Visual Studio or Python+Qt -- but I'm open for other > suggestions. > > Visual Studio seems to offer the easiest solution, but is IronPython > stable enough? How easy is the IronPython/Visual Studi integration? > What about IronPython Studio? I've had success using wxPython in conjunctin with wxGlade. wxGlade is quite flexible, allows quick previews and generates code that's not bad. The wxPython binding is very well supported and works nicely in practice. And, best of all, this solution is both free and completely cross-platform. Eli From bees.inc at gmail.com Wed Jun 4 04:03:42 2008 From: bees.inc at gmail.com (BEES INC) Date: Wed, 4 Jun 2008 18:03:42 +1000 Subject: Interesting Math Problem Message-ID: <748f2d520806040103q48689a01i310ee07df20a5e73@mail.gmail.com> I've been awfully busy programming lately. My Django-based side project is coming along well and I hope to have it ready for use in a few weeks. Please don't ask more about it, that's really all I can say for now. Anyways, I came across an interesting little math problem today and was hoping some skilled programmers out there could come up with a more elegant solution than mine. Problem: Star Ratings People can rate cheeseburgers on my website with a star rating of 0-5 stars (whole stars only), 5 being mighty tasty and 0 being disgusting. I would like to show the average of everyone's ratings of a particular cheeseburger to the nearest half star. I have already calculated the average rating as a float (star_sum) and the total number of people that rated the particular cheeseburger (num_raters). The result should be stored as a float in a variable named "stars." My Solution (in Python): # round to one decimal place and # separate into whole and fractional parts parts = str(round(star_sum/num_raters, 1)).split('.') whole = int(parts[0]) frac = int(parts[1]) if frac < 3: ___frac = 0 elif frac > 7: ___frac = 0 ___whole += 1 else: ___frac = 5 # recombine for a star rating rounded to the half stars = float(str(whole)+'.'+str(frac)) Mmmm? In-N-Out Burgers? Please reply if you've got a better solution. From larry.bates at websafe.com` Mon Jun 30 09:13:30 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 30 Jun 2008 08:13:30 -0500 Subject: List Performance In-Reply-To: References: <42358e0b-a351-4862-8f6a-1938eedeff6c@s21g2000prm.googlegroups.com> Message-ID: <2eydnaP-saOZQfXVnZ2dnUVZ_qvinZ2d@comcast.com> Peter Otten wrote: > Ampedesign wrote: > >> If I happen to have a list that contains over 50,000 items, will the >> size of the list severely impact the performance of appending to the >> list? > > No. > > $ python -m timeit -n20000 -s"items = []" "items.append(42)" > 20000 loops, best of 3: 0.554 usec per loop > $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" > 20000 loops, best of 3: 0.529 usec per loop > > http://wiki.python.org/moin/TimeComplexity > > Peter Peter, So its actually faster to append to a long list than an empty one? That certainly would not have been intuitively obvious now would it? -Larry From d3vvnull at gmail.com Thu Jun 5 07:51:54 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Thu, 5 Jun 2008 06:51:54 -0500 Subject: Python and Harry Potter? In-Reply-To: <6apvtsF3892asU1@mid.uni-berlin.de> References: <6aprloF38p4l7U1@mid.dfncis.de> <6apvtsF3892asU1@mid.uni-berlin.de> Message-ID: <170543c70806050451v326bf862l1b3a5e752328e8fb@mail.gmail.com> Harry Potter is a Parselmouth. He can speak to snakes. Of course, Amazon would get this right! Sheesh! On Thu, Jun 5, 2008 at 6:10 AM, Marc 'BlackJack' Rintsch wrote: > On Thu, 05 Jun 2008 11:58:14 +0200, Helmut Jarausch wrote: > > > Today I've got an email from Amazon recommending me > > Harry Potter and the Deathly Hallows > > > > and they told me why they recommended this book, > > because I've bought > > Core PYTHON Programming > > > > Didn't know, Harry Potter is a Python fan. > > I would've expected something with more magic, like Perl. :-) > > Ciao, > Marc 'BlackJack' Rintsch > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From s0suk3 at gmail.com Sat Jun 28 02:54:22 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Fri, 27 Jun 2008 23:54:22 -0700 (PDT) Subject: surprising behaviour of os.environ.clear References: Message-ID: <494d6aa7-5c66-4dab-98d9-2d3ac66fe198@a70g2000hsh.googlegroups.com> On Jun 27, 4:05 pm, "Joe P. Cool" wrote: > If I call os.environ.clear in a python program child processes still > see the deleted entries. But when I iterate over the keys like so > > names = os.environ.keys > for k in names: > del os.environ[k] > > then the entries are also deleted for the child processes. Where is > the difference? Is this a bug? > (Observed in Python 2.5.2) > For one thing, the expression 'os.environ.keys' will yield a method object (not a list, as you're probably expecting), but iterating over a method as you did should produce an exception. If you want to get the list of environment vars, you have to call the method, like 'os.environ.keys()'. Also, aren't changes to environment vars supposed to be visible to child processes anyway? Which one are you suggesting that behaves the wrong way, 'os.environ.clear()' or 'del os.environ[key]'? From alexnbryan at gmail.com Sat Jun 21 23:24:01 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Sat, 21 Jun 2008 22:24:01 -0500 Subject: Connecting a Desktop App to a Web App Message-ID: <61460E55-28FD-42A3-85EB-4D352E21CC30@gmail.com> Okay, well I wouldn't be creating the app, so, any hints on how to figure out the API of a web app I don't know super well? From support.intranet at libero.it Wed Jun 4 12:40:54 2008 From: support.intranet at libero.it (support.intranet at libero.it) Date: Wed, 4 Jun 2008 09:40:54 -0700 (PDT) Subject: Exit from os.chroot() References: Message-ID: On 4 Giu, 17:08, Wolfgang Draxinger wrote: > support.intranet wrote: > > Hello! I'm writing a small script and I need to call the > > os.chroot function. The problem is, a few lines below I need to > > call a program in /usr/bin. Is there a way to exit from the > > chroot, or to limit the chroot to a single function or thread? > > Thanks in advance > > No, chroot applies to the whole process and once applied it can't > be reverted. Otherwise the whole idea of chroot being a FS jail > would not work. > > So you need some programs in your chroot: Then put a directory > usr/bin into the chroot directory and bind the system's /usr/bin > there: > > mount --bind /usr/bin $chroot/usr/bin > > The same has to be done with all library stuff. Another option > would be to place a statically linked busybox and it's > subprogram links into the chroot > > Wolfgang Draxinger > -- > E-Mail address works, Jabber: hexar... at jabber.org, ICQ: 134682867 Thanks! I'll try the bind way From mensanator at aol.com Fri Jun 6 21:00:06 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 6 Jun 2008 18:00:06 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> <0294ec96$0$25039$c3e8da3@news.astraweb.com> Message-ID: <2fcf90a2-349d-4ef1-8f67-a357be71738f@d1g2000hsg.googlegroups.com> On Jun 6, 3:19?pm, "John Salerno" wrote: > "Mensanator" wrote in message > > news:c55356a4-04a0-442e-ad84-f35156cdec9c at z72g2000hsb.googlegroups.com... > On Jun 6, 1:44 am, "Terry Reedy" wrote: > > > "Mensanator" wrote in message > > And since the OP foolishly > hardcoded his range bounds > > Hmm, I just love the arrogance of some people. I actually posted a response > to my own thread that asked about this situation of how best to make the > range, but it doesn't seem to have posted. It wasn't meant to be arrogant. Just that you must be careful with zip() because it will not throw an exception if the two iterables are of different length (this behaviour is by design) but simply return tuples for the shorter of the iterables. Hardcoding the range bounds instead of setting them dynamically is a classic cause of this type of error. Obviously, you want the range to start with 8, but what should be the upper bound? The start plus the length of the other iterable keeping in mind that if length is 11, last index is 8+10 since counting starts at 0. So you want range(8,8+len(score_costs)) Using enumerate() means you don't have to figure this out and you'll never get an error or bad results that don't make an error. From kamhung.soh at gmail.com Fri Jun 6 19:03:23 2008 From: kamhung.soh at gmail.com (Kam-Hung Soh) Date: Sat, 07 Jun 2008 09:03:23 +1000 Subject: readline() & seek() ??? In-Reply-To: <078bfcbf-4f6c-459c-9f68-619af24c3678@27g2000hsf.googlegroups.com> References: <12655f64-33b1-4ab0-b6fb-294bfd2fa8c6@d45g2000hsc.googlegroups.com> <078bfcbf-4f6c-459c-9f68-619af24c3678@27g2000hsf.googlegroups.com> Message-ID: Chris wrote: > On Jun 6, 5:13 am, Kam-Hung Soh wrote: >> Tim Roberts wrote: >>> DataSmash wrote: >>>> I have a text file that contains thousands of lines and each line is >>>> 256 characters long. >>>> This is my task: >>>> For each line in the file, move to the 25th character, if the >>>> character is a "T", >>>> move to the 35th character of the line and read 5 characters from >>>> there. >>>> Capture these 5 characters and write them to a new text file, each 5 >>>> characters separated by a comma. >>>> I appreciate your help! >>> Did you even TRY this? Your task reads like pseudocode that translates >>> virtually line-for-line to Python code. >>> fout = open('outputfile.txt','w') >>> for line in open('inputfile.txt'): >>> if line[24] == 'T': >>> fout.write( line[34:39] + ',' ) >> Should the last line be ... >> >> fout.write(','.join(line[34:39]) >> >> -- >> Kam-Hung Soh Software Salariman > > each 5 characters need to be delimited by a comma, your statement > would have a comma between each of the 5 characters. You're right; I see where I got confused. -- Kam-Hung Soh Software Salariman From s0suk3 at gmail.com Sat Jun 7 02:57:03 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Fri, 6 Jun 2008 23:57:03 -0700 (PDT) Subject: Parsing a path to components References: <7d7dd66c-b2bb-4a9a-a2e4-589079cda97b@e39g2000hsf.googlegroups.com> Message-ID: <14bf5448-4677-4ced-9d79-b4eb0c048218@56g2000hsm.googlegroups.com> On Jun 7, 12:55?am, eliben wrote: > Hello, > > os.path.split returns the head and tail of a path, but what if I want > to have all the components ? I could not find a portable way to do > this in the standard library, so I've concocted the following > function. It uses os.path.split to be portable, at the expense of > efficiency. > > ---------------------------------- > def parse_path(path): > ? ? """ Parses a path to its components. > > ? ? ? ? Example: > ? ? ? ? ? ? parse_path("C:\\Python25\\lib\\site-packages\ > \zipextimporter.py") > > ? ? ? ? ? ? Returns: > ? ? ? ? ? ? ['C:\\', 'Python25', 'lib', 'site-packages', > 'zipextimporter.py'] > > ? ? ? ? This function uses os.path.split in an attempt to be portable. > ? ? ? ? It costs in performance. > ? ? """ > ? ? lst = [] > > ? ? while 1: > ? ? ? ? head, tail = os.path.split(path) > > ? ? ? ? if tail == '': > ? ? ? ? ? ? if head != '': lst.insert(0, head) > ? ? ? ? ? ? break > ? ? ? ? else: > ? ? ? ? ? ? lst.insert(0, tail) > ? ? ? ? ? ? path = head > > ? ? return lst > ---------------------------------- > > Did I miss something and there is a way to do this standardly ? > Is this function valid, or will there be cases that will confuse it ? > You can just split the path on `os.sep', which contains the path separator of the platform on which Python is running: components = pathString.split(os.sep) Sebastian From aisaac at american.edu Thu Jun 5 19:58:15 2008 From: aisaac at american.edu (Alan Isaac) Date: Thu, 05 Jun 2008 23:58:15 GMT Subject: parser recommendation In-Reply-To: References: Message-ID: One other possibility: SimpleParse (for speed). It is very nice. Alan Isaac From sjmachin at lexicon.net Wed Jun 25 19:02:52 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 25 Jun 2008 16:02:52 -0700 (PDT) Subject: Newbie question about tuples and list comprehensions References: Message-ID: On Jun 26, 7:37 am, idiolect wrote: > Hi all - Sorry to plague you with another newbie question from a > lurker. Hopefully, this will be simple. > > I have a list full of RGB pixel values read from an image. I want to > test each RGB band value per pixel, and set it to something else if it > meets or falls below a certain threshold - i.e., a Red value of 0 > would be changed to 50. > > I've built my list by using a Python Image Library statement akin to > the following: > > data = list(image.getdata()) > > Which produces a very long list that looks like [(0,150,175), > (50,175,225),...]. I'm trying to figure out a fast and pythonic way > to perform my operation. The closest I've come so far to a succinct > statement is a list comprehension along the syntax of: > > source = [((x,y,z),(x+50,y+50,z+50))[bool(x or y or z < 50)] for > (x,y,z) in source] > > ...which kind of approaches the effect I'm looking for, but it doesn't > really test and change each value in the tuple individually. My > understanding of the things you can do with lists and python in > general is rather naive, so I would appreciate any insight anyone can > offer since I am not sure if I'm even headed down the correct path > with list comprehensions. > "x or y or z < 50" doesn't do what you think it does: >>> x, y, z = 120, 130, 140 >>> x or y or z < 50 120 >>> ((x or y) or z) < 50 False >>> x or (y or (z < 50)) 120 >>> Here's one approach (requires Python 2.5 or later): [(50 if x < 50 else x, 50 if y < 50 else y, 50 if z < 50 else z) for (x, y, z) in source] From florencio.cano at gmail.com Wed Jun 11 04:33:52 2008 From: florencio.cano at gmail.com (Florencio Cano) Date: Wed, 11 Jun 2008 10:33:52 +0200 Subject: How to view how much memory some process use in Windows? Message-ID: How can I monitor with a Python script how much memory does a process use in Windows? I want to do statistics about memory consumption of processes like Firefox, Antivirus, etc. When I search in Google I only find information about how to monitor this in linux or how to reduce Python programs memory usage. From davidreynon at gmail.com Tue Jun 17 17:12:53 2008 From: davidreynon at gmail.com (korean_dave) Date: Tue, 17 Jun 2008 14:12:53 -0700 (PDT) Subject: using the string functions (ex. find()) on a multi-symbol string Message-ID: <8debb6d8-2181-4938-be02-5579b4ed8e14@d45g2000hsc.googlegroups.com> How can i use the find() function on a string that is composed of tons of symbols that cause errors... THis is my string: find("

Connected!

","margin") The tough part about this is that the string is dynamically produced. So I can't manually go into the string and eliminate the quote-marks or to "literal-character" them. From tjreedy at udel.edu Thu Jun 26 18:04:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 26 Jun 2008 18:04:40 -0400 Subject: Error when interfacing with TCP/IP In-Reply-To: <538D574F1250484EA840C88924E04B5E0C8A45AA@vistap101.vlgdc.visteon.com> References: <538D574F1250484EA840C88924E04B5E0C8A45AA@vistap101.vlgdc.visteon.com> Message-ID: Devarajulu, Baskar (D.) wrote: > Hi, > > I'm using Python and working for automation of testing ,I face error > when the script accessed TCP/IP Interface > > COMM_TYPE = 1 # Choose 1 - TCP IP Communication or 0 - > RS232 communication. > TCP_ip = '136.18.201.53' # the TCP IP address of the PC. > port = 8080 > BAUD_RATE = 115200 > > if (COMM_TYPE == 1): > asap3.TcpOpen(TCP_ip,port) > > Error: > > C:/Apps/dSPACE51/Common/Python22/Modules/InterfaceLibs/asap3lib.py", > line 320, in TcpOpen > asap3libError: Error connect TCP/IP > Thanks if you can help. asap3lib.py is not part of the stdlib, and the error message is not very informative. Look at line 320 and see what might trigger the error. From carbonimax at gmail.com Mon Jun 23 09:02:34 2008 From: carbonimax at gmail.com (Carbonimax) Date: Mon, 23 Jun 2008 06:02:34 -0700 (PDT) Subject: py2exe, PyQT, QtWebKit and jpeg problem References: Message-ID: <2b292f88-db2d-4fd3-a4b2-de72ff1b5387@c58g2000hsc.googlegroups.com> On Jun 21, 12:21?am, David Boddie wrote: > On Friday 20 June 2008 17:24, Phil Thompson wrote: > > > On Fri, 20 Jun 2008 08:04:57 -0700 (PDT), Carbonimax > > wrote: > >> I have a problem with py2exe and QtWebKit : > >> I make a program with a QtWebKit view. > >> If I launch the .py directly, all images (jpg, png) are displayed but > >> if I compile it with py2exe I have only png images. No jpg ! > >> No error message, nothing. > > >> Have you a solution ? Thank you. > > > At a guess, the JPEG support is implemented as a Qt plugin which you are > > not including. > > Yes, that would appear to the be most obvious cause. See here for another > report about this: > > http://lists.trolltech.com/qt4-preview-feedback/2008-03/msg00064.html > > David How can I do that ? If I copy the dll in the dist directory, and I use QPluginLoader() and load(), it does work in the .py but it doesn't in .exe made with py2exe my code : dll = QPluginLoader(path_to_dll) res = dll.load() res == true in the .py res == false in the .exe :-/ From ptmcg at austin.rr.com Wed Jun 18 10:01:23 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 18 Jun 2008 07:01:23 -0700 (PDT) Subject: Does '!=' equivelent to 'is not' [drifting OT...] References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> Message-ID: <9f496e22-31e8-4135-a3bc-a020476a90f5@b1g2000hsg.googlegroups.com> On Jun 17, 7:09?am, Derek Martin wrote: > On Tue, Jun 17, 2008 at 04:33:03AM -0300, Gabriel Genellina wrote: > > > Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)' > > > and 'not(id(a) == id(b))' > > > No. > > > Saying a flat "no" alone, without qualifying your statement is > generally interpreted as rude in English... ?It's kind of like how you > talk to children when they're too young to understand the explanation. > Yucky. > Geez, man, this is Usenet. If you want rude or condescending, the answer would have been "No, you flatulent moron." Or maybe the alarmist, "No! No! No!" I see the unqualified "No." often on this list, as a short cut for "Your technical explanation is flawed or has overlooked a critical point or corner case," and is usually followed by more details further down in the post to explain what the misconception or oversight was. Back in my college days, I would not be surprised for a professor to respond "No." (or worse) if I offered an erroneous explanation to another student. The unqualified "No." may be curt, and on a more sensitive day, one might write "No. (see below)", but as one of the most informed and careful posters on this list, I'm inclined to give Gabriel a little slack. -- Paul From alexnbryan at gmail.com Tue Jun 10 12:28:35 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 10 Jun 2008 09:28:35 -0700 (PDT) Subject: problems with opening files due to file's path Message-ID: <17759531.post@talk.nabble.com> Okay, so what I want my program to do it open a file, a music file in specific, and for this we will say it is an .mp3. Well, I am using the system() command from the os class. The problem I am running into is that when I send the path of the file to the system() command, which for those of you who don't know the system command is the equivalent of typing one command into command prompt or terminal depending on your system. But let's say that the file is "C:\Music\01 - Track.mp3" or something like that where the number 0 is next to the backslash. Another example is this "C:\Music\track(single)\Track.mp3" The problem here is that the ")" at the end of the single, is conflicting with the backslash as well. Now here is the exact code I was trying to do and when I run it I get false returned. system("\"C:\Documents and Settings\Alex\My Documents\My Music\Rhapsody\Bryanbros\Weezer\(2001)\04 - Island In The Sun.wma\"") Okay, now as you can see it sends it to the system with quotes "\"" and works if I change the file path and get rid of the "04" and the ")" it works, so that is the problem no doubt. If anyone has a way to do this please let me know, or even another way to open a music file like this. Help? -- View this message in context: http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17759531.html Sent from the Python - python-list mailing list archive at Nabble.com. From davidj411 at gmail.com Fri Jun 27 12:38:31 2008 From: davidj411 at gmail.com (davidj411) Date: Fri, 27 Jun 2008 09:38:31 -0700 (PDT) Subject: Using Python Scripts with IIS - ASP or Python-based CGI scripts with IIS - which makes more sense? Message-ID: when does is make sense to use a ASP style Page (.psp) over a Python- based CGI script with IIS. ? http://support.microsoft.com/kb/276494 ASP requires registering the python engine. which has better performance? The ASP style uses a new part of the python language which is unfamiliar to me, e.g. "Response.Write('Python Test
')" . Where can i learn about the syntax for ASP (PSP) with Python? Thanks! From duncan.booth at invalid.invalid Wed Jun 11 17:10:41 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Jun 2008 21:10:41 GMT Subject: basic code of what I am doing References: Message-ID: Alexnb wrote: > path = self.e.get() > path = "\"" + path + "\"" > os.startfile(path) Why are you adding spurious quote marks round the filename? os.startfile() will strip them off, but you don't need them. The help for os.startfile() does say though that the path must not start with a /, so you should use os.normpath to be on the safe side: os.startfile(os.path.normpath(self.e.get()) Anyway, the code works either with that change, or as you originally wrote it provided the path does not start with /. What was the question again? From floris.bruynooghe at gmail.com Mon Jun 30 20:25:54 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Mon, 30 Jun 2008 17:25:54 -0700 (PDT) Subject: lxml validation and xpath id function Message-ID: <018b5155-64f5-46b3-b426-7e6d6d1b20e3@k37g2000hsf.googlegroups.com> Hi I'm trying to use the .xpath('id("foo")') function on an lxml tree but can't get it to work. Given the following XML: And it's XMLSchema: Or in more readable, compact RelaxNG, form: element root { element child { attribute id { xsd:ID } } } Now I'm trying to parse the XML and use the .xpath() method to find the element using the id XPath function: from lxml import etree schema_root = etree.parse(file('schema.xsd')) schema = etree.XMLSchema(schema_root) parser = etree.XMLParser(schema=schema) root = etree.fromstring('', parser) root.xpath('id("foo")') --> [] I was expecting to get the element with that last statement (well, inside a list that is), but instead I just get an empty list. Is there anything obvious I'm doing wrong? As far as I can see the lxml documentation says this should work. Cheers Floris From cwitts at gmail.com Fri Jun 13 10:38:11 2008 From: cwitts at gmail.com (Chris) Date: Fri, 13 Jun 2008 07:38:11 -0700 (PDT) Subject: urllib (54, 'Connection reset by peer') error References: <92ecee86-ba92-4f14-b4f8-05064ef5406c@f63g2000hsf.googlegroups.com> Message-ID: <7cb6e19e-74f8-453d-b131-9b3739991cf9@s50g2000hsb.googlegroups.com> On Jun 13, 4:21?pm, chrispoliq... at gmail.com wrote: > Hi, > > I have a small Python script to fetch some pages from the internet. > There are a lot of pages and I am looping through them and then > downloading the page using urlretrieve() in the urllib module. > > The problem is that after 110 pages or so the script sort of hangs and > then I get the following traceback: > > > > Traceback (most recent call last): > ? File "volume_archiver.py", line 21, in > ? ? urllib.urlretrieve(remotefile,localfile) > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/urllib.py", line 89, in urlretrieve > ? ? return _urlopener.retrieve(url, filename, reporthook, data) > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/urllib.py", line 222, in retrieve > ? ? fp = self.open(url, data) > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/urllib.py", line 190, in open > ? ? return getattr(self, name)(url) > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/urllib.py", line 328, in open_http > ? ? errcode, errmsg, headers = h.getreply() > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/httplib.py", line 1195, in getreply > ? ? response = self._conn.getresponse() > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/httplib.py", line 924, in getresponse > ? ? response.begin() > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/httplib.py", line 385, in begin > ? ? version, status, reason = self._read_status() > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/httplib.py", line 343, in _read_status > ? ? line = self.fp.readline() > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/socket.py", line 331, in readline > ? ? data = recv(1) > IOError: [Errno socket error] (54, 'Connection reset by peer') > > > > My script code is as follows: > ----------------------------------------- > import os > import urllib > > volume_number = 149 # The volumes number 150 to 544 > > while volume_number < 544: > ? ? ? ? volume_number = volume_number + 1 > ? ? ? ? localfile = '/Users/Chris/Desktop/Decisions/' + str(volume_number) + > '.html' > ? ? ? ? remotefile = 'http://caselaw.lp.findlaw.com/scripts/getcase.pl? > court=us&navby=vol&vol=' + str(volume_number) > ? ? ? ? print 'Getting volume number:', volume_number > ? ? ? ? urllib.urlretrieve(remotefile,localfile) > > print 'Download complete.' > ----------------------------------------- > > Once I get the error once running the script again doesn't do much > good. ?It usually gets two or three pages and then hangs again. > > What is causing this? The server is causing it, you could just alter your code import os import urllib import time volume_number = 149 # The volumes number 150 to 544 localfile = '/Users/Chris/Desktop/Decisions/%s.html' remotefile = 'http://caselaw.lp.findlaw.com/scripts/getcase.pl? court=us&navby=vol&vol=%s' while volume_number < 544: volume_number += 1 print 'Getting volume number:', volume_number try: urllib.urlretrieve(remotefile%volume_number,localfile %volume_number) except IOError: volume_number -= 1 time.sleep(5) print 'Download complete.' That way if the attempt fails it rolls back the volume number, pauses for a few seconds and tries again. From sspatz at kcnet.com Sun Jun 22 09:44:25 2008 From: sspatz at kcnet.com (Saul Spatz) Date: Sun, 22 Jun 2008 08:44:25 -0500 Subject: Learning Python: Code critique please In-Reply-To: <2f25e0ae-5828-4651-8ac6-55ba8bb50089@p25g2000pri.googlegroups.com> References: <2f25e0ae-5828-4651-8ac6-55ba8bb50089@p25g2000pri.googlegroups.com> Message-ID: macoovacany wrote: > http://macoovacany.wordpress.com/ When I tried to run it, I got all kinds of syntax errors because of non-ASCII characters; namely, you have fancy left and right single and double quotes. Once I replaced these with the ASCII equivalents, it worked fine. I suggest you use a plain ASCII text editor, like the one that comes with IDLE. HTH, Saul From taygunkekec at gmail.com Mon Jun 23 08:21:08 2008 From: taygunkekec at gmail.com (Taygun Kekec) Date: Mon, 23 Jun 2008 05:21:08 -0700 (PDT) Subject: Learning Python in a group References: <507738ef0806220343r3e9ea053neeec0baf0ccfdbe6@mail.gmail.com> <18c1e6480806220422x5d06c54byd23b249bb699691f@mail.gmail.com> <507738ef0806220452s74358615v44518469cf3b5f45@mail.gmail.com> <18c1e6480806220511s5117aef4gb4ec93bceb44a0ac@mail.gmail.com> <337ab3f9-5334-4737-baac-fded524e6d99@s50g2000hsb.googlegroups.com> Message-ID: hi guys. I would be glad to join your group because i want to learn deeper python but i am frustrated of isolation too. It would provide stimulation and encourage to study and will boost our desire to learn. So count me in! From schickb at gmail.com Tue Jun 24 19:19:23 2008 From: schickb at gmail.com (schickb) Date: Tue, 24 Jun 2008 16:19:23 -0700 (PDT) Subject: Sequence iterators with __index__ References: <433c6aca-745e-4c9f-b182-d76291449829@m73g2000hsh.googlegroups.com> Message-ID: <119bb268-2064-4128-8006-f5564f0c62f8@q27g2000prf.googlegroups.com> On Jun 24, 3:45?pm, Matimus wrote: > > > I think it would be useful if iterators on sequences had the __index__ > > method so that they could be used to slice sequences. I was writing a > > class and wanted to return a list iterator to callers. ?I then wanted > > to let callers slice from an iterator's position, but that isn't > > supported without creating a custom iterator class. > > Could you post an example of what you are talking about? I'm not > getting it. Interactive mock-up: >>> a = ['x','y','z'] >>> it = iter(a) >>> a[it:] ['x', 'y', 'z'] >>> it.next() 'x' >>> a[it:] ['y', 'z'] >>> a[:it] ['x'] >>> it.next() 'y' >>> a[it:] ['z'] This lets you use sequence iterators more general position indicators. Currently if you want to track a position and slice from a tracked position you must do it manually with an integer index. It's not difficult, but given that sequence iterators already do that already it seems redundant (and of course more error prone). > In any case, the first step is writing a PEP.http://www.python.org/dev/peps/ > Ok thanks, but I do want some idea of interest level before spending a bunch of time on this. -Brad From keasler at llnl.gov Fri Jun 20 18:33:46 2008 From: keasler at llnl.gov (Jeff Keasler) Date: Fri, 20 Jun 2008 15:33:46 -0700 Subject: optparse functionality missing Message-ID: <485C304A.7030107@llnl.gov> Hi, optparse doesn't seem to have a pass-through capability for command line parameters/options that were not registered with add_option. I'm not the first person to complain about this. On Wed Mar 17 08:20:10 CET 2004, there's a thread titled "Perceived optparse shortcomings" where someone complains of the same problem. In a scripting environment, I often want to strip some of the command line options off the argument list, and then pass the remaining options to another module that is deeper in the tool chain. optparse doesn't seem to allow this, as far as I can tell. It requires that you register all possible options with add_option() or an error is flagged. When my second tier module is an autoconf script that could have hundreds of its own options, it seems dumb to have to register all those options, just to have to reconvert them to command-line options so that I can pass them to the autoconf command line. Could we get a mode added to optparse so that any commandline parameters/options that are not registered via add_option() can be in the args return value of the parse_args() method? -Jeff From ddasilva at umd.edu Sat Jun 28 02:02:47 2008 From: ddasilva at umd.edu (Daniel da Silva) Date: Sat, 28 Jun 2008 02:02:47 -0400 Subject: this is simple... In-Reply-To: <716a7999-a2c3-4792-90f5-f253c1e8296b@j33g2000pri.googlegroups.com> References: <716a7999-a2c3-4792-90f5-f253c1e8296b@j33g2000pri.googlegroups.com> Message-ID: <8d9ec3dd0806272302y48efe2f1ta2eb3f12bdfddcad@mail.gmail.com> ToshiBoy, You might want to take a look at the filter() function, it can also be used for the kind of the thing you're doing. http://docs.python.org/tut/node7.html#SECTION007130000000000000000 >>> B = range(1,27) >>> def test(b): ... if b*b in B: ... return True ... else: ... return False ... >>> A = filter(test, B) >>> A [1, 2, 3, 4, 5] Daniel On Sat, Jun 28, 2008 at 1:00 AM, ToshiBoy wrote: > On Jun 28, 2:48 pm, Mel wrote: > > ToshiBoy wrote: > > > I have two lists A and B that are both defined as range(1,27) I want > > > to find the entries that are valid for A = BxB > > [ ... ] > > > I get, as expected 1,4,9,16,25 printed out being the only members of B > > > where the condition is true, but when I print B I get: > > > > > [1, 2, 3, 4, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25] > > > > > 1 to 5 is correct, but why doesn't the remove method remove 7 and > > > above? What am I doing wrong here? > > > > Try this: > > > > A = range(1,27) > > B = range(1,27) > > C = [] > > > > for b in B: > > print "Trying", b > > if b*b in A: > > print b > > C.append (b) > > else: > > print "Removing", b > > B.remove(b) > > print 'B', B > > print 'C', C > > > > The essential problem is that your `B.remove`s are pulling the rug out > from > > under your `for b in B:`. There are ways to mess with B while you > iterate. > > Running though B backwards will do: `for b in B[::-1]:`, or iterating > over > > a copy of B: `for b in B[:]:` or `for b in list(B):`. Leaving B alone > and > > building up the desired items in C is probably simplest. > > > > Mel. > > Thank you, of course! :-) Didn't even think of that... that I was > modifying my iterators... > > Thank you > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From irmen.NOSPAM at xs4all.nl Sun Jun 29 07:43:34 2008 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 29 Jun 2008 13:43:34 +0200 Subject: pixel colour on screen In-Reply-To: References: Message-ID: <4867756b$0$14358$e4fe514c@news.xs4all.nl> Dennis Lee Bieber wrote: > On Sat, 28 Jun 2008 11:47:46 -0700 (PDT), cjstuttle at hotmail.com > declaimed the following in comp.lang.python: > >> Could anyone help me, I'm a python noob and need some help. im trying >> to find some code that will, given a screen co-ordinate, will give me >> the colour of that pixel in RGB. i have found a lot about getting the >> pixel colour from a picture file with a given co-ordinate, but is it >> possible to do it from the whole screen output regardless what >> application the selected pixel is in? >> > Such capability differs with OS and GUI libraries. If one is lucky, > the GUI library will accept any screen coordinate -- but it is just as > likely that the OS could limit a program to only coordinates within its > own window. Maybe the easiest way is to create a screenshot of the whole screen (that should be doable from within a program, although this differs for every OS and GUI lib as well) and then get the pixel value from that. --irmen From ahaupt at gmail.com Tue Jun 17 06:11:06 2008 From: ahaupt at gmail.com (AndreH) Date: Tue, 17 Jun 2008 03:11:06 -0700 (PDT) Subject: pyinotify issue References: Message-ID: <6297fd1a-89d2-482f-8a20-5539f7784b57@k13g2000hse.googlegroups.com> On Jun 13, 3:39 pm, AndreH wrote: > Good day, > > I just installed pyinotify on my gentoo box. > > When I test the library through "pyinotify.pv -v /tmp" under root, > everything works great, but when I try the same thing under my local > user account, I receive the following error: > Error: cannot watch . (WD=-1) > > Not very helpful. I've tried VERBOSE=True mode, but it doens't provide > any additional information. > > I also tried it for a directory in my home folder just to be sure it's > not a permission problem, but no luck. > > Any ideas? > > Regards, > Andre Ok I ended up solving my problem. pyinotify is just a wrapper for the c lib, inotif.h. Installing the inotify-tools package allows one to do better troubleshooting. First, my kernel version was too old and did not allow inotify to be executed at user-level. I bumped my kernel up to 2.6.24 and enabled the user-level execution flag. Then pyinotify worked once and failed for all consecutive retries. inotifwatch said that my "maximum number of user watches" was maxed out and that I should increase it under /proc/sys/fs/inotify/ max_user_watches. Something must be wrong, since the max_user_watches was set to 8192. I played around with this setting (sysctl -w fs.inotify.max_user_watches=16843), pyinotify.py and inotifywatch, and finally came the conclusion that pyinotify 0.7.0 was buggy. I got hold of 0.7.1 which seems to have fixed this problem. Hopefully, I'm not speaking too soon. From rychphd at gmail.com Mon Jun 23 08:32:55 2008 From: rychphd at gmail.com (rych) Date: Mon, 23 Jun 2008 05:32:55 -0700 (PDT) Subject: how to export functions by name for ctype References: <8f76bf6e-08b1-4af9-a739-bdc018553374@a1g2000hsb.googlegroups.com> Message-ID: On 23 Jun, 10:32, Nick Craig-Wood wrote: > rych wrote: > > ?I'm on Windows with VS2005 testing ctypes on a very simple dll > > ?I create a test.dll project which exports a function fntest(). I don't > > ?touch anything in the autogenerated source and build it. I can load > > ?the dll but can't access the function by its name fntest. Only by > > ?ordinal number or calling getattr with "?fntest@@YAHXZ". How do I > > ?export functions by name? It's probably rather a VS2005 question, but > > ?I'm a bit disappointed ctypes doesn't work with a default export > > ?convention. > > I guess you've compiled your DLL with C++ and the above is a C++ > mangled name. > > Either compile it with C, or export the names in an extern "C" { } > block. > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick That fixed it, thank you. From trepca at gmail.com Sat Jun 21 03:05:15 2008 From: trepca at gmail.com (Sebastjan Trepca) Date: Sat, 21 Jun 2008 09:05:15 +0200 Subject: Weird local variables behaviors In-Reply-To: <8e8a1d67-4d5f-4b52-a1aa-5a08f9530b75@y21g2000hsf.googlegroups.com> References: <8e8a1d67-4d5f-4b52-a1aa-5a08f9530b75@y21g2000hsf.googlegroups.com> Message-ID: I see, intuitively one would think it would try to get it from global context as it's not yet bound in the local. Thanks for the explanation. Sebastjan On Sat, Jun 21, 2008 at 5:48 AM, Dan Bishop wrote: > On Jun 20, 7:32 pm, Matt Nordhoff wrote: >> Sebastjan Trepca wrote: >> > Hey, >> >> > can someone please explain this behavior: >> >> > The code: >> >> > def test1(value=1): >> > def inner(): >> > print value >> > inner() >> >> > def test2(value=2): >> > def inner(): >> > value = value >> > inner() >> >> > test1() >> > test2() >> >> > [trepca at sauron ~/dev/tests]$ python locals.py >> > 1 >> > Traceback (most recent call last): >> > File "locals.py", line 13, in >> > test2() >> > File "locals.py", line 10, in test2 >> > inner() >> > File "locals.py", line 9, in inner >> > value = value >> > UnboundLocalError: local variable 'value' referenced before assignment >> >> > Why can't he find the variable in the second case? >> >> > Thanks, Sebastjan >> >> Python doesn't like when you read a variable that exists in an outer >> scope, then try to assign to it in this scope. >> >> (When you do "a = b", "b" is processed first. In this case, Python >> doesn't find a "value" variable in this scope, so it checks the outer >> scope, and does find it. But then when it gets to the "a = " part... >> well, I don't know, but it doesn't like it.) > > In a language like C++, the scope of a variable is determined by the > declaration. > > int x; // A > class Example > { > int x; // B > void f() > { > int x; // C > x = 42; // Which x? > } > }; > > The "x" referred to in the statement "x = 42;" refers to local > variable of Example::f. If line C were removed, then it would refer > to the member variable of class Example. And if line B were removed, > then it would refer to the global variable. > > In Python, however, there are no declarations. Therefore, it requires > another approach. What it chose was: > > (1) Explicit "self" for object attributes. > (2) A function's local variables are defined as those appearing on the > left side of an assignment. Whether the name happens to refer to a > global is NOT considered. > -- > http://mail.python.org/mailman/listinfo/python-list > From kretik at yahoo.com Thu Jun 19 00:01:36 2008 From: kretik at yahoo.com (kretik) Date: Wed, 18 Jun 2008 21:01:36 -0700 Subject: Ternary operator alternative in Ptyhon In-Reply-To: References: Message-ID: Thank you everyone. I ended up implementing the dict.get() method, which seems "cleaner", but I'll keep the (x if y else z) syntax in mind. I didn't know it existed, I guess it's what I was looking for to begin with. Thanks again! Allen wrote: > kretik wrote: >> I'm sure this is a popular one, but after Googling for a while I >> couldn't figure out how to pull this off. From gopalm at infotechsw.com Wed Jun 11 23:48:32 2008 From: gopalm at infotechsw.com (gopal mishra) Date: Thu, 12 Jun 2008 09:18:32 +0530 Subject: How to set directory in save as combo box Message-ID: <01f201c8cc3f$2f6ba990$2fc513ac@pwit.com> Hi, In 'save as' dialog of window application, I am trying to set the path in 'save in' combo box using python win32 programming. How we can set the directory in the 'save in' combo box. Thanks, Gopal -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Mon Jun 9 05:11:58 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 9 Jun 2008 02:11:58 -0700 (PDT) Subject: need help with timezone conversion (unexpected side effect of time.mktime ??) References: <8ea566b6-9562-4ee1-8c1a-5dffea553825@j22g2000hsf.googlegroups.com> <3a6e930b-9652-48c5-89d7-1d0560687a21@d45g2000hsc.googlegroups.com> <4c8fb0bb-3e92-4b1b-b5c8-ec0b86e8934e@e53g2000hsa.googlegroups.com> <28654738-beac-443a-9c3e-677c17d442ad@f63g2000hsf.googlegroups.com> Message-ID: <7b58406a-1d92-430a-968b-970f8bb7069a@d1g2000hsg.googlegroups.com> On 9 Jun, 07:40, Ivan Velev wrote: > Thanks Paul, > > I have identified the "problem" - because of daylight change this > particular timesamp was observed twice in Europe/Sofia. Here is the > GMT-to-local-time conversion: > > +------------+---------------------+---------------------+ > | gmt_stamp | gmt_time | local_time | > +------------+---------------------+---------------------+ > | 1130631000 | 2005-10-30 00:10:00 | 2005-10-30 03:10:00 | > +------------+---------------------+---------------------+ > | 1130634600 | 2005-10-30 01:10:00 | 2005-10-30 03:10:00 | > +------------+---------------------+---------------------+ > | 1130638200 | 2005-10-30 02:10:00 | 2005-10-30 04:10:00 | > +------------+---------------------+---------------------+ > | 1130641800 | 2005-10-30 03:10:00 | 2005-10-30 05:10:00 | > +------------+---------------------+---------------------+ I still don't understand why the "problematic" timestamp would affect the latter operation, though. I can see that both timestamps could be valid depending on which time zone is supposed to be in operation - have the dates for daylight saving (summer vs. winter) time changed in Bulgaria in the last few years? Maybe asking for a conversion for a date in 2004 invokes some old rules which then affect a conversion for a date in 2005, even though that would be really bad behaviour (which I don't see on this machine here). > When you do local-time-to-GMT conversion you can expect any of those > two timestamps. I missed that initially :( (I was sure that local time > has "one hour gap" and not "one hour of overlapping time") Well, it really isn't overlapping as such: you're in different zones, of course. ;-) > > and I'd recommend the datetime module for any serious work with dates and times. > > Last time when I was playing with TZ conversions, I was not able to do > anything using datetime module - it seems that one needs to define his > own set of timezones (+ all the details) to get it working ... Am I > wrong ? Can you show me how do accomplish the same conversion using > datetime module ? I think it's easiest to install one of the libraries which provides the zone data. The first one that comes to mind is python-dateutil, but I think there are others. Paul From dmitrey.kroshko at scipy.org Sat Jun 14 05:13:56 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sat, 14 Jun 2008 02:13:56 -0700 (PDT) Subject: write Python dict (mb with unicode) to a file Message-ID: hi all, what's the best way to write Python dictionary to a file? (and then read) There could be unicode field names and values encountered. Thank you in advance, D. From mccredie at gmail.com Thu Jun 12 13:28:46 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 12 Jun 2008 10:28:46 -0700 (PDT) Subject: Simple and safe evaluator References: Message-ID: <80b23a5a-8613-4232-8954-7f7e4181322e@k37g2000hsf.googlegroups.com> On Jun 11, 9:16 pm, George Sakkis wrote: > On Jun 11, 8:15 pm, bvdp wrote: > > > > > Matimus wrote: > > > > The solution I posted should work and is safe. It may not seem very > > > readable, but it is using Pythons internal parser to parse the passed > > > in string into an abstract symbol tree (rather than code). Normally > > > Python would just use the ast internally to create code. Instead I've > > > written the code to do that. By avoiding anything but simple operators > > > and literals it is guaranteed safe. > > > Just wondering ... how safe would: > > > eval(s, {"__builtins__":None}, {} ) > > > be? From my testing it seems that it parses out numbers properly (int > > and float) and does simple math like +, -, **, etc. It doesn't do > > functions like int(), sin(), etc ... but that is fine for my puposes. > > > Just playing a bit, it seems to give the same results as your code using > > ast does. I may be missing something! > > Probably you do; within a couple of minutes I came up with this: > > >>> s = """ > > ... (t for t in 42 .__class__.__base__.__subclasses__() > ... if t.__name__ == 'file').next()('/etc/passwd') > ... """>>> eval(s, {"__builtins__":None}, {} ) > > Traceback (most recent call last): > File "", line 1, in > File "", line 3, in > IOError: file() constructor not accessible in restricted mode > > Not an exploit yet but I wouldn't be surprised if there is one. Unless > you fully trust your users, an ast-based approach is your best bet. > > George You can get access to any new-style class that has been loaded. This exploit works on my machine (Windows XP). [code] # This assumes that ctypes was loaded, but keep in mind any classes # that have been loaded are potentially accessible. import ctypes s = """ ( t for t in 42 .__class__.__base__.__subclasses__() if t.__name__ == 'LibraryLoader' ).next()( ( t for t in 42 .__class__.__base__.__subclasses__() if t.__name__ == 'CDLL' ).next() ).msvcrt.system('dir') # replace 'dir' with something nasty """ eval(s, {"__builtins__":None}, {}) [/code] Matt From mccredie at gmail.com Wed Jun 11 17:30:56 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 11 Jun 2008 14:30:56 -0700 (PDT) Subject: Simple and safe evaluator References: Message-ID: <6de2cbf8-9ab0-462b-aa66-32a7895d70c9@a70g2000hsh.googlegroups.com> On Jun 11, 1:25 pm, bvdp wrote: > Is there a simple/safe expression evaluator I can use in a python > program. I just want to pass along a string in the form "1 + 44 / 3" or > perhaps "1 + (-4.3*5)" and get a numeric result. > > I can do this with eval() but I really don't want to subject my users to > the problems with that method. > > In this use I don't need python to worry about complex numbers, > variables or anything else. Just do the math on a set of values. Would > eval() with some restricted list of permitted operators do the trick? > > I'm feeling too lazy to write/debug my own parser for this :) > > Thanks, Bob. Here is something that I wrote using the _ast module. It works pretty well, and might be a good example for others wanting to experiment with the _ast module. On a related note... if anybody wants to provide feedback on this code it would be much appreciated. It involves a lot of if/elif branches, and feels ugly. Matt [code] import _ast class SafeEvalError(Exception): pass class UnsafeCode(SafeEvalError): pass # safe types: # Sequences: # list, tuple, dict, set, frozen_set* # Literals: str, unicode, int, long, complex, float def safe_eval(text): "similar to eval, but only works on literals" ast = compile(text, "", 'exec', _ast.PyCF_ONLY_AST) return _traverse(ast.body[0].value) def _traverse(ast): if isinstance(ast, _ast.List): return [_traverse(el) for el in ast.elts] elif isinstance(ast, _ast.Tuple): return tuple(_traverse(el) for el in ast.elts) elif isinstance(ast, _ast.Dict): return dict( zip( (_traverse(k) for k in ast.keys), (_traverse(v) for v in ast.values) ) ) elif isinstance(ast, _ast.Str): return ast.s elif isinstance(ast, _ast.Num): return ast.n elif isinstance(ast, _ast.Expr): return _traverse(ast.value) elif isinstance(ast, _ast.BinOp): if isinstance(ast.op, _ast.Add): return _traverse(ast.left) + _traverse(ast.right) elif isinstance(ast.op, _ast.Sub): return _traverse(ast.left) - _traverse(ast.right) elif isinstance(ast.op, _ast.Div): return _traverse(ast.left) / _traverse(ast.right) elif isinstance(ast.op, _ast.FloorDiv): return _traverse(ast.left) // _traverse(ast.right) elif isinstance(ast.op, _ast.Mod): return _traverse(ast.left) % _traverse(ast.right) elif isinstance(ast.op, _ast.Mult): return _traverse(ast.left) * _traverse(ast.right) elif isinstance(ast.op, _ast.Pow): return _traverse(ast.left) ** _traverse(ast.right) elif isinstance(ast.op, _ast.BitAnd): return _traverse(ast.left) & _traverse(ast.right) elif isinstance(ast.op, _ast.BitOr): return _traverse(ast.left) | _traverse(ast.right) elif isinstance(ast.op, _ast.BitXor): return _traverse(ast.left) ^ _traverse(ast.right) elif isinstance(ast.op, _ast.LShift): return _traverse(ast.left) << _traverse(ast.right) elif isinstance(ast.op, _ast.RShift): return _traverse(ast.left) >> _traverse(ast.right) elif isinstance(ast, _ast.BoolOp): if isinstance(ast.op, _ast.And): return all(_traverse(v) for v in ast.values) if isinstance(ast.op, _ast.Or): return any(_traverse(v) for v in ast.values) elif isinstance(ast, _ast.UnaryOp): if isinstance(ast.op, _ast.Invert): return _traverse(ast.operand) if isinstance(ast.op, _ast.USub): return -_traverse(ast.operand) if isinstance(ast.op, _ast.UAdd): return +_traverse(ast.operand) if isinstance(ast.op, _ast.Not): return not _traverse(ast.operand) raise UnsafeCode() if __name__ == "__main__": print safe_eval("[1,2,3,{'hello':1}, (1,-2,3)], 4j, 1+5j, ~1+2*3") [/code] From Russ.Paielli at gmail.com Wed Jun 4 00:45:04 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 3 Jun 2008 21:45:04 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> <873antn9il.fsf@benfinney.id.au> Message-ID: <87e962bb-a658-4240-9bbe-e848c190c451@a32g2000prf.googlegroups.com> On Jun 3, 8:50 pm, Ben Finney wrote: > alex23 writes: > > So the basic answers I'm seeing that "do just fine" are: > > > 1. Don't test private functions. > > 2. Add functionality _to_ the private functions for testing. > > 3. Change the interface for the purpose of testing. > > > All of which seem exceptionally inefficient and run counter to the > > whole purpose of unit testing. > > It seems you have a different idea of what unit testing is for from > me. > > Isn't the entire point of encapsulation to separate internal > components from the external interface? > > Why would a unit test, the whole purpose of which is to assert some > aspect of the external behaviour of the unit of code, care about how > that code unit is implemented internally? > > If changing the internal, encapsulated components of a unit causes its > external behaviour to change, that's a bug; either in the change made > (it shouldn't have altered the external behaviour), or in the unit > test asserting the wrong thing (it shouldn't be asserting anything > about internal state of the code). > > -- > \ ?Try to become not a man of success, but try rather to become | > `\ a man of value.? ?Albert Einstein | > _o__) | > Ben Finney Thank you. Let me just add that, as I said before, I think "private" data (if it were added to Python) should be accessible through some sort of "indirect" mechanism akin to the double-leading-underscore rule. Then, even if it *is* needed for unit testing, it can be accessed. As for unit testing in C++, Java, and Ada, I confess I know nothing about it, but I assume it gets done. Considering that Ada is used to manage and control fighter jets, cruise missiles, and nuclear arsenals, let's hope it gets done right. From cwitts at gmail.com Wed Jun 25 07:33:12 2008 From: cwitts at gmail.com (Chris) Date: Wed, 25 Jun 2008 04:33:12 -0700 (PDT) Subject: python -regular expression - list element References: <62e21ec1-18f3-4572-b223-1b8a5c40688c@f63g2000hsf.googlegroups.com> <87abh9pzyd.fsf@benfinney.id.au> Message-ID: <09a7f1dd-7cb8-4369-8af7-160276b71f0e@m73g2000hsh.googlegroups.com> On Jun 25, 12:32?pm, Ben Finney wrote: > antar2 writes: > > for x in list1: > > ? ?re.compile(x) > > ? ?for y in list2: > > ? ? ? ? ? ?re.compile(y) > > ? ? ? ? ? ?if x in y: > > ? ? ? ? ? ? ? ? ? ?z = re.sub(x, 'u', y) > > but this does not work > > You need to frotz the hymangirator with spangule. > > That, or show us the actual result you're seeing and how it differs > from what you expect to happen. > > -- > ?\ ? ? "I must say that I find television very educational. The minute | > ? `\ ? somebody turns it on, I go to the library and read a book." ?-- | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Groucho Marx | > Ben Finney That made me laugh :D Why not a list comprehension ? ::: list1 = ['a','o'] ::: list2 = ['star', 'day', 'work', 'hello'] ::: [l2.replace(l1,'u') for l2 in list2 for l1 in list1 if l1 in l2] ['stur', 'duy', 'wurk', 'hellu'] From fc14301589 at icqmail.com Sun Jun 1 03:24:41 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Sun, 01 Jun 2008 15:24:41 +0800 Subject: File browser in python gui References: <4841353e_1@news.tm.net.my> <48419d7c_2@news.tm.net.my> Message-ID: <48424eb9_1@news.tm.net.my> On 02:48, domenica 01 giugno 2008 TheSaint wrote: > I'm gonna back to study a little I'm facing tough time, I can't get clear by Trolltech's C++ examples. I'm a bit puzzled :), I'd like to remain with the QT widget set, but hard learning curve. Other simplified developing TK are giving different widgets, I don't expect to mix up :( -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From lepto.python at gmail.com Tue Jun 24 02:23:12 2008 From: lepto.python at gmail.com (oyster) Date: Tue, 24 Jun 2008 14:23:12 +0800 Subject: Any GUI lib wiget is capable of a WYSIWYG editor? Message-ID: <6a4f17690806232323p5f10ff22s15b65d97539eed57@mail.gmail.com> that is an html editor with text and picture, while the picture is linked to the local image file. for wxPython, the richtextcontrol save the image as en embedded object, so it is not my choice is there any other GUI lib and/or sample code to do so? thanks From straton at lampsacos.demon.co.uk Mon Jun 23 04:59:41 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Mon, 23 Jun 2008 09:59:41 +0100 Subject: binary number format ? format character %b or similar. In-Reply-To: <194cf4ed-2ca4-455b-b36e-9fb69b118c07@d77g2000hsb.googlegroups.com> References: <194cf4ed-2ca4-455b-b36e-9fb69b118c07@d77g2000hsb.googlegroups.com> Message-ID: Mensanator wrote: > On Jun 22, 4:07?pm, Ken Starks wrote: >> weheh wrote: >>> I don't know if you found this example: >>> http://www.daniweb.com/code/snippet285.html >> Thanks for that. The offerings are very similar to the >> algorithms I wrote myself. >> >> It wasn't the solution I was after,really; that's >> easy. It was whether anything had found its way into >> the standard library. > > Isn't that coming in Python 3.0? Thanks for the tip! following which, I found information at: http://docs.python.org/dev/3.0/library/string.html#formatstrings > > You could also use gmpy, which has a lot of > other bit-functionality in addition to displaying > them. > Yes, that'll be useful. Thanks again. From deets at nospam.web.de Mon Jun 9 09:34:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 09 Jun 2008 15:34:27 +0200 Subject: lists to save in a tuple References: <130e261e-1e1a-4657-b8db-8a7704fb083d@z66g2000hsc.googlegroups.com> Message-ID: <6b4psbF35e8fgU1@mid.uni-berlin.de> Nader wrote: > Hello, > > I have two lists and would save them in a tuple. > > a = [1,2,3] > b = ['a','b','c'] > > with the next statement I can do that: > > t = [(x,y), for x in a for y in b] > > This gives the next list: > > [(1,'a'),(1,'b'),(1,'c'), (2,'a'),(2,'b'),(2,'c'), (3,'a'),(3,'b'), > (3,'c')] > > But I want the next list: > > [(1,'a'),(2,'b'),(3,'c')] > > Would somebody tell me how I can solve this problem? zip(a, b) Diez From upton at virginia.edu Fri Jun 27 16:14:01 2008 From: upton at virginia.edu (Dan Upton) Date: Fri, 27 Jun 2008 16:14:01 -0400 Subject: [Employment] New TurboGears Job in Eugene, OR In-Reply-To: <486547C9.7090701@ulmcnett.com> References: <4df107ec-7193-412a-addf-ecbb4b6a3f3a@p25g2000hsf.googlegroups.com> <486547C9.7090701@ulmcnett.com> Message-ID: <5504f9ac0806271314oc8fc35ct3511fa208a872d38@mail.gmail.com> On Fri, Jun 27, 2008 at 4:04 PM, Paul McNett

wrote: > Silas Snider wrote: >> >> Full-time academic year position >> Salary range: $2819 - $4404 per month ( $16.26 - $25.41 per hour) > >> The following knowledge, skills and experience are necessary for this >> position: >> >> Expert Python and SQL programming skills, and proficiency with >> Javascript, CSS, XHTML and web standards. Professional experience with >> open source projects, ideally using Turbogears and MySQL. Experience >> with Mac OSX Server or other server administration. Familiarity with >> version control. Skills using on-line documentation for open source >> packages. Wide knowledge of open-source software and ability to find, >> evaluate, learn and implement new open source technologies. > > They want an expert for a maximum of $25 per hour? If they find someone, > it'll be a pretty good bullshitter looking for experience. > That's often the problem with academic positions. They frequently just don't have the money for what they actually want. I used to work for a university's web office and they listed the position as requiring a CompSci degree at least 2 years experience, but the offered salary was low even for someone being hired right out of college. From johnjsal at NOSPAMgmail.com Tue Jun 17 09:39:07 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 17 Jun 2008 09:39:07 -0400 Subject: Buffer size when receiving data through a socket? References: <20080616202135.41c407de.johnjsal@NOSPAMgmail.com> Message-ID: <03985958$0$8452$c3e8da3@news.astraweb.com> "John Salerno" wrote in message news:20080616202135.41c407de.johnjsal at NOSPAMgmail.com... > from socket import * > > host = 'localhost' > port = 51567 > address = (host, port) > buffer_size = 1024 > > client_socket = socket(AF_INET, SOCK_STREAM) > client_socket.connect(address) > > while True: > data = raw_input('> ') > if not data: > break > client_socket.send(data) > data = client_socket.recv(buffer_size) > if not data: > break > print data > > client_socket.close() Also, is that second "if not data: break" statement necessary? It seems like once you get past the first if, you don't need the second one. Of course, I guses it's possible that the server could return a False value, but even still, would it make sense to break out of the loop and close the connection because of that? It runs fine without the if statement, but I'm wondering if I just haven't encountered the proper problem situation yet. From dstromberglists at gmail.com Fri Jun 13 14:24:10 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Fri, 13 Jun 2008 18:24:10 GMT Subject: How to sort very large arrays? References: Message-ID: On Fri, 13 Jun 2008 17:54:32 +0000, kj wrote: > I'm downloading some very large tables from a remote site. I want to > sort these tables in a particular way before saving them to disk. In > the past I found that the most efficient way to do this was to > piggy-back on Unix's highly optimized sort command. So, from within a > Perl script, I'd create a pipe handle through sort and then just print > the data through that handle: > > open my $out, "|$sort -t '\t' -k1,1 -k2,2 -u > $out_file" or die $!; > print $out $_ for @data; > > But that's distinctly Perlish, and I'm wondering what's the "Python Way" > to do this. > > TIA! > > kynn os.system and os.popen are much like what you'd find in C. The subprocess module is more specific to python, and is a little more complicated but more powerful. From omer at no-log.org Wed Jun 25 15:24:25 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Wed, 25 Jun 2008 21:24:25 +0200 Subject: reading from list with paths In-Reply-To: <6c1ed580-259a-4df2-b389-ecf38296a138@25g2000hsx.googlegroups.com> References: <6c1ed580-259a-4df2-b389-ecf38296a138@25g2000hsx.googlegroups.com> Message-ID: <200806252124.25967.omer@no-log.org> Le Wednesday 25 June 2008 20:59:38 antar2, vous avez ?crit?: > Hello, > > I would like to read and print files, of which the complete filepaths > are > mentioned in another textfile. In this textfile (list.txt) are for > example the following paths: > > /data/chorec/chorec-nieuw/s01/S01C001M1/S01C001M1_1LG_f01.TextGrid > /data/chorec/chorec-nieuw/s01/S01C001M1/ > S01C001M1_1LGPseudo_f01.TextGrid > /data/chorec/chorec-nieuw/s01/S01C001M1/S01C001M1_AVI1_f01.TextGrid > > I know how to open and read one file in my current directory, > but after trying to find this out my self, I give up... > > I already got one answer for this question, but it did not work > What's the problem exactly ? If you already know how to read a file you have all what you need: f_list = open('list.txt') for filename in f_list : f = open(filename) print f.read() f.close() f_list.close() If you get an error, please post the full error message with the backtrace. -- C?dric Lucantis From sarvi at cisco.com Fri Jun 20 01:26:15 2008 From: sarvi at cisco.com (Saravanan Shanmugham (sarvi)) Date: Thu, 19 Jun 2008 22:26:15 -0700 Subject: Python as a Testing Language - TTCN-3 Comparison Message-ID: Well, looks like someone did such a comparison just recently. Just FYI PDF at the link below http://www.site.uottawa.ca/~bernard/A%20comparison%20between%20ttcn-3%20 and%20python%20v%2011.pdf Comparing TTCN-3 with raw python as they have done is not fair. But even then some of the comparisons made does not seem to make good use of python constructs to be fair. It seems to me with a little bit of a well written python test framework behind the scenes the comparison wouldn't be as bad as this document shows. For example they compare a TTCN-3 structure and template to Python objects. But I am guessing for these uses a Dictionary would have been a better way of representing a TTCN-3 template or structure in python. Anyway, to me what this does point out is that the current python test frameworks(python the language) are just good enough, compared to TTCN-3. We just need a better python test framework and may be in that process we may be able to identify some python language constructs, if any, that might make it easier to build the test framework or describe test cases. Sarvi ________________________________ From: Saravanan Shanmugham (sarvi) Sent: Wednesday, June 11, 2008 1:28 PM To: 'python-list at python.org' Subject: Python as a Testing Language - TTCN-3 Comparison Hi, Is there any work being done to make Python better suited for writing test cases for any problem space. I am a huge python fan and one of the things that got me there was the simplicy and elegance its constructs that allow me to do complex programming operations in very few lines without compromising on readability. When I was looking for an efficient language for describing test cases for any problem domain, I naturally thought Python would be my best bet. (Even though Tcl is used extensively, and I have used it). But I found something called TTCN-3 which is a language designed specifcally for describing test cases. I found the following comparison of TTCN-3 with Junit and Tcl http://www.site.uottawa.ca/~bernard/Tutorial_JUnit_tcltk_ttcn-3_animated .pdf It clearly shows the elegance of the language when it comes to describing test cases. Questions: 1. Does anyone one know of a similar comparison of TTCN-3 with Python? Or does some one have an idea how it would compare if we actually did a comparison. 2. Two powerfull things that seems to make TTCN-3 suite for testing is the Template matching mechanism and the concept Alternate matching or Trees. How best do we do this in Python? Is there room for improvement language constructs that could make this simpler. Thx, Sarvi -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Tue Jun 17 07:21:20 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 17 Jun 2008 04:21:20 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <4856e80c$0$30401$9b622d9e@news.freenet.de> <2d1e9b84-3dc7-4822-9c61-73991a527c67@s50g2000hsb.googlegroups.com> <48574b41$0$30410$9b622d9e@news.freenet.de> Message-ID: <31defced-c60d-45dc-a32a-af01a2b84c89@2g2000hsn.googlegroups.com> Martin v. L.: > http://wiki.python.org/moin/TimeComplexity Thank you, I think that's not a list of guarantees, while a list of how things are now in CPython. > If so, what's the advantage of using that method over d.items[n]? I think I have lost the thread here, sorry. So I explain again what I mean. I think for this data structure it's important to keep all the normal dict operations at the same speed. If you use a C implementation vaguely similar to my pure python recipe you can perform the del in O(1) too, because pairs are joined in (double) linked list. But such data structure is O(n) to find the n-th item inserted into the sequence. Bye, bearophile From geoff.bache at jeppesen.com Wed Jun 11 16:51:29 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Wed, 11 Jun 2008 13:51:29 -0700 (PDT) Subject: Converting a simple python script to a simple windows executable References: <135a4069-8d99-4fef-b794-ac3e87ea9a25@e39g2000hsf.googlegroups.com> Message-ID: On Jun 11, 9:49?pm, jay graves wrote: > On Jun 11, 2:25 pm, geoffbache wrote: > > > Anyone have any better ideas? > > How about ExeMaker? > > http://effbot.org/zone/exemaker.htm > > I have not used it but it seems to do what you want. > > ... > Jay Thanks, this looks very promising! Will try out a bit more tomorrow but I think it should work. Regards, Geoff From alexelder at gmail.com Mon Jun 16 14:07:38 2008 From: alexelder at gmail.com (Alex Elder) Date: Mon, 16 Jun 2008 11:07:38 -0700 (PDT) Subject: String Concatenation O(n^2) (was: Re: Explaining Implementing a Binary Search Tree.) References: <3fc761710806160941q3c1a93b5p7761fbe148718585@mail.gmail.com> <20080616170916.4714.1881297769.divmod.quotient.9773@ohm> Message-ID: I found this article useful when dealing with strings in Python: http://www.skymind.com/~ocrow/python_string/ It may help squeeze some more time out of your code. 8-) Alex. From workitharder at gmail.com Mon Jun 9 01:46:25 2008 From: workitharder at gmail.com (bukzor) Date: Sun, 8 Jun 2008 22:46:25 -0700 (PDT) Subject: Newbie help (TypeError: int argument required) References: Message-ID: <98ee3f11-cd9c-412e-8c9e-9d38943484c5@z24g2000prf.googlegroups.com> On Jun 8, 11:43?am, Iain Adams wrote: > Hi, > > I am new to python. I have been having trouble using the MysqlDB. I > get an error pointing from the line > > cursor.execute("UPDATE article SET title = %s, text = %s WHERE id = > %u", (self.title, self.text, self.id)) > > Here is the error: > > ?line 56, in save > ? ? cursor.execute("UPDATE article SET title = %s, text = %s WHERE id > = %u", (self.title, self.text, self.id)) > ? File "/var/lib/python-support/python2.5/MySQLdb/cursors.py", line > 151, in execute > ? ? query = query % db.literal(args) > TypeError: int argument required > > However when I print out type(self.id) I get . > > So surely I have provided an int argument. > > Any ideas anyone?? Change your u to an s and you'll be fine. If you want a specific format on the integer, format it first and pass in the string. From cwitts at gmail.com Wed Jun 4 04:38:38 2008 From: cwitts at gmail.com (Chris) Date: Wed, 4 Jun 2008 01:38:38 -0700 (PDT) Subject: Help need with subprocess communicate References: <0312b7e9-bffe-4360-bf3a-f5b3b26d243d@l64g2000hse.googlegroups.com> <530ccda9-818e-4abe-9f82-0720e27c48fd@z72g2000hsb.googlegroups.com> <8aef95d4-065d-4afe-bed6-bb3b4aabe04e@u12g2000prd.googlegroups.com> <94CdnYdgxM4m19vVnZ2dnUVZ_qTinZ2d@earthlink.com> Message-ID: <5300f781-51db-4d84-bf62-e05c04b6aba6@l42g2000hsc.googlegroups.com> On Jun 4, 9:56?am, Dennis Lee Bieber wrote: > On Tue, 3 Jun 2008 23:48:38 -0700 (PDT), rdab... at gmail.com declaimed the > following in comp.lang.python: > > > Is there way to configure the stdout buffer size so that it flushes > > earlier.. > > Is there a way to make above mentioned piece code working? > > ? ? ? ? I believe there is a command line argument that will set Python into > an unbuffered mode... BUT, unless the spawned process/program has some > similar option, you have no control over its output. > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? ?wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ starting your application with "python -u" sets it to unbuffered binary stdout and stderr, hopefully that helps. From grflanagan at gmail.com Tue Jun 17 03:48:52 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Tue, 17 Jun 2008 09:48:52 +0200 Subject: Removing inheritance (decorator pattern ?) In-Reply-To: <200806170510.58587.maric@aristote.info> References: <439e5f62-73d2-4d13-88b5-8d7afa16da09@w7g2000hsa.googlegroups.com> <200806170510.58587.maric@aristote.info> Message-ID: Maric Michaud wrote: > Le Monday 16 June 2008 20:35:22 George Sakkis, vous avez ?crit : >> On Jun 16, 1:49 pm, Gerard flanagan wrote: [...] >>> variation of your toy code. I was thinking the Strategy pattern, >>> different classes have different initialisation strategies? But then you >>> could end up with as many Strategy classes as subclasses, I don't know. [...] >> This doesn't solve the original problem, the combinatorial explosion >> of empty subclasses. [...] > > Yes, and it fails to implement the strategy pattern as well... which would > have solved the problem as it is intended exactly for this purpose. > Ok, better would have been 'my made-up strategy pattern, any resemblance to other patterns, either living or dead, is purely coincidental' :-) Non-canonically, G. From jonas at MIT.EDU Thu Jun 12 17:21:31 2008 From: jonas at MIT.EDU (Eric Jonas) Date: Thu, 12 Jun 2008 17:21:31 -0400 Subject: cPickle asymptotic performance? In-Reply-To: <8763se4h1s.fsf@mulj.homelinux.net> References: <8763se4h1s.fsf@mulj.homelinux.net> Message-ID: <1213305691.8320.28.camel@convolution> On Thu, 2008-06-12 at 20:57 +0200, Hrvoje Niksic wrote: > Eric Jonas writes: > > > I've done some benchmarking while attempting to serialize my (large) > > graph data structure with cPickle; I'm seeing superlinear performance > > (plotting it seems to suggest n^2 where n is the number of nodes of my > > graph), in the duration of the pickle.dump calls and I can't quite > > figure out why. > > Try gc.disable() before loading the pickle, and gc.enable() after. > > > Is cPickle's behavior known to be O(n^2)? > > No, but the garbage collector's sometimes is. Wow, that totally fixed it -- we went from 1200 seconds to 60 seconds. I'm somewhat shocked -- is the occasionally-abysmal behavior of the GC documented anywhere? ...Eric From gandalf at shopzeus.com Mon Jun 9 05:10:59 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 09 Jun 2008 11:10:59 +0200 Subject: [Fwd: Re: How to make one program connect to more than one TCP?] In-Reply-To: <1174.10.191.1.101.1212967299.squirrel@webmail.its.ac.id> References: <1361.222.124.226.218.1212587123.squirrel@webmail.its.ac.id> <4846A609.6080809@shopzeus.com> <1174.10.191.1.101.1212967299.squirrel@webmail.its.ac.id> Message-ID: <484CF3A3.1030306@shopzeus.com> agus at cs.its.ac.id wrote: > i want to make one program that the steps like this: > 1. download email from email account, for example: agus at yahoo.com, saved > in a file, for example: downloadedEmail.txt > Can be done via the standard imaplib module. No need to use twisted. > 2. parsing the downloadedEmail.txt, get the sender, subject and the > message.if there is attachmet/s, not be taken. > Save it as an eml file. Use the standard email.Parser module for extracting headers. > 3. posting the downloadedEmail.txt that has been parsed into nntp server. > 4. open nntp client for example 'thunderbird' to acces your nntp server. > I have no clue about it. > i attach my programs to u.. > it is very important for me as final project in my study class, too > difficult for me....thanks for your help!!! > Well, I can send you some examples that show how to download and parse emails from imap server. I have never used nntp before so.... Some examples are attached, and also a code fragment: IMAPDate.py - to convert between IMAP and datetime.date imaputils.py - to show how to connect to IMAP server and list folders on it (you need to create your own local.py file...), also shows how to append a new message to a folder on the imap server. code_fragment.py - to show how to search for messages on the server and download them as pure data string, it is NOT a complete program! And finally, here is how you parse and email: import email.Parser email_data = file('test2.eml','rb').read() parser = email.Parser.Parser() Then you need to example "parser" and its methods. Anyway, it is your homework, I don't think that I'm going to give more help unless you have a specific question. :-) Best, Laszlo -------------- next part -------------- A non-text attachment was scrubbed... Name: IMAPDate.py Type: text/x-python Size: 1372 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: imaputils.py Type: text/x-python Size: 1285 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: code_fragment.py Type: text/x-python Size: 4805 bytes Desc: not available URL: From maric at aristote.info Fri Jun 13 12:55:24 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 13 Jun 2008 18:55:24 +0200 Subject: Summing a 2D list In-Reply-To: <873anhtjlr.fsf@ara.blue-cable.net> References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <873anhtjlr.fsf@ara.blue-cable.net> Message-ID: <200806131855.24859.maric@aristote.info> Hello, Le Friday 13 June 2008 17:55:44 Karsten Heymann, vous avez ?crit?: > Maric Michaud writes: > > So, writing C in python, which has dictionnary as builtin type, > > should be considered "more elegant" ? > > IMO that's a bit harsh. > harsh ? Sorry, I'm not sure to understand. > > You are comparing apples with lemons, there is no such a difference > > between list index access and dictionnary key access in Python. > > [...] > > > If you know in advance the number and names of users, what prevent > > you to initialize completelly the target dictionnary ? > > > > The following code compare the same algorithm, once with list and > > the second time with dict : > > [...] > > > The result is pretty close now : > > > > maric at redflag1 17:04:36:~$ ./test.py > > with list 1.40726399422 > > with dict 1.63094091415 > > > > So why use list where the obvious and natural data structure is a > > dictionnary ? > > I'd never argue that using a dictionary is the obvious and natural > data structure for this case. But is it the best? Honestly, as your > very nice example shows, we have two solutions that are equally fast, > equally complex to code and equally robust, but one needs Yes, but my example take ordered integer for keys (users' names) which they should not be in a real case, so retrieving the result is by way easier (and faster) with a dictionnary. > approximately the double amount of memory compared to the other. I don't see how you came to this conclusion. Are you sure the extra list take twice more memory than the extra dictionary ? > So, as much as i like dictionaries, what's the gain you get from using it > in this corner case? It's the very purpose of it's usage, store and retrieve data by key. Cheers, -- _____________ Maric Michaud From george.sakkis at gmail.com Thu Jun 5 09:41:32 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 5 Jun 2008 06:41:32 -0700 (PDT) Subject: Tuples part 2 References: <295215b0-83b4-46a7-ac94-ed94be57ccad@27g2000hsf.googlegroups.com> Message-ID: <0d3f0f2b-f345-44f9-adb3-6fbed603cce9@d1g2000hsg.googlegroups.com> On Jun 5, 9:26 am, "victor.hera... at gmail.com" wrote: > On Jun 5, 1:37 am, bearophileH... at lycos.com wrote: > > > > > victor.hera... at gmail.com: > > > Do you mean something like this? (notice the many formatting > > differences, use a formatting similar to this one in your code) > > > coords = [] > > > for i in xrange(1, 5): > > for j in xrange(1, 5): > > for k in xrange(1, 2): > > coords.append( (i, j, k) ) > > > coords *= 10 > > print coords > > > Bye, > > bearophile > > Hi, > > the result i would like is similar to a set of n tuples: tuple_1, > tuple_2,...,tuple_n. I use h in order to enumerate the tuples and > i,j,k would be the coordinates. >From the pseudocode you wrote at first, tuple_1, tuple_2, ..., tuple_n would be all equal. Is this intentional, and if so, what's the purpose ? George From apardon at forel.vub.ac.be Mon Jun 2 05:00:08 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 2 Jun 2008 09:00:08 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> Message-ID: On 2008-05-24, Ben Finney wrote: > Sh4wn writes: > >> first, python is one of my fav languages, and i'll definitely keep >> developing with it. But, there's 1 one thing what I -really- miss: >> data hiding. I know member vars are private when you prefix them with >> 2 underscores, but I hate prefixing my vars, I'd rather add a keyword >> before it. > > From whom are you trying to hide your attributes? > > In Python, the philosophy "we're all consenting adults here" applies. > You shouldn't pretend to know, at the time you write it, all the uses > to which your code will be put. Barriers such as enforced "private" > attributes will only cause resentment when people, despite your > anticipations, *need* to access them and are then forced to hack their > way around them. I don't find this argument very compelling. You can't anticipate all functionality people would like your function to have. Acces to information in a (private) attribute is just one of those possible functionallities. People will resent you if you don't provide functionality they think fits logically in your package. > If you want the users of your code to know that an attribute should > not be used as a public API for the code, use the convention of naming > the attribute with a single leading underscore. This is a string > signal that the attribute is part of the implementation, not the > interface. The reader is then on notice that they should not rely on > that attribute; but they are not *prohibited* from using it if > necessary to their ends. But they will resent you just as much if you decide to rewrite your module in such a way that the attribute is no longer present or is used now in a slightly different way, so that it break code. -- Antoon Pardon From none at this.time Fri Jun 6 13:51:14 2008 From: none at this.time (The Pythonista) Date: Fri, 06 Jun 2008 13:51:14 -0400 Subject: Assigning to __class__ : bad form? Message-ID: <61f33$48497912$7402@news.teranews.com> I've been wondering for a while about whether assigning to __class__ is bad form or not. Specifically, I mean doing so when some other method of implementing the functionality you're after is available (i.e. using an adapter, or something like the strategy pattern). To give an example and a non-example of what I'm talking about, consider the following recipes from the online Python Cookbook: Ring Buffer: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68429 In this case, I think the assignment to __class__ just obfuscates things, and the example would be better coded as a single class. On the other hand, Fast copy of an object having a slow __init__ : http:// aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66507 This seems like a reasonable use case for assigning to __class__ (except that it's already implemented in the 'new' module, but, read the Martelli- bot's comments near the end of the recipe). I consider this a reasonable use case for assigning to __class__, because, short of the 'new' module, I don't see any other way to accomplish it. So, what is the opinion of the broader Python community? Is code that assigns to __class__ just clever trickiness to be avoided, or is it sometimes a good thing? -- code.py: A blog about life, the universe, and Python http://pythonista.wordpress.com ** Posted from http://www.teranews.com ** From nospam at nospam.com Sun Jun 1 09:28:27 2008 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 01 Jun 2008 15:28:27 +0200 Subject: Good grid + calendar, etc.? References: <9c80b15f-791e-4933-984b-fd8bf0bafef1@m36g2000hse.googlegroups.com> Message-ID: On Sun, 1 Jun 2008 06:00:03 -0700 (PDT), Mike Driscoll wrote: >I recall that there is an advanced calendar widget that's been made by >one of the regulars on the wxPython list, but it's not a part of the >official distribution at this time. You'll have to ask about calendar >widgets and such there though. The impression I get, is that those extra widgets (besides the usual edit, listbox, etc.) aren't really developped/maintained, which is a problem when comitting for applications that will have to be developped for a few years. For instance, is there a calendar in wxPython that has this look and feel, and is under active development? http://www.devexpress.com/Products/VCL/ExScheduler/ >The grid can be quite advanced. Did you look at the wxPython demo? Or >Dabo? Yes, but although the basic wigets are just fine, wxGrid looks a bit like the basic TStringGrid in Delphi, ie. it's pretty basic so that several vendors came up with enhanced alternatives. But maybe I haven't played with it long enough. www.asiplease.net/computing/delphi/images/string_grid_demo_popstars.gif It lacks sorting capability, merging cells with the same content, etc. From bronger at physik.rwth-aachen.de Sun Jun 15 11:47:31 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 15 Jun 2008 17:47:31 +0200 Subject: Making wxPython a standard module? References: <6bidd7F3bg8usU1@mid.uni-berlin.de> <87fxrfx0h0.fsf@physik.rwth-aachen.de> <87wskrvhwd.fsf@physik.rwth-aachen.de> <87skvfvd0b.fsf@physik.rwth-aachen.de> <3L-dnZvBzrFZh8jVnZ2dnUVZ_uudnZ2d@posted.visi> Message-ID: <87d4miwvho.fsf@physik.rwth-aachen.de> Hall?chen! Grant Edwards writes: > On 2008-06-14, Torsten Bronger wrote: > >>> You're saying that having the user or-together a bunch of >>> bitmasks and pass the result as an integer is a common way for >>> Python functions/object allow the user to turn optional features >>> on and off? >> >> "Common" doesn't matter. > > Yes it does. "Common in Python" is what defines "Pythonic". Then I have your definition of it. I don't think that it leads to good design, though. In case of doubt, choose what's common in Python, but other characteristics must have higher priority. >> Legibility and practicality matter. > > [...] With a little practice and care, functional programming in > prefix-notation (a-la Scheme) can both practical and legible, Not legible for a Python-only programmer like me, and I am the target audience. > but it still isn't Pythonic. > > [...] > >>> They are sources of bugs. >> >> I don't think so. What do you mean? > > Because certain flags are only to be used in certain contexts, but > there's no way to force (or even to indicate) that usage to the > user. Related flags are orthogonal so that the library can well detect an error. Okay, you can pass a *very* wrong parameter, like telling wxPython that this event should have an OK button, but I find this problem case artificial. > [...] > >> I used to use C++ before I switched to Python, but I don't see >> any C++ in wxPython. > > The whole "flags" thing with a truckload of globally defined > integer constants competing for a single namespace is pure C/C++. > Were wxWidgets written in Python, I guarantee that wouldn't be the > way it was done. Well, of course it would look heavily different with a different history but this applies to every piece of software. As I said, I used flags in my own package, designed with Python 2.4. And I consider myself a purist. So, there are things that are bad or sub-optimal, but flags are a matter of personal preference. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From badmuthahubbard at gmail.com Sun Jun 8 02:28:14 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Sun, 8 Jun 2008 09:28:14 +0300 Subject: More than one element of list changing when only one should be In-Reply-To: <8200bab70806070753y69652e74v73a280cfacb23af2@mail.gmail.com> References: <8200bab70806070753y69652e74v73a280cfacb23af2@mail.gmail.com> Message-ID: <8200bab70806072328m733e0303hbae1e15ef8428370@mail.gmail.com> I solved this problem. I still don't understand why, but it seems Python was appending a reference to the first element at the end of the list, rather than copying the data. I used something like: "self.regionlist.append(list(self.regionlist[self.hregion])" and now it works fine, i.e., altering the appended list member doesn't change the copied one. -Chuckk On Sat, Jun 7, 2008 at 5:53 PM, Chuckk Hubbard wrote: > Hello. > This program is clunky, I know; I'm not a programmer, but I need to > use this program, so I'm writing it. > The problem: > I have a cursor following the mouse that shows frequency ratios of > potential notes in relation to 1/1 (something like Middle C). At any > time, the user may hit "t" to move 1/1 to wherever the cursor is. > There is also the option to use many regions, so that some of the > notes in the score, in region 0, for instance, can have 1/1 as their > base, and others, in region 1 for instance, could have perhaps 3/2 as > their base. > > The program starts out with 2 existing regions, region 0 = 1/1, and > region 1 = 3/2. If the user hits r+NUM, the cursor switches to region > NUM. If NUM is longer than the list of regions (self.regionlist), a > new region is appended with the same base as the current one, and the > cursor goes to that region. > > SO, if you start this program, then: > 1) move the cursor around a little; > 2) hit 'r' and '1' at the same time - now you are in region 1; > 3) hit 'r' and '0', now region 0; > 4) hit 'r' and '2', now a new region 2 is created with the same > parameters as region 0, and self.regionlist is appended with the new > info - now you're in region 2; > 5) move the mouse until the fraction reads anything other than 1/1; > 6) hit 't' to transpose the current region by that fraction; > > You can see by the output in the text window that self.regionlist[0] > AND self.regionlist[2] have been updated. Only [2] should have been > changed. > > 7) hit 'r' and '0', and see that region 0 has now changed its base to > match region 2. > > I hope someone is curious enough to get through this and help me. I > tried extracting the function in question into its own mini-file and > the problem didn't happen. I can't think of any reason these lines: > > self.regionlist[self.hregion][0] = self.curnum > self.regionlist[self.hregion][1] = self.curden > self.regionlist[self.hregion][3] = self.octave11 = self.yadj > > should change self.regionlist[0] AND self.regionlist[2] in the same > call, but they do. Also, if I add more regions in series, they all > update each other. > > Thanks for your time. > > -Chuckk > > -- > http://www.badmuthahubbard.com > -- http://www.badmuthahubbard.com From johnjsal at NOSPAMgmail.com Wed Jun 18 09:59:27 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 18 Jun 2008 09:59:27 -0400 Subject: One more socket programming question References: <4858772c$0$5015$607ed4bc@cv.net> Message-ID: <4859145f$0$28604$c3e8da3@news.astraweb.com> "Tim Roberts" wrote in message news:sjdh541b2u7m789i8ef6rmple5smklbt9i at 4ax.com... > John Salerno wrote: >> >>I'm now experimenting with the SocketServer class. Originally I >>subclassed the StreamRequestHandler to make my own custom handler, but a >>result of this seems to be that the client socket closes after it has >>been used, instead of staying open. > > Right. "handle" is not called for one REQUEST at a time, it's called for > one CONNECTION at a time. If you need a connection to be persistent, then > your handle() function needs to sit in a loop making recv calls until you > detect that the conversation is complete. Ah, so I need to rewrite my handle method. I was thinking that the specialized setup() and/or finish() calls from StreamRequestHandler were the reason that the connection was closed after one use (which is why I tried BaseRequestHandler instead). Thanks. From sturlamolden at yahoo.no Thu Jun 5 06:15:21 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 5 Jun 2008 03:15:21 -0700 (PDT) Subject: multiprocessing module (PEP 371) References: <877a5774-d3cc-49d3-bb64-5cab8505a419@m3g2000hsc.googlegroups.com> Message-ID: <1c867dff-a909-4b9e-99ec-b096ddfbd83d@c58g2000hsc.googlegroups.com> On Jun 5, 11:02 am, pataphor wrote: > This is probably not very central to the main intention of your post, > but I see a terminology problem coming up here. It is possible for > python objects to share a reference to some other object. This has > nothing to do with threads or processes, although it can be used as a > *mechanism* for threads and processes to share data. It is complicated in the case of processes, because the object must be kept in shared memory. The complicating factor is that the base address of the memory mapping, which is not guaranteed to be the same in the virtual address space of different processes. From Lie.1296 at gmail.com Sun Jun 15 13:22:13 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 15 Jun 2008 10:22:13 -0700 (PDT) Subject: Creating a TCP/IP connection on already-networked computers References: <4853f269$0$11615$607ed4bc@cv.net> Message-ID: <73ea41f5-2723-48d4-8a52-9ece0260ba5c@u12g2000prd.googlegroups.com> On Jun 14, 11:31?pm, John Salerno wrote: > Let me see if this question even makes sense...I'm reading Core Python > Programming and I jumped ahead to the more specific topics like network > programming. I plan to follow along with the example in that chapter and > create a socket connection between my desktop and laptop. > > However, these two computers are already connected on my home network > (using the Windows Network Setup Wizard), so I was wondering if this > will have any effect on what I might try to do with Python. In other > words, if the program I write actually works and allows the two > computers to speak to each other, will that be a result purely of the > program, or will it have anything to do with the fact that they are > already on a home network together? (i.e. there's another variable in play?) > > Thanks. The Windows Network Wizard is a poor abstraction to set up layer 3 and 4 (the TCP/IP and lower) and layer 5 (the file sharing). You don't need to run this wizard if you've set up your TCP/IP and lower correctly manually (which, according to me, is easier than using the wizard). In a normal situation, you shouldn't need to worry about setting up the layer 3 and 4, you can assume that this two already set up. Some problem lies when connecting two computers through internet, such as you may have to use external IP address or set up port forwarding on the server-side. This is due to the use of 192.168.xxx.xxx as inside-LAN IP address instead of letting each device on the whole world has their own IP address. From schickb at gmail.com Wed Jun 25 03:11:54 2008 From: schickb at gmail.com (schickb) Date: Wed, 25 Jun 2008 00:11:54 -0700 (PDT) Subject: Sequence iterators with __index__ References: <433c6aca-745e-4c9f-b182-d76291449829@m73g2000hsh.googlegroups.com> <119bb268-2064-4128-8006-f5564f0c62f8@q27g2000prf.googlegroups.com> Message-ID: <996af953-f2a5-4dc5-ac9d-f98067cacbf7@l42g2000hsc.googlegroups.com> On Jun 24, 5:46 pm, Terry Reedy wrote: > > Wanting to slice while iterating is a *very* specialized usage. I disagree because iterators mark positions, which for sequences are just offsets. And slicing is all about offsets. Here is a quote from the already implemented PEP 357: "Currently integers and long integers play a special role in slicing in that they are the only objects allowed in slice syntax. In other words, if X is an object implementing the sequence protocol, then X[obj1:obj2] is only valid if obj1 and obj2 are both integers or long integers. There is no way for obj1 and obj2 to tell Python that they could be reasonably used as indexes into a sequence. This is an unnecessary limitation." But this isn't just about slicing. I'd like sequence iterators to be usable as simple indexes as well; like a[it] (which __index__ would also provide). > In any case: > A. If the iterator uses in incrementing index to iterate, you want access. > B. Using an iterator as an integer will strike most people as > conceptually bizarre; it will never be accepted. It's not meant to be used as an integer. It's meant to be used as a position in the sequence, which iterators already are. The fact that the position is represented as an integer is not that important (except to python). I'll grant you that it is conceptually strange that you could use an iterator on one sequence as an index into another. > C. Doing so is unnecessary since the internal index can just as easily > be exposed as an integer attribute called 'index' or, more generally, > 'count'. > a[it.count:] looks *much* better. > D. You can easily add .index or .count to any iterator you write. The > iterator protocol is a minimum rather than maximum specification. Following that line of reasoning, the __index__ special method shouldn't really exist at all. Your arguments would suggest that NumPy shouldn't use __index__ either because: a[ushort.index] "looks *much* better". > E. You can easily wrap any iterable/iterator in an iterator class that > provides .count for *any* iteration process. Sure, and that is why I mentioned this in my original post. But the idea is to avoid redundant code and data in the case of sequences, and make it a standard feature. > F. Even this should be unnecessary for most usages. Built-in function > enumerate(iterable) generates count,item pairs in much the same manner: I am not aware of a way to get the current position out of an enumerate object without advancing it (or creating a custom wrapper). If the special __index__ method was added it might be interesting ;) But iterators are already a clean and abstract position marker, and for sequences it seems surprising to me that they can't really be used as such. -Brad From Lie.1296 at gmail.com Thu Jun 19 06:12:25 2008 From: Lie.1296 at gmail.com (Lie) Date: Thu, 19 Jun 2008 03:12:25 -0700 (PDT) Subject: how to send a "Multiline" mail with smtplib? References: Message-ID: <72daf82c-1921-4aba-b41a-3bf13d3f0e51@s21g2000prm.googlegroups.com> On Jun 19, 4:02?pm, Justin Ezequiel wrote: > perhaps change html > > body=MIMEText('hello,\r\n > ok',_subtype='html',_charset='windows-1255') > > to plain > > body=MIMEText('hello,\r\n > ok',_subtype='plain',_charset='windows-1255') If that was the case, and you needed a line break in html-mode, use
or

tags. From larry at portcommodore.com Sun Jun 29 11:16:20 2008 From: larry at portcommodore.com (larry at portcommodore.com) Date: Sun, 29 Jun 2008 08:16:20 -0700 (PDT) Subject: help debugging noob code - converting binary data to images... References: <56955a42-155c-4c37-9bf6-5a99cadb5c79@l42g2000hsc.googlegroups.com> Message-ID: <8a9b4e80-45cf-4145-85c0-94d2f2a04aa4@j22g2000hsf.googlegroups.com> Wonderful, thank you! Will try them out this evening. The image module syntax looks more like what I was expecting than TKinter. All the online drawing examples I found yesterday used TKinter; image was only shown to manipulate pre-made images. Larry From python at rcn.com Mon Jun 16 13:25:21 2008 From: python at rcn.com (Raymond Hettinger) Date: Mon, 16 Jun 2008 10:25:21 -0700 (PDT) Subject: 'string'.strip(chars)-like function that removes from the middle? References: Message-ID: On Jun 16, 10:09?am, Peter Otten <__pete... at web.de> wrote: > Ethan Furman wrote: > > The strip() method of strings works from both ends towards the middle. > > Is there a simple, built-in way to remove several characters from a > > string no matter their location? (besides .replace() ;) > >>> identity = "".join(map(chr, range(256))) > >>> 'www.example.com'.translate(identity, 'cmowz.') > > 'exaple' And in Py2.6, you'll be able to simplify further: >>> 'abcde'.translate(None, 'bd') 'ace' Raymond From pavlovevidence at gmail.com Sun Jun 1 10:05:23 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 1 Jun 2008 07:05:23 -0700 (PDT) Subject: python's setuptools (eggs) vs ruby's gems survey/discussion References: <71ff8ebc-96e6-40f8-bcf2-43a0a2bd4135@w7g2000hsa.googlegroups.com> Message-ID: <78f01f07-c300-48f7-b5a0-8f3fa7e75e1d@z72g2000hsb.googlegroups.com> On Jun 1, 4:47 am, Alia Khouri wrote: > Can we open up the discussion here about how to improve setuptools > which has become the de facto standard for distributing / installing > python software. I've been playing around with ruby's gems which seems > to be more more mature and usable. > > From my perspective, the relative immaturity of setuptools and its > simultaneous widespread use is a clear python weakness and can make > python less easy to absorb than it should be. > > A few questions (please add more) so far are: Oh boy. > (1) Should setuptools be standard? Shamelessly speaking as someone who does no wish to enter this particular niche of Python: I would hope the Python community can do better. > (2) What bugs you most about the current featureset? 1. setuptools will download and install dependencies on the user's behalf, without asking, by default. It can be disabled, but I think it's extremely rude: it should ask by default. 2. One cannot simply import modules from packages that use entry_points: you have to go through package resources. Very annoying. 3. Tools such as py2exe don't work with packages that use entry_points except with some hand tweaks (at least as of the last time I tried). One might suggest that py2exe should learn how to include setuptools models, but I don't think people who write tools like py2exe ought to be burdened with it. py2exe was possible because the import mechanism was theretofore so straightforward. FWIW, I've abandoned usage of a package that used entry points because of this issue. > (3) Which features do you need the most (list in order of need)? Not that my needs are all important, but: 1. Works. 2. Ability to install to unusual locations (BIG) 3. Packages can be installed separately by hand if the user so desires (copying to site directory, hand editing if necessary) 4. Ability to easily specify compiler options when rebuilding extension modules. 5. Handles data files reasonably > (4) Shouldn't we just port gems to python? Fine with me, some new blood would be useful here. > (5) What's the best community process to improve setuptools? Have the BDFL declare that it's the official Python package manager. Of course, I hope if it ever comes to that the BDFL will pronounce something else to be the official Python package manager, preferrably something that isn't based on distutils. > Hope this discussion can be constructive. In any case, I do appreciate > the effort that went into creating setuptools (Thanks Phillip J. > Eby :-). It's existence is clearly better than otherwise. I don't agree. It's probably better than otherwise for enterprise applications, which is the environment for which it was designed. For instance, entry points and dependency bookkeeping are useful in such environments, since there are policies to ensure consistent and reasonable usage. For open source, mom-and-pop operations, and other smaller projects, I think it adds a whole lot of complexity over what otherwise is a simple thing. Carl Banks From mensanator at aol.com Sat Jun 7 21:03:09 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 7 Jun 2008 18:03:09 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> <484ad07b$0$25721$607ed4bc@cv.net> Message-ID: <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> On Jun 7, 6:43?pm, "Terry Reedy" wrote: > "John Salerno" wrote in message > > news:484ad07b$0$25721$607ed4bc at cv.net...| Mensanator wrote: > > | > | > Surely enumerate() wasn't added to Python with no intention of > | > ever being used. > | > | I see your reasons for preferring enumerate over zip, but I'm wondering > | if using enumerate this way isn't a little hackish or artificial. > > It seems to be a difference of personal preference. ?I see no reason to > write a for loop (statement or expression) when a simple usage of basic > builtins does the same. ?Mensanator apparently does. ? *sigh* I never said a for..loop was preferable. What I said was the answer to "Can I do this with a list comprehension?" I never said you shouldn't use the builtins. What I DID say was that how the builtins actually work should be understood and it APPEARED that the OP didn't understand that. Maybe he understood that all along but his example betrayed no evidence of that understanding. > So it goes. So I was trying to help the guy out. So sue me. > > Because zip stops when the first iterator is exhausted, the original zip > with range can be pretty well future proofed with a high stop value. > > zip(range(9,2000000000), iterable) Oh, dear. You didn't actually try this, did you? > > Of course, a non-1 step can be added to the range. I would hope so, otherwise you're going to have a problem creating a list with two billion integers. You might want to try xrange() in your production code. > > tjr From socyl at 987jk.com.invalid Fri Jun 13 13:54:32 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 13 Jun 2008 17:54:32 +0000 (UTC) Subject: How to sort very large arrays? Message-ID: I'm downloading some very large tables from a remote site. I want to sort these tables in a particular way before saving them to disk. In the past I found that the most efficient way to do this was to piggy-back on Unix's highly optimized sort command. So, from within a Perl script, I'd create a pipe handle through sort and then just print the data through that handle: open my $out, "|$sort -t '\t' -k1,1 -k2,2 -u > $out_file" or die $!; print $out $_ for @data; But that's distinctly Perlish, and I'm wondering what's the "Python Way" to do this. TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From sjmachin at lexicon.net Sun Jun 8 19:31:48 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 8 Jun 2008 16:31:48 -0700 (PDT) Subject: Q re documentation Python style References: Message-ID: <71beb475-7602-462a-af9f-f22c79ee2347@x19g2000prg.googlegroups.com> On Jun 9, 7:17 am, kj wrote: [snip] > For example, I want to document a function that > takes a dictionary as argument, and this dictionary is expected to > have 5 keys. (When the number of mandatory arguments gets above > 4, I find that it's too difficult to remember their order, so I > resort to using a dictionary as the single argument.) Like myfunc({'strarg': 'foo', 'intarg': 42}) ?? So the start of this function would look something like this: def myfunc(dictarg): strarg = dictarg['strarg'] intarg = dictarg['intarg'] # the real work starts now Why not use keyword args? >>> def func(a1, a2): ... print 'a1=%r a2=%r' % (a1, a2) ... >>> func('foo', 42) a1='foo' a2=42 >>> func(a1='foo', a2=42) a1='foo' a2=42 >>> func(a2=42, a1='foo') a1='foo' a2=42 >>> Have you read this section in the Python tutorial: "4.7 More on Defining Functions" (http://docs.python.org/tut/ node6.html#SECTION006700000000000000000) HTH, John From gert.cuykens at gmail.com Sat Jun 28 18:38:27 2008 From: gert.cuykens at gmail.com (gert) Date: Sat, 28 Jun 2008 15:38:27 -0700 (PDT) Subject: pxssh submit su commands = very very slow Message-ID: <39f89067-8ee6-470a-92ce-77b46a344f37@34g2000hsf.googlegroups.com> This works but after the su command you have to wait like 2 minutes before each command gets executed ? What did i do wrong ? import pxssh try: s = pxssh.pxssh() s.login ('127.0.0.1', 'gert', '123') s.sendline ('uptime') s.prompt() print s.before s.sendline ('ls -l') s.prompt() print s.before s.sendline ('df') s.prompt() print s.before s.sendline ('su') s.expect('Password:') s.sendline ('123') s.prompt() print s.before s.sendline ('df') s.prompt() print s.before s.sendline ('exit') s.logout() except pxssh.ExceptionPxssh, e: print "pxssh failed on login." print str(e) From tjreedy at udel.edu Wed Jun 25 19:26:00 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 25 Jun 2008 19:26:00 -0400 Subject: Newbie question about tuples and list comprehensions In-Reply-To: References: Message-ID: idiolect wrote: > Hi all - Sorry to plague you with another newbie question from a > lurker. Hopefully, this will be simple. > > I have a list full of RGB pixel values read from an image. I want to > test each RGB band value per pixel, and set it to something else if it > meets or falls below a certain threshold - i.e., a Red value of 0 > would be changed to 50. > > I've built my list by using a Python Image Library statement akin to > the following: > > data = list(image.getdata()) > > Which produces a very long list that looks like [(0,150,175), > (50,175,225),...]. I'm trying to figure out a fast and pythonic way > to perform my operation. The closest I've come so far to a succinct > statement is a list comprehension along the syntax of: Why are you trying to do this with a list comprehension? Learn the basics first. Perhaps you have read too many of the recent threads presenting diverting challenges for bored experienced programmers. Some of these were definitely not Pythonic code for real use. First question: do you really want to create a new 'very long list' or modify list 'data' in place. Let's assume the latter. for i,tup in enumerate(data): data[i] = replace(tup) where replace(tup) is an expression or function that produces a tuple meeting your criteria. Simplest is (max(tup[0],Rthresh), max(tup[1],Gthresh), max(tup[2],Bthresh)). If nearly all your pixels are ok, add the following before the assignment so you only make replacements when actually needed: if tup[0] < Rthresh or tup[1] < Gthresh or tup[2] < Bthresh: Terry Jan Reedy From kyrie at uh.cu Sun Jun 8 12:00:15 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Sun, 08 Jun 2008 12:00:15 -0400 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> Message-ID: <1212940815.484c020fa98ef@comuh.uh.cu> I don't know about Erlang (though I'd think it's behaviour sould be similar to prolog), but at least in Prolog, yes, _ and _ are different variables. The whole idea of "_" is that it is a placeholder that can bind to anything, but will be immediately discarded. It's just syntactic sugar so you don't have to create new names for things you don't care about, which could be a problem in prolog (once bound, cannot be bound again on the same branch) or erlang (once bound, bound forever). I just tried on erlang: f(0,_) -> 1+_; f(X,_) -> X*f(X-1,_). produces an error: ./t.erl:4: variable '_' is unbound ./t.erl:5: variable '_' is unbound (referring to the right side uses of the _ symbol) while the definition: f(0,Y)->1+Y; f(X,Y)->X*f(X-1,Y). produces a [very weird, just for testing purposes, don't use it at home] version of 'factorial'. So, you understood well. As I haven't been following this thread, I won't go offtopic talking about functional languages. But yes, on functional (and declarative?) languages, it makes a lot of sense to have a 'symbol' that represents a new variable any time you use it. Cheers, -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie Quoting Roy Smith : > In article , > Mark Wooding wrote: > > > * Prolog and Erlang distinguish atoms from variables by the case of > > the first letter; also `_' is magical and is equivalent to a new > > variable name every time you use it. > > Can you explain that in more detail? A literal reading of what you wrote > would mean that if you did (assuming this is even legal syntax): > > _ = 1; > y = _; > > the _'s are different variables, which is absurd enough to make me believe > I just misunderstood you. > -- > http://mail.python.org/mailman/listinfo/python-list > From jaywgraves at gmail.com Mon Jun 2 17:56:08 2008 From: jaywgraves at gmail.com (jay graves) Date: Mon, 2 Jun 2008 14:56:08 -0700 (PDT) Subject: Cast list of objects to list of strings References: <48546eb1-11f3-4a88-b1ac-97bd485a1823@k30g2000hse.googlegroups.com> Message-ID: <63d3d50d-0e9b-4682-b523-c2ff7d336c6a@m44g2000hsc.googlegroups.com> On Jun 2, 4:02 pm, Larry Bates wrote: > I think what you want is: > def write_err(*args): > from sys import stderr > stderr.write("\n".join([str(o) for o in args])) Slight nitpick. If you are using version >= 2.4 you could use a generator expression instead of a list comprehension to avoid building and throwing away a list. "\n".join(str(o) for o in args) http://www.python.org/dev/peps/pep-0289/ Very unlikely to yield a material time difference in this case but cleaner IMO. ... Jay Graves From michele.simionato at gmail.com Tue Jun 3 09:25:17 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 3 Jun 2008 06:25:17 -0700 (PDT) Subject: Webpy vs Django? References: <7db4dfb2-1e50-4a89-a47b-7356119b2741@r66g2000hsg.googlegroups.com> Message-ID: <33f44e6c-d08b-45f6-9512-2fd3d3ddac9b@m36g2000hse.googlegroups.com> On Jun 3, 3:14?pm, circularf... at yahoo.se wrote: > > what do you think of webpy for big projects that need performance? A better question would be: do you need features which are in Django and not in webpy? If webpy suits your needs and you are happy with it, keep it. OTOH, if you need more than webpy, consider a bigger framework (there are many of them, Django is not your only choice). I would expect the performance of all Python framework to be roughly the same, the difference is in the learning curve and in the features, not in the performance. Michele Simionato From likunarmstrong at gmail.com Mon Jun 23 03:48:25 2008 From: likunarmstrong at gmail.com (windstorm) Date: Mon, 23 Jun 2008 00:48:25 -0700 (PDT) Subject: Learning Python in a group References: Message-ID: <1820ab03-882c-4629-843c-ea9d6175d253@x19g2000prg.googlegroups.com> On Jun 23, 1:12?pm, Mensanator wrote: > On Jun 22, 5:43?am, "Jonathan Roberts" > wrote: > > > > > Hi all, > > > I'm looking to learn Python (as my first programming language) and I'm > > pretty sure I'd be more successful doing this with a group of other > > people. > > > I've currently got one other person to learn with me, and we plan to > > work remotely over the net using tools such as IM/VoiP/Gobby/WIkis > > etc. We'd still like a few others to work with us, with a group of > > about 5 or 6 being seen as ideal. We'd also like to find somebody to > > act as a mentor/guide who might be happy to meet with us once every > > couple of weeks to help keep us moving in the right direction and find > > solutions to problems when we get really stuck! > > > Wondered if there was anybody here who might be interested in working > > with us in either of these roles? We both have differing goals, but > > ultimately we'd just like to get more familiar so that we can provide > > some simple fixes to packages we maintain/scratch a few itches of our > > own. Any one is welcome, no matter what your own aim :) > > > Would love to hear feedback, especially from anyone who's interested > > in working with us... > > Have you considered creating your own Google Group? > > > > > Best, > > > Jon > > Yeah, set up your personal Google group, post the address here and ask people who want to join in sounds like a better idea rather than asking here. Considering time-zone, I don't know how you guys communicate with each other "real-time". So "post in group, get discuss and reply" may make more sense. From wuwei23 at gmail.com Thu Jun 5 12:43:14 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 5 Jun 2008 09:43:14 -0700 (PDT) Subject: Import text file References: <832784cb-08b0-46df-bf78-84051e27d498@k13g2000hse.googlegroups.com> Message-ID: <260fc576-11f1-473c-bc4f-a63873a21719@s21g2000prm.googlegroups.com> On Jun 6, 2:28 am, Franck Y wrote: > I have a text file where there is > > xxx=value > yyy=value > zzz=value > etc... > > I would like use the from myfile import xxxx > > Since it has not the extension py how can i read it ? > I know the way to do it with the open file but i think this one is > easier... I don't think you'll be able to use import unless you change the file extension to .py If you're in control of the text file and are confident it will only contain name=value pairs, try: execfile('your_file.txt') From gagsl-py2 at yahoo.com.ar Wed Jun 18 03:02:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Jun 2008 04:02:04 -0300 Subject: Buffer size when receiving data through a socket? References: <20080616202135.41c407de.johnjsal@NOSPAMgmail.com> <4857f4f7$0$28588$c3e8da3@news.astraweb.com> Message-ID: En Tue, 17 Jun 2008 14:32:44 -0300, John Salerno escribi?: > "Gabriel Genellina" wrote in message > news:mailman.547.1213684963.1044.python-list at python.org... >> Note that most of the time you want to use the sendall() method, because >> send() doesn't guarantee that all the data was actually sent. >> > > If I use sendall(), am I still recv'ing data with a given buffer size? What > if I send more data than the buffer size. Is my code as written not prepared > to handle that case? It seems like I might need to continue receiving data > until there is no more to receive (in a loop?)...is that right? send and recv are separate calls (they occur usually in different processes, even in different computers). Buffer sizes are separate too. It is posible to send 5K at once from one side, and require three recv calls on the other side to read it completely. On the other hand, if you try to read from a blocking socket (the default state) when no data is available, the read call will block (and the whole program freezes) until some data is received. There are several alternatives to avoid this, and surely they're explained in detail in a later chapter in your book... -- Gabriel Genellina From hniksic at xemacs.org Thu Jun 12 04:19:16 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 12 Jun 2008 10:19:16 +0200 Subject: ClassName.attribute vs self.__class__.attribute References: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> Message-ID: <87abhrdq0r.fsf@mulj.homelinux.net> Mike Orr writes: > There's a very good reason to use self.__class__: it makes it > possible to subclass your class. This really depends on the usage. In the OP's use case, he wanted the subclasses to share the same lock object defined in the superclass (because of synchronization), so it would have been wrong to use self.__class__ *because* of subclassing. Also note that for new-style classes, self.__class__ can be spelled as type(self), since there is no distinction between classes and types. > It's a little annoying that if you want to print a class's name in > some unknown object, you have to use obj.__class__.__name__ if it's > an instance, and obj.__name__ if it's a class. I sometimes wish > classes had a .__class__ attribute that's the class itself, but I > can see how that would cause its own confusion (and recursion). They do, the metaclass. :-) From sri_annauni at yahoo.co.in Thu Jun 19 03:58:41 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Thu, 19 Jun 2008 13:28:41 +0530 (IST) Subject: python socket programming Message-ID: <12884.73075.qm@web7914.mail.in.yahoo.com> HI, I want?to know the different kind of exceptions may occur in client-server? socket communication and the way to handle those scenarios. 1. What does the?server do when a socket error occurs at any point: accepting a connection, sending data to a client, receiving?data from a client, waiting for a?client to shut down. ?? 2. What does the?client do when a socket error occurs at any point: connecting to the server, receiving data, sending?data. If anyone knows answer for this qns, Can?you please explain me briefly about it?? Thanks, Srini Unlimited freedom, unlimited storage. Get it now, on http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/ From george.sakkis at gmail.com Thu Jun 19 20:31:50 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 19 Jun 2008 17:31:50 -0700 (PDT) Subject: Null pattern Message-ID: I'd like to extend the Null pattern from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205 to handle special methods (e.g. Null[3], del Null['key'], Null+1) but it's not always clear how to do it while keeping the behavior consistent and intuitive. For example, consider the container methods __len__, __iter__ and __contains__. The obvious choice for a null container is an empty one. When taking __getitem__ into account though, the behaviour looks inconsistent: >>> Null[3] Null >>> len(Null) 0 Another group of methods is rich comparisons: Should Null > x be allowed and if so, what it should return ? Then again, perhaps Null is an inherently domain-specific notion and there are no general answers to such questions, in which case it doesn't make sense trying to define an all-purpose Null object. George From M8R-yfto6h at mailinator.com Tue Jun 3 03:19:11 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Tue, 3 Jun 2008 00:19:11 -0700 Subject: =?GB2312?B?UmU6IHB5dGh0b24gtffTwyBzbyC5ss/tv+Kyu8Tc16q7u7LOyv3A4NDN?= References: Message-ID: "windwiny" wrote in message news:c2600a0a-6ff4-4e3d-bfa6-2edf7869c60d at a9g2000prl.googlegroups.com... > ???python ? ctypes, ?????? ubuntu 8.04, Python 2.5.2 > (r252:60911, > May 7 2008, 15:19:09) , gcc (GCC) 4.2.3 (Ubuntu 4.2.3-2ubuntu7) > ?????? so ??? > --------------------- > #include > double myfd(double x) { return x * 2;} > float myff(float x) { return x * 3;} > int myfi(int x) { return x * 4 ;} > --------------------- > ? gcc -shared a.c -o liba.so ?????? liba.so , > ??? c ???????????????????? > ?????python ?? > --------------------- > # coding:utf-8 > import ctypes as dll > p = dll.cdll.LoadLibrary("./liba.so") p.myfd.argtypes = [dll.c_double] p.myfd.restype = dll.c_double p.myff.argtypes = [dll.c_float] p.myff.restype = dll.c_float > print p.myfi(8) # ?32,?? > try: > print p.myfd(0.3) # ?? > except: > print "except myfd()" > try: > print p.myff(0.4) # ?? > except: > print "except myff()" > --------------------- > ????? ctypes.ArgumentError: argument 1: 'exceptions.TypeError'>: > Don't know how to convert parameter 1 > > ??????? --Mark ???) From gagsl-py2 at yahoo.com.ar Tue Jun 17 20:26:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 17 Jun 2008 21:26:00 -0300 Subject: Does '!=' equivelent to 'is not' References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> <20080617120941.GE7349@dragontoe.org> Message-ID: En Tue, 17 Jun 2008 09:09:41 -0300, Derek Martin escribi?: > On Tue, Jun 17, 2008 at 04:33:03AM -0300, Gabriel Genellina wrote: >> > Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)' >> > and 'not(id(a) == id(b))' >> >> No. > > Sure it is... he said "similar"... not identical. They are not the > same, but they are similar. 'equality' and 'identity' are similar too, so the whole answer would make no sense in that case. You can't explain identity based on things that aren't identical. A fine grained question for a fine grained difference requires a fine grained answer. > Saying a flat "no" alone, without qualifying your statement is > generally interpreted as rude in English... It's kind of like how you > talk to children when they're too young to understand the explanation. > Yucky. I didn't meant to be rude at all - and I apologize to Mr. Lie. The explanation for such strong "No" was in the paragraph below it (the idea was to say: "No to this, yes to that") -- Gabriel Genellina From jazle at nospam.log.web.id Mon Jun 16 07:11:24 2008 From: jazle at nospam.log.web.id (Jaimy Azle) Date: Mon, 16 Jun 2008 18:11:24 +0700 Subject: Python GC does not work as it should be References: Message-ID: Jean-Paul Calderone wrote: > > A system exception? What's that? C doesn't have exceptions. > How could I determine it? I dont know GCC implementation, and others, but C on MSVC does have it. My application were not written in C, an exception raised was something like "access violation at address xxxx on module python25.dll", and MSVC debugger shows collecting state were not reset (1), that is why GC would never happen. Salam, -Jaimy. From gh at ghaering.de Wed Jun 11 07:38:07 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 11 Jun 2008 13:38:07 +0200 Subject: Python regex question In-Reply-To: References: Message-ID: Tim van der Leeuw wrote: > Hi, > > I'm trying to create a regular expression for matching some particular > XML strings. I want to extract the contents of a particular XML tag, > only if it follows one tag, but not follows another tag. Complicating > this, is that there can be any number of other tags in between. [...] Sounds like this would be easier to implement using Python's SAX API. Here's a short example that does something similar to what you want to achieve: import xml.sax test_str = """ """ class MyHandler(xml.sax.handler.ContentHandler): def __init__(self): xml.sax.handler.ContentHandler.__init__(self) self.ignore_next = False def startElement(self, name, attrs): if name == "ignore": self.ignore_next = True return elif name == "foo": if not self.ignore_next: # handle the element you're interested in here print "MY ELEMENT", name, "with", dict(attrs) self.ignore_next = False xml.sax.parseString(test_str, MyHandler()) In this case, this looks much clearer and easier to understand to me than regular expressions. -- Gerhard From tjreedy at udel.edu Mon Jun 16 20:13:19 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 16 Jun 2008 20:13:19 -0400 Subject: 'string'.strip(chars)-like function that removes from the middle? In-Reply-To: <200806161839.13647.omer@no-log.org> References: <48569B9E.6030206@admailinc.com> <200806161839.13647.omer@no-log.org> Message-ID: C?dric Lucantis wrote: > I don't see any string method to do that >>> 'abcde'.translate(str.maketrans('','','bcd')) 'ae' I do not claim this to be better than all the other methods, but this pair can also translate while deleting, which others cannot. From thomasmallen at gmail.com Tue Jun 3 14:44:20 2008 From: thomasmallen at gmail.com (tmallen) Date: Tue, 3 Jun 2008 11:44:20 -0700 (PDT) Subject: Picking apart strings Message-ID: <7e5b2c51-a1a0-45aa-9b53-547482747292@x41g2000hsb.googlegroups.com> Is there a way to pick apart this text without resorting to regular expressions? p { color: black; } p -> element color -> property black -> value From rw.segaar at xs4all.nl Sat Jun 14 15:27:19 2008 From: rw.segaar at xs4all.nl (Robert) Date: Sat, 14 Jun 2008 21:27:19 +0200 Subject: Configuration files Message-ID: <485419f0$0$5958$e4fe514c@dreader16.news.xs4all.nl> What is the most Pythonic way to maintain a configuration file? Are there any libraries mimicking registry / ini file writing that many windows programming languages/environments offer? Robert From fuzzyman at gmail.com Mon Jun 9 16:52:25 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 9 Jun 2008 13:52:25 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <6e6df35e-e641-44d9-9f56-c0732306eec2@q27g2000prf.googlegroups.com> Message-ID: On Jun 9, 9:20?pm, Rhamphoryncus wrote: > On Jun 9, 5:33 am, Antoon Pardon wrote: > > > > > On 2008-06-07, Rhamphoryncus wrote: > > > > On Jun 6, 12:44 pm, The Pythonista wrote: > > >> It's always been my understanding that you can't forcibly kill a thread > > >> in Python (at least not in a portable way). ?The best you can do is > > >> politely ask it to die, IIRC. > > > > Inherently, the best you can do in most languages is ask them politely > > > to die. ?Otherwise you'll leave locks and various other datastructures > > > in an inconvenient state, which is too complex to handle correctly. > > > The exception is certain functional languages, which aren't capable of > > > having threads and complex state in the same sense. > > > Well it would of course depend on what is considered asking politely? > > > If one thread could cause an exception being thrown in an other thread, > > would this be considered a polite way to ask? Would it be considered > > an acceptable way? > > The exception must not be raised until a point explicitly designed as > safe is hit. ?Otherwise, any function that manipulates data you'll > still use will potentially be buggered. ?Consider sys.stdout: codecs, > buffering, lots to go wrong. Java and .NET both have ways of killing threads. They both work by raising a 'ThreadAbort' (or similar) exception in the target thread. In early implementations they both suffered from a similar problem. You could protect locks (etc) by having a finally block that would release all resources as needed - but what happens if the thread abort exception is raised *inside* the finally block? Java responded by deprecating thread aborting. .NET responded by ensuring that a thread abort exception would never be raised inside a finally block - if that happened the exception would only be raised once the code has left the finally block. Aborting threads in .NET can be extremely useful. Politely asking a thread to die is no good if the task the thread is executing is extremely coarse grained - it may not be able to respond to the request for some time. If your code is structured correctly (performing a long running background calculation for example) then you may *know* that you can kill it without problems, but Python has no native API to do this. Michael Foord http://www.ironpythoninaction.com/ From jeffrey at fro.man Thu Jun 26 11:42:46 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 26 Jun 2008 08:42:46 -0700 Subject: automatically import modules upon interpreter invocation References: Message-ID: Daniel Fetchinson wrote: > Is there a way of making python execute the above whenever it starts > up so that I don't have to type it all the time? Create a script containing these statements, and specify its location with the PYTHONSTARTUP environment variable. Your script will run whenever python starts. Jeffrey From circularfunc at yahoo.se Fri Jun 27 22:58:40 2008 From: circularfunc at yahoo.se (defn noob) Date: Fri, 27 Jun 2008 19:58:40 -0700 (PDT) Subject: Pygame, how to show window without loop? no loop=popupand close... References: <8ecb6375-356a-4e73-be21-18ffe0f5c4f2@r66g2000hsg.googlegroups.com> Message-ID: right. im an idiot anyway. i can just draw the lines before entering the loop, problem solved... From kyosohma at gmail.com Sun Jun 1 09:00:03 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sun, 1 Jun 2008 06:00:03 -0700 (PDT) Subject: Good grid + calendar, etc.? References: Message-ID: <9c80b15f-791e-4933-984b-fd8bf0bafef1@m36g2000hse.googlegroups.com> On Jun 1, 6:59?am, Gilles Ganault wrote: > Hello > > ? ? ? ? Since Python is such a productive language, I'd really like to be > able to use it to write GUI apps for Windows, but business apps > require rich widgets like (DB)grids, calendars, etc. > > The ones available in wxWidgets looked a bit too basic compared to > what's available for eg. Delphi or .Net, and don't seem to be under > active development (lots of "1.0", "Last updated 2005", etc.) > > For instance, here's wxGrid and DevExpress' grid for Delphi:http://www.simpol.com/guiimages/wxgrid.jpghttp://community.devexpress.com/blogs/thinking/PrintingXtraPivotGridF... > > Is it hopeless, or did I overlook things? Are ?there other solutions I > should look at (FLTK, etc.)? For those of you writing business apps in > Python for Windows, how do things go as far as GUI widgets are > concerned? > > Thank you. The wxPython GUI is updated much more often than the Tkinter toolkit. I recall that there is an advanced calendar widget that's been made by one of the regulars on the wxPython list, but it's not a part of the official distribution at this time. You'll have to ask about calendar widgets and such there though. The grid can be quite advanced. Did you look at the wxPython demo? Or Dabo? Mike From victor.herasme at gmail.com Thu Jun 5 09:26:08 2008 From: victor.herasme at gmail.com (victor.herasme at gmail.com) Date: Thu, 5 Jun 2008 06:26:08 -0700 (PDT) Subject: Tuples part 2 References: <295215b0-83b4-46a7-ac94-ed94be57ccad@27g2000hsf.googlegroups.com> Message-ID: On Jun 5, 1:37 am, bearophileH... at lycos.com wrote: > victor.hera... at gmail.com: > > Do you mean something like this? (notice the many formatting > differences, use a formatting similar to this one in your code) > > coords = [] > > for i in xrange(1, 5): > for j in xrange(1, 5): > for k in xrange(1, 2): > coords.append( (i, j, k) ) > > coords *= 10 > print coords > > Bye, > bearophile Hi, the result i would like is similar to a set of n tuples: tuple_1, tuple_2,...,tuple_n. I use h in order to enumerate the tuples and i,j,k would be the coordinates. Maybe something like: tuple_1=((a,b,c),..,(n,n,n)) . . . tuple_n=((d,e,f),..,(n,n,n)) I hope u can help me with that. Victor From eliben at gmail.com Sat Jun 28 04:37:10 2008 From: eliben at gmail.com (eliben) Date: Sat, 28 Jun 2008 01:37:10 -0700 (PDT) Subject: problem compiling extensions with mingw References: <4973972a-e510-49b1-86bf-4ee4294842cd@m44g2000hsc.googlegroups.com> <73f6d268-252e-4de8-9839-4bab4c256d62@k13g2000hse.googlegroups.com> Message-ID: <43089036-0701-4311-a128-786921c2a47a@i76g2000hsf.googlegroups.com> On Jun 28, 8:20 am, John Machin wrote: > On Jun 28, 3:41 pm, eliben wrote: > > > > > On Jun 27, 3:10 pm, eliben wrote: > > > > Hello, > > > I'm trying to compile the minimal example fromhttp://en.wikibooks.org/wiki/Python_Programming/Extending_with_Cwith > > > MinGW (latest version) and Python 2.5 (latest ActiveState binary > > > install). When running the setup file, the following happens: > > > > running build > > > running build_ext > > > building 'hello' extension > > > writing build\temp.win32-2.5\Release\hello.def > > > d:\mingw\bin\gcc.exe -mno-cygwin -shared -s build > > > \temp.win32-2.5\Release\hellomo > > > dule.o build\temp.win32-2.5\Release\hello.def -LC:\Python25\libs -LC: > > > \Python25\P > > > Cbuild -lpython25 -lmsvcr71 -o build\lib.win32-2.5\hello.pyd > > > build\temp.win32-2.5\Release\hellomodule.o:hellomodule.c:(.text+0x3e): > > > undefined > > > reference to `_imp___Py_NoneStruct' > > > build\temp.win32-2.5\Release\hellomodule.o:hellomodule.c:(.text+0x46): > > > undefined > > > reference to `_imp___Py_NoneStruct' > > > collect2: ld returned 1 exit status > > > error: command 'gcc' failed with exit status 1 > > > > What's more, compiling the same extension with Visual Studio 2005 > > > (without using distutils) works fine, the extension is loaded and ran > > > successfully from Python. Any ideas about this error ? > > > > Eli > > > Problem solved:http://eli.thegreenplace.net/2008/06/28/compiling-python-extensions-w... > > libpython2?.a is now *supplied* with the official CPython distribution > fromwww.python.org. > I'm using ActiveState's distribution, because I was told that it comes with more precompiled win32 goodies out of the box. > The procedure that you followed is described in the manual:http://docs.python.org/inst/tweak-flags.html#SECTION00062200000000000... > Thanks, I didn't notice it :-) Eli From stef.mientki at gmail.com Mon Jun 30 15:05:10 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 30 Jun 2008 21:05:10 +0200 Subject: list extension ? In-Reply-To: <4868b0ba$0$17063$426a34cc@news.free.fr> References: <4868b0ba$0$17063$426a34cc@news.free.fr> Message-ID: <48692E66.4080406@gmail.com> thanks guys, > >> def __init__ ( self, value = [] ) : > > Gotcha : default argument values are eval'd only once. Also, it would > make more sense IMHO to follow the parent's class initializer's > behaviour: > > def __init__(self, *args) > >> list.__init__ ( self, value ) > > list.__init__(self, *args) > that's even better, except the call must be list.__init__ ( self, args ) cheers, Stef From ptmcg at austin.rr.com Wed Jun 11 20:25:51 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 11 Jun 2008 17:25:51 -0700 (PDT) Subject: Simple and safe evaluator References: Message-ID: On Jun 11, 3:25?pm, bvdp wrote: > Is there a simple/safe expression evaluator I can use in a python > program. I just want to pass along a string in the form "1 + 44 / 3" or > perhaps "1 + (-4.3*5)" and get a numeric result. > > I can do this with eval() but I really don't want to subject my users to > the problems with that method. > > In this use I don't need python to worry about complex numbers, > variables or anything else. Just do the math on a set of values. Would > eval() with some restricted list of permitted operators do the trick? > > I'm feeling too lazy to write/debug my own parser for this :) > > Thanks, Bob. This example ships with pyparsing, and can be extended to support built-in functions: http://pyparsing.wikispaces.com/space/showimage/fourFn.py. -- Paul From johnjsal at gmailNOSPAM.com Sat Jun 14 21:39:15 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sat, 14 Jun 2008 21:39:15 -0400 Subject: Creating a TCP/IP connection on already-networked computers In-Reply-To: References: <4853f269$0$11615$607ed4bc@cv.net> <4854123f$0$5017$607ed4bc@cv.net> <485413d0$0$4997$607ed4bc@cv.net> <485425b2$0$11631$607ed4bc@cv.net> Message-ID: <485472c9$0$11612$607ed4bc@cv.net> Dennis Lee Bieber wrote: > Is there any possibility you are confusing a Windows Workgroup or > Domain in this... (Assuming anyone still runs such) Or other Windows > convenience features to automatically detect computers in a local area > network and display them in "network neighborhood". What I have is a desktop PC connected via ethernet cable to my cable modem. I also use a router and my laptop uses a wireless connection. This alone, of course, doesn't connect the computers, AFAIK. It's just an internet connection. What I did next was go to My Network Places > Set up a home or small office network, and follow the wizard through the steps that would allow me to share files and folders between the two computers. It's possible I'm using the wrong terminology when I say this is a "home network," because all it is is the two computers being able to access each other's hard drive. From subhabrata.iisc at hotmail.com Fri Jun 27 03:23:17 2008 From: subhabrata.iisc at hotmail.com (subhabrata.iisc at hotmail.com) Date: Fri, 27 Jun 2008 00:23:17 -0700 (PDT) Subject: Question on time module References: <2c7d4ffa-496d-4a0b-8c14-628decbfd4ae@a9g2000prl.googlegroups.com> Message-ID: <389efb92-9710-46ff-bfab-a2fb525a3b5b@z24g2000prf.googlegroups.com> This problem is solved with time.gmtime subhabrata.i... at hotmail.com wrote: > Dear Members of the group, > I have one function > def sum1(n): > a1=5 > a2=6 > a3=a1+a2 > a4=a3+8 > print "The First sum is" > print a3 > print "The Second sum is" > print a4 > > Now, I want to do it in a way, a4 is calculated after a given time > interval of a3 -this is easy but if I want to check after how much > time a4 is calculated from a3 how can I do? > If any one can help it. > Best Regards, > Subhabrata. From gherron at islandtraining.com Thu Jun 5 03:41:08 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 05 Jun 2008 00:41:08 -0700 Subject: os.path.walk -- Can You Limit Directories Returned? In-Reply-To: <65971e97-09eb-4295-a090-517341a86065@e53g2000hsa.googlegroups.com> References: <65971e97-09eb-4295-a090-517341a86065@e53g2000hsa.googlegroups.com> Message-ID: <48479894.8060205@islandtraining.com> Jeff Nyman wrote: > Greetings all. > > I did some searching on this but I can't seem to find a specific > solution. I have code like this: > > ========================================= > def walker1(arg, dirname, names): > DC_List.append((dirname,'')) > > os.path.walk('\\\\vcdcflx006\\Flex\\Sites', walker1, 0) > ========================================= > > The Sites\ directory is set up like this: > > Sites\ > Baltimore > Birmingham > .... > > And so forth. Each of the city directories has directories under it as > well. The problem is that my code grabs every single directory that is > under the various city directories when what I really want it to do is > just grab the directories that are under Sites\ and that's it. I don't > want it to recurse down into the sub-directories of the cities. > > Is there a way to do this? Or is os.path.walk not by best choice here? > Yes. But first, use the more modern iterator os.walk instead of the older function calling os.path.walk. Then in either case (or at least for the os.walk -- I'm a little rusty on the older os.path.walk) you can modify in-place the subdirectory listing that was passed to you, thereby controlling which subdirectories the walk follows. Here's some examples: for path, dirs, files in os.walk(root): if 'etc' in dirs: dirs.remove('etc') # Skip any directory named 'etc' if path == 'whatever': del dirs[:] # Clearing dirs means recurse into NO subdirectory of path ... process the files of directory path... Gary Herron > Any help and/or advice would be appreciated. > > - Jeff > -- > http://mail.python.org/mailman/listinfo/python-list > From goldnery at gmail.com Tue Jun 17 12:45:36 2008 From: goldnery at gmail.com (Gandalf) Date: Tue, 17 Jun 2008 09:45:36 -0700 (PDT) Subject: text alignment References: <39d1c620-9923-46e7-999d-ed86c8b465ff@34g2000hsh.googlegroups.com> Message-ID: On Jun 17, 6:43?pm, Gandalf wrote: > Hi every one. What is the similar python WX style property for CSS > text-align? > > I need this item text to start from the right direction: > > aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60)) > ? ? ? ? aaa.LoadPage('../../aa.html') > > Thanks! *right to the left direction... And I'm using pythin 2.5 on XP (I forget to mention...) From haraldarminmassa at gmail.com Tue Jun 10 16:36:47 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Tue, 10 Jun 2008 13:36:47 -0700 (PDT) Subject: Instructions on how to build py2exe 0.6.8 (or an installer would be nice, too!) References: <5426baaf-2ba6-41b0-a0ec-1070429b5195@x35g2000hsb.googlegroups.com> Message-ID: <5eddd91e-e3c5-4bd6-8aa6-77223b7cdf82@a70g2000hsh.googlegroups.com> Evan, > I hear this problem is fixed in 0.6.8, but unfortunately there's no > standalone installer for py2exe 0.6.8 - the most recent version that Maybe you can solve your problem via updating the build_exe.py after installing py2exe 0.6.6 So: a) use the 0.6.6 installer b) update the build_exe.py from 0.6.8 Possible? Best wishes, Harald From rossgk at gmail.com Thu Jun 5 11:42:44 2008 From: rossgk at gmail.com (RossGK) Date: Thu, 5 Jun 2008 08:42:44 -0700 (PDT) Subject: mod_python installer fails Message-ID: <9c92c071-cbc4-402d-9184-be9f28679dc0@x35g2000hsb.googlegroups.com> I've been running python 2.5 for a while on WinXP, working fine. I code and compile in PyDev/Eclipse. I wanted to start playing with Django, but when I go to install mod_python for Apache 2.2 I get the error: python version 2.5 required, which was not found in the registry from the installer: mod_python-3.3.1.win32-py2.5-Apache2.2.exe I've confirmed that I'm running python25, apache2.2. I thought maybe I could point to my python, but the next screen that comes up with blank locating fields takes the cursor but does not allow any text input. Does anyone know the solution to this one? Thanks Ross. From pfreixes at gmail.com Thu Jun 19 17:31:23 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Thu, 19 Jun 2008 23:31:23 +0200 Subject: [Python-Dev] C API for gc.enable() and gc.disable() In-Reply-To: References: Message-ID: <207312b70806191431g2f52af9bg53299e1e6b9ec909@mail.gmail.com> Sorry for my ignorance, gc it's garbage collector ? On Thu, Jun 19, 2008 at 11:23 PM, Alexandre Vassalotti < alexandre at peadrop.com> wrote: > On Sun, Jun 1, 2008 at 12:28 AM, Adam Olsen wrote: > > On Sat, May 31, 2008 at 10:11 PM, Alexandre Vassalotti > > wrote: > >> Would anyone mind if I did add a public C API for gc.disable() and > >> gc.enable()? I would like to use it as an optimization for the pickle > >> module (I found out that I get a good 2x speedup just by disabling the > >> GC while loading large pickles). Of course, I could simply import the > >> gc module and call the functions there, but that seems overkill to me. > >> I included the patch below for review. > > > > I'd rather see it fixed. It behaves quadratically if you load enough > > to trigger full collection a few times. > > > > Do you have any idea how this behavior could be fixed? I am not a GC > expert, but I could try to fix this. > > -- Alexandre > _______________________________________________ > Python-Dev mailing list > Python-Dev at python.org > http://mail.python.org/mailman/listinfo/python-dev > Unsubscribe: > http://mail.python.org/mailman/options/python-dev/pfreixes%40gmail.com > -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From jarausch at igpm.rwth-aachen.de Thu Jun 19 06:07:54 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Thu, 19 Jun 2008 12:07:54 +0200 Subject: Python-3.0b1 build fails on Linux : _gestalt Message-ID: <6bupftF3d2d0kU1@mid.dfncis.de> Hi, trying to build Python-3.0b1 on my Gentoo Linux box fails with Failed to find the necessary bits to build these modules: _gestalt Looking at setup.py it seems that module '_gestalt' is only needed on Darwin but my build on Linux fails nevertheless. Thanks for any hints, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From Lie.1296 at gmail.com Thu Jun 19 11:15:39 2008 From: Lie.1296 at gmail.com (Lie) Date: Thu, 19 Jun 2008 08:15:39 -0700 (PDT) Subject: Simple Python class questions References: Message-ID: <8549940b-e909-4bc6-b9a1-ea7d14284785@z16g2000prn.googlegroups.com> On Jun 19, 7:21?pm, Ulrich Eckhardt wrote: > John Dann wrote: > > Let's say I define the class in a module called comms.py. The class > > isn't really going to inherit from any other class (except presumably > > in the most primitive base-class sense, which is presumably automatic > > and implicit in using the class keyword). Let's call the class > > serial_link. So in comms.py I have: > > > class serial_link: > > ? ? def __init__(self): > > ? ? ? ? Try > > ? ? ? ? ? ? Import serial # the pyserial library > > Stop, this can't work. Other than VB, Python actually is case sensitive, so > you must write 'try' and not 'Try' and also 'import' and not 'Import'. > Further, many (all?) statements that cause an indention are usually > terminated with a colon, so like with 'class ..:' and 'def ..:' you also > must use 'try:' and not just 'try'. Fix all these and try again, I guess > this will already help a lot. > > One more thing: you are abusing exceptions. Typically, in such a short > program you only have one try-except pair in the main entry function and > all other code only throws the exceptions. In particular the __init__ > function of a class should always signal errors using exceptions. However, > this is not a strict yes/no question but rather a stylistic one. > > Uli > > -- > Sator Laser GmbH > Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 I think it's not that hard to see that it's just a pseudo code From cwitts at gmail.com Tue Jun 10 02:47:14 2008 From: cwitts at gmail.com (Chris) Date: Mon, 9 Jun 2008 23:47:14 -0700 (PDT) Subject: How to find the first space? References: <7a91cc8f-2e93-46e9-8360-a01da9170187@m44g2000hsc.googlegroups.com> Message-ID: On Jun 9, 5:02?pm, Johny wrote: > How can I find the first space using regex? > > For example I have text > Text=' This is a sample ' > > The last space I can remove by > Text=re.sub(r"\s(?!\w)",'',Text) > > but I do not know how to remove the first space. > Can anyone help? > > Thanks > L. If it's leading spaces you're worried about you can use the .lstrip() method, if you want to find the first space you can use .index(' ') to get the position of it and do with what you want. From connect2shashi at gmail.com Thu Jun 26 06:48:20 2008 From: connect2shashi at gmail.com (ShashiGowda) Date: Thu, 26 Jun 2008 03:48:20 -0700 (PDT) Subject: Urllib(1/2) how to open multiple client sockets? Message-ID: Hey there i made a script to download all images from a web site but it runs damn slow though I have a lot of bandwidth waiting to be used please tell me a way to use urllib to open many connections to the server to download many pics simultaneously.... Any off question suggestions are also ok... From asmodai at in-nomine.org Thu Jun 19 08:10:06 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 19 Jun 2008 14:10:06 +0200 Subject: Extending Python with C: Cannot find MPI library In-Reply-To: References: Message-ID: <20080619121006.GJ97799@nexus.in-nomine.org> -On [20080619 13:53], Spectrum (spectrumdt at gmail.com) wrote: > ImportError: /big/School/Cluster/Opgave03/ctest.so: undefined >symbol: ompi_mpi_comm_world > [ore at localhost Opgave03]$ > > Can anyone suggest anything? Can I get MPI to work in Python? Sounds like a typical case of not specifying any -L and/or -l options. In this case the ctest.so module has an undefined reference to the symbol ompi_mpi_comm_world and cannot resolve it. So either it was not linked properly or the loader cannot find the required library. Apply nm -D and ldd to the .so and see what ails. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B Under this standard shalt thou conquer... From kirk at daycos.com Tue Jun 17 11:14:45 2008 From: kirk at daycos.com (Kirk Strauser) Date: Tue, 17 Jun 2008 10:14:45 -0500 Subject: Pattern Matching Over Python Lists References: <21a9c996-75ff-4f7c-b7e9-c94247f65674@c58g2000hsc.googlegroups.com> Message-ID: <87ej6w6ql6.fsf@internal.daycos.com> At 2008-06-17T05:55:52Z, Chris writes: > Is anyone aware of any prior work done with searching or matching a > pattern over nested Python lists? I have this problem where I have a > list like: > > [1, 2, [1, 2, [1, 7], 9, 9], 10] > > and I'd like to search for the pattern [1, 2, ANY] so that is returns: > > [1, 2, [1, 2, [6, 7], 9, 9], 10] > [1, 2, [6, 7], 9, 9] Hint: recursion. Your general algorithm will be something like: def compare(list, function): if function(list): print list for item in list: if item is a list: compare(item, function) def check(list): if list starts with [1, 2] and length of the list > 2: return True else: return False -- Kirk Strauser The Day Companies From cwitts at gmail.com Mon Jun 2 17:40:25 2008 From: cwitts at gmail.com (Chris) Date: Mon, 2 Jun 2008 14:40:25 -0700 (PDT) Subject: Formatting Output References: <6e94b4dc-5920-447e-9971-96ec6a48b9ce@c58g2000hsc.googlegroups.com> <6ea2e85a-d00c-4228-98be-431205fceb7b@34g2000hsf.googlegroups.com> <650fca09-a6de-4d81-a19b-687c63ad429b@l64g2000hse.googlegroups.com> Message-ID: On Jun 2, 11:34?pm, Chris wrote: > On Jun 2, 9:43?pm, Doug Morse wrote: > > > > > On Mon, 2 Jun 2008 12:42:12 -0700 (PDT), Mensanator wrote: > > > ?On Jun 2, 3:38?am, Chris wrote: > > > > On Jun 2, 9:34?am, "victor.hera... at gmail.com" > > > > > wrote: > > > > > Hi, > > > > > > i am building a little script and i want to output a series of columns > > > > > more or less like this: > > > > > > 1 ?5 ?6 > > > > > 2 ?2 ?8 > > > > > 2 ?9 ?5 > > > ... > > > I have a related question: > > > Does Python have (or can emulate) the formatted output capability found in > > Perl? > > > For example, all I have to do to get nicely formatted (i.e., aligned) output > > is provide values for special STDOUT variables (i.e., STDOUT_TOP, STDOUT, > > STDOUT_BOTTOM, etc.), exemplified by: > > > ? format STDOUT_TOP = > > ? ------------------------------------------------------------------------------ > > ? ~ > > ? . > > > ? format STDOUT = > > ? @<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<< > > ? $res->{'full_name'}, ?$res->{'phone_1'}, ? ? ? ? $res->{'phone_1_type'} > > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > > ? $res->{'address_1a'}, ? ? ? ? ? ? ? ?$res->{'address_2a'} > > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > > ? $res->{'address_1b'}, ? ? ? ? ? ? ? ?$res->{'address_2b'} > > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > > ? $res->{'address_1c'}, ? ? ? ? ? ? ? ?$res->{'address_2c'} > > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > > ? $city_1 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?$city_2 > > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > > ? $res->{'email_1'}, ? ? ? ? ? ? ? ? ? $res->{'email_2'} > > ? ------------------------------------------------------------------------------ > > ? ~ > > ? . > > > Then, all I have to do is populate my $res object/hash as desired -- in this > > example simple the results of a SQL query -- and lastly just call the "write" > > function: > > > ? write; > > > and Perl will produce very nicely formatted results. ?This is useful not only > > for producing human readable output, but also fixed-column-width data files, > > etc. ?I'd love to learn the Pythonistic way of doing the same thing. > > > Thanks! > > Doug > > Can't seem to do this with dictionaries but... > > preformatted_string = """ > %s %20s %20s > %s %30s > %s %30s > """ > > print preformatted_string % ('first name'[:20], 'contact num 1'[:20], > ? ? ? ? 'contact num type'[:20], 'address line 1'[:30], 'address line > 2'[:30] > ? ? ? ? 'address line 3'[:30], 'address line 4'[:30]) > > You could do something like that. ?the "[:20]" etc @ the end of the > inputs is ofc to trim the strings to a max length. ?The string > formatter supports "%s" so > you can use that for alignment. ?It's a bit late so maybe I buggered > up when I tried to use dictionary assignment with it, but who knows :p Actually just realised I had the number on the wrong side... :D preformatted_string = """ %(first_name)s %(contact_num)20s %(contact_type)20s """ print preformatted_string % {'first_name':'Chris', 'contact_num':'555-5555', 'contact_type':'Home'} From duncan.booth at invalid.invalid Thu Jun 12 04:12:00 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jun 2008 08:12:00 GMT Subject: ClassName.attribute vs self.__class__.attribute References: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> Message-ID: Mike Orr wrote: > That's a misunderstanding of classes vs instances. If you have an > instance of MyClass(Superclass), there is one instance but several > classes. The instance is of MyClass; there is no instance of > Superclass. 'self' has a .__class__ attribute because it's an > instance, but MyClass and Superclass do not because they're already > classes. Classes are also instances, usually they are instances of the type 'type' (and even 'type' is an instance of itself): >>> class SuperClass(object): pass >>> SuperClass.__class__ >>> type(SuperClass) >>> type.__class__ Old style classes don't have a class attribute, but you shouldn't be using old style classes anyway and so long as you use type(x) to access its class rather than accessing the __class__ attribute directly that doesn't particularly matter. -- Duncan Booth http://kupuguy.blogspot.com From deets at nospam.web.de Wed Jun 11 10:01:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 11 Jun 2008 16:01:31 +0200 Subject: Does the python library of Google Data API is truly free? References: <3ac654b2-61b4-44ce-8e03-75f2344d5869@s50g2000hsb.googlegroups.com> <6fb57ab1-b0d2-4b7d-93c1-b919ca0e51a0@i36g2000prf.googlegroups.com> <3a296d00-d4e0-4f03-b6b3-bef4c5d628dd@x35g2000hsb.googlegroups.com> <6b5mloF3aeui4U1@mid.uni-berlin.de> <18115776-edf7-41b8-a5e9-639847c57a6a@x41g2000hsb.googlegroups.com> Message-ID: <6ba472F3anud0U1@mid.uni-berlin.de> > I understand very well that a service is a software which is accessed > through a network. No, you obviously don't understand. A service is something that is offered to you, for free or not, and that you might use on the terms the service provider lays down. Some examples? Pizza delivery service Shoe cleaning service Car wash service Online software store Google search engine/mail/groups/other services All these are services. You are free to use them, on their terms and conditions. Some require you to pay money. Some take your data, enrich/recombine or do whatever with it, and provide you added value - for the cost of you giving away the data for free and agreeing on using it, and for having to look at advertisements when using the service. > And the description given on Wikipedia [1] is "A 'Web service' (also > Web Service) is defined by the W3C as "a software system designed to > support interoperable Machine to Machine interaction over a network." A webservice is a technical term for software interoperation. It has *nothing* to do with a service in the above sense. It defines an interface, it might come with a example implementation under a FOSS license. > Now, to ending with this. I understand that (almos) everybody is pro > Google (and anti Microsoft), thinking that they have given a lot of > services for free. And it's very hard that people understand my > thinking. because it is obviously skewed. Just because the term "service" is used in two meanings does not mean they are the same... > All that "free service" has a great price, that are the rights > about those data, and when Google want can to disable the free access > to that information. Yes, they can. That are their conditions. But this has *NOTHING* to do with them offering a piece of software under a FOSS license. > People don't realize that it's one more a company and like so it has > only an end, that is to obtain the greater number of benefits which > will be distributed between his shareholders. Within any years Google > will be as hated as Microsoft. Maybe, maybe not. > At least I try to use the less possible those services than limit my > freedoms about data that has been contributed by me and another users. You are free to do so, and I can't say a single word against it. But you say """ There is certain deceit because they have used a free license as Apache 2.0 so that people think that it is a free program, but it stops of being it when there are terms/conditions of this style. They use to the community to get information as data about geo- localization. You haven't any right about its *free software* but they get all rights about your content. And they could cancel the service when they want. In addition these terms are more restrictive that the owner software, because you could not duplicate any service. Please read well those terms and conditions before of use that library because *IT IS NOT FREE SOFTWARE*. """ It is FREE SOFTWARE. You can take the software ,manipulate it, redestribute it under the terms of the GPL and so forth. That has NOTHING to do with the service offered by google HOSTED AT THEIR SITE, PROGRAMMED AT THEIR EXPENSE, OPERATED AT THEIR COSTS to be something they put out for free. They do gather your data to make a richer experience for others, including yourself, and cashing in on advertisements or whatever business-model they like. If you don't like that, fine. But that has *nothing* to do with free software they might offer to access that service. Diez From aahz at pythoncraft.com Mon Jun 16 19:44:15 2008 From: aahz at pythoncraft.com (Aahz) Date: 16 Jun 2008 16:44:15 -0700 Subject: We are all consenting adults here References: <2cca4335-1162-4d61-b115-1f17d368721d@d1g2000hsg.googlegroups.com> Message-ID: In article <2cca4335-1162-4d61-b115-1f17d368721d at d1g2000hsg.googlegroups.com>, David Hughes wrote: > >Who coined this originally? AFAICT, none other than Guido. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From nagle at animats.com Tue Jun 3 12:19:49 2008 From: nagle at animats.com (John Nagle) Date: Tue, 03 Jun 2008 09:19:49 -0700 Subject: Continuous Timer In-Reply-To: References: <496954360805301850u4ce63746vc8fcc84ad1b72824@mail.gmail.com> Message-ID: <48456b96$0$17165$742ec2ed@news.sonic.net> Gabriel Genellina wrote: > En Fri, 30 May 2008 22:50:13 -0300, Robert Dailey > escribi?: > >> Reading through the Python 2.5 docs, I'm seeing a Timer class in the >> threading module, however I cannot find a timer object that will >> continuously call a function of my choice every XXXX amount of >> milliseconds. >> For example, every 1000 milliseconds I want a function named Foo to be >> called. This would continue to happen until I terminate the timer in >> my main >> thread. Thanks for the help. > > Use an Event object; its wait() will provide the sleep time, and when it > is set() the thread knows it has to exit. > > import threading > import time > > def repeat(event, every, action): > while True: > event.wait(every) > if event.isSet(): > break > action() Actually, to do this right, it's necessary to account for the time used by "action". The code above will run no sooner than the time "every" after the COMPLETION of action. I've done this sort of thing under QNX, the real-time operating system, which has better timing primitives, and seen the action executed within a few microseconds of the correct time, every time. But that was in C++. If you're trying to do hard real time in Python on Linux or Windows, don't expect reliable timing. Remember, Python isn't really preemptive, because of the global interpreter lock and the lack of thread priorities. John Nagle From prabhuragav.b at gmail.com Fri Jun 6 12:04:27 2008 From: prabhuragav.b at gmail.com (BABLU) Date: Fri, 6 Jun 2008 09:04:27 -0700 (PDT) Subject: EARN DOLLARS WIYH OUT INVESTMENT Message-ID: <1fc408cd-c95f-4a73-80b2-d1b6db4ec7c8@x19g2000prg.googlegroups.com> Hi, I am doing home based business and earning a good amount of money and found that business through internet is amazing to earn during leisure.Its just easy and relaxing. Just login in the link below and register yourself. register is free. then they will promote job for you. I have provided three site links for you so that you can earn money in which you want. Every job is genuine, good easy and interesting too. Make a try and fill your pockets with dollars. FREE ! FREE ! FULLY GENUINE HOME BASED ? CLICK HERE http://www.ezinfocenter.com/10122618/CB http://Prabhiya.dubaimlm.com? http://www.CashBlasterPro.com/earndollars http://www.webupgrade7.com/earndollars http://www.webupgrade9.com/earndollars http://www.webupgrade10.com/earndollars http://www.www2upgrade.com/earndollars http://www.BizOpSpace.com/earndollars http://www.BizOpBuilder.com/earndollars http://www.MyWebToo.com/earndollars http://www.Web2Wow.com/earndollars While you've been reading the above, thousands of people all over the world have been working. I even make money while I sleep! By this time next week, so could YOU. Get full info here http://www.ezinfocenter.com/10122618/CB http://Prabhiya.dubaimlm.com http://www.CashBlasterPro.com/earndollars http://www.webupgrade7.com/earndollars http://www.webupgrade9.com/earndollars http://www.webupgrade10.com/earndollars http://www.www2upgrade.com/earndollars http://www.BizOpSpace.com/earndollars http://www.BizOpBuilder.com/earndollars http://www.MyWebToo.com/earndollars http://www.Web2Wow.com/earndollars Network Marketing is BOOMING on the Web! Learn how we're sponsoring OVER 100,000 monthly worldwide without mailing anything, without faxing anything, without calling anyone! Totally Internet and system- driven and we've only scratched the surface. Get started FREE! Sign up as an affiliate at: http://www.ezinfocenter.com/10122618/CB ?http://Prabhiya.dubaimlm.com http://www.CashBlasterPro.com/earndollars http://www.webupgrade7.com/earndollars http://www.webupgrade9.com/earndollars http://www.webupgrade10.com/earndollars http://www.www2upgrade.com/earndollars http://www.BizOpSpace.com/earndollars http://www.BizOpBuilder.com/earndollars http://www.MyWebToo.com/earndollars http://www.Web2Wow.com/earndollars For More Details : Contact us at: Priya Prabhu No.75/31,Ist Floor , Subramanianm Swamy Koil Street West Saidapet chennai-600015 prabhuragav.b at gmail.com http://www.ezinfocenter.com/10122618/CB http://Prabhiya.dubaimlm.com http://www.CashBlasterPro.com/earndollars http://www.webupgrade7.com/earndollars http://www.webupgrade9.com/earndollars http://www.webupgrade10.com/earndollars http://www.www2upgrade.com/earndollars http://www.BizOpSpace.com/earndollars http://www.BizOpBuilder.com/earndollars http://www.MyWebToo.com/earndollars http://www.Web2Wow.com/earndollars From smmckay at broncs.utpa.edu Sun Jun 8 23:31:17 2008 From: smmckay at broncs.utpa.edu (Steve McKay) Date: Sun, 08 Jun 2008 22:31:17 -0500 Subject: sendKey In-Reply-To: <47d57426-3131-4252-8cee-086977f51b0b@2g2000hsn.googlegroups.com> References: <47d57426-3131-4252-8cee-086977f51b0b@2g2000hsn.googlegroups.com> Message-ID: Gandalf wrote: > I found some script that send keys , But I couldn't manage to send > CTRL+c with none of them > > can any one tell me what i'm doing wrong: > > import win32api > import win32com.client > > shell = win32com.client.Dispatch("WScript.Shell") > shell.Run("Notepad") > win32api.Sleep(100) > shell.AppActivate("Notepad") > win32api.Sleep(100) > shell.SendKeys("112435435") > win32api.Sleep(100) > > shell.SendKeys("^a") # that wouldn't select all > win32api.Sleep(100) > shell.SendKeys("^c")# that wouldn't copy > > > > > import SendKeys > SendKeys.SendKeys("""^c""") > > > Thank you! > Your code didn't work for me, either. But shell.SendKeys("^a^c") works...go figure. From hancock.robert at gmail.com Mon Jun 16 19:20:53 2008 From: hancock.robert at gmail.com (Robert Hancock) Date: Mon, 16 Jun 2008 16:20:53 -0700 (PDT) Subject: sqlite3 and Python 2.5.1 References: <612ed26a-c6cf-4133-af6c-f256484e3928@x41g2000hsb.googlegroups.com> <6bo3euF3c8etnU1@mid.uni-berlin.de> Message-ID: On Jun 16, 5:15 pm, Gerhard H?ring wrote: > milan_sanremo wrote: > > I have sqlite installed, but when I try to importsqlite3I receive: > > > Python 2.5.1 (r251:54863, Nov 3 2007, 02:54:36) [C] on sunos5 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> importsqlite3 > > Traceback (most recent call last): > > File "", line 1, in > > ImportError: No module namedsqlite3 > > > Yet: > > > # find /usr/local/python -name "sqlite*" -print > > /usr/local/python/lib/python2.5/sqlite3 > > > # /opt/csw/bin/sqlite3 > > SQLite version 3.2.2 > > Enter ".help" for instructions > > sqlite> > > > What is missing? > > You compiled Python yourself. During that, theSQLite3header files > could not be found, so thesqlite3module was not compiled/installed. > > -- Gerhard Thanks, I'll recompile. From leodp at yahoo.com Mon Jun 30 06:13:22 2008 From: leodp at yahoo.com (leodp) Date: Mon, 30 Jun 2008 03:13:22 -0700 (PDT) Subject: Getting sorting order References: <7cb9ebb7-e722-41e1-bdf2-693954a21b92@j22g2000hsf.googlegroups.com> Message-ID: <5ce855b0-e2fa-4323-b7b8-5b5dd11ef586@d1g2000hsg.googlegroups.com> > >>> master_index.sort(key=master.__getitem__) that was it! Thanks Peter, leodp From lotrpy at gmail.com Wed Jun 11 20:14:25 2008 From: lotrpy at gmail.com (lotrpy) Date: Wed, 11 Jun 2008 17:14:25 -0700 (PDT) Subject: How to make py2.5 distutil to use VC2005? References: Message-ID: <4b6be352-c119-4b20-a32d-f85863227cc8@n19g2000prg.googlegroups.com> On 6?4?, ??9?47?, "David Cournapeau" wrote: > On Wed, Jun 4, 2008 at 11:38 AM, ?? wrote: > > Well, IMO, the format of binary files generated by VC2003 and > > VC2005 is compatible in most cases. > > Problem arise with the C runtime, not with object file format. In > particular, python uses the C api for file handling, and the standard > C is definitely not ABI compatible within VS versions. > > I strongly advise you against using VS 2005 (with the binary python; > if you build python by yourself, then no problem; I don't know if it > is possible to build python with VS 2005). You *will* get crashes in > many cases. > > David My stupid question: if there is something between VS 2003 and VS 2005 incompatible, what about MINGW for python2.5(VS 2003)? Is it safe, or just as (un)safe as VS 2005? From nospam at nospam.com Sun Jun 1 08:43:06 2008 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 01 Jun 2008 14:43:06 +0200 Subject: [Business apps for Windows] Good grid + calendar, etc.? References: Message-ID: On Sun, 1 Jun 2008 21:27:30 +0900, "Ryan Ginstrom" wrote: >For your stated needs, I'd advise checking out IronPython or Python.NET >(which allow use of .NET GUI libraries). Thanks but I forgot to say that I'd rather not use .Net because deployment/updates are too problematic for our audience. .. that's assuming that a GUI Python can install/update itself as easily as eg. Delphi, which is where I could be wrong :-/ From tdahsu at gmail.com Fri Jun 13 11:11:16 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Fri, 13 Jun 2008 08:11:16 -0700 (PDT) Subject: Iterate creating variables? Message-ID: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> I have twenty-five checkboxes I need to create (don't ask): self.checkbox1 = ... self.checkbox2 = ... . . . self.checkbox25 = ... Right now, my code has 25 lines in it, one for each checkbox, since these are all variables. Is there a way to write a loop so that I can have fewer lines of code but still keep the variables? I've tried: for o in xrange(25): self.checkbox[o] = ... which didn't work, and for o in xrange(25): self.checkbox[''%d'%(o)] = ... which also didn't work. Both give the error message: "Attribute error: Main.App has no attribute "checkbox"", which clearly indicates that I'm not keeping the "variability" aspect I want. Is there a way? I appreciate any and all answers! Thanks! From gagsl-py2 at yahoo.com.ar Wed Jun 18 03:45:54 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Jun 2008 04:45:54 -0300 Subject: Does '!=' equivelent to 'is not' References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> Message-ID: En Tue, 17 Jun 2008 23:04:16 -0300, Asun Friere escribi?: > On Jun 17, 5:33 pm, "Gabriel Genellina" > wrote: >> En Tue, 17 Jun 2008 02:25:42 -0300, Lie escribi?: > >> >> > Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)' >> > and 'not(id(a) == id(b))' >> >> No. > ... >> ... The above statement is not. A counterexample: >> >> py> [] is [] >> False >> py> id([])==id([]) >> True >> > But that's not what he said, he used 'a' and 'b' which are names, not > anonymous objects. > Fairer would be, > a = [];b = [] > id(a) == id(b) If you limit yourself to interpret 'a' and 'b' as actual names, yes, the statement is true. But I thought of them as placeholders or metasyntactic names - like in "abs(x) returns the absolute value of x", where x may represent *any* expression, not just a single name. Under this general interpretation the statement is not true anymore. (This thread is getting way above 10000cp...) -- Gabriel Genellina From jarausch at igpm.rwth-aachen.de Mon Jun 23 04:38:01 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Mon, 23 Jun 2008 10:38:01 +0200 Subject: 2to3 bug and question Message-ID: <6c95nbF3euiugU1@mid.dfncis.de> Hi, is this the right group to ask / report problems with python3.0 ? The question: Is it possible to tell 2to3 to replace, say, #!/usr/bin/python by #!/usr/local/bin/python3.0 ? Here the bug: While 2to3 keeps the first line #!/usr/bin/python it removes the first line if it was #!/usr/bin/python -O Is this a bug or a feature? Thanks for hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From moneymakecash2 at gmail.com Tue Jun 10 14:51:23 2008 From: moneymakecash2 at gmail.com (MERLIN) Date: Tue, 10 Jun 2008 11:51:23 -0700 (PDT) Subject: BANKRUPTCY LAWYER Message-ID: <5638827c-d056-4b21-a0d4-c863c6c6dbe6@z16g2000prn.googlegroups.com> ****************************************** http://bankruptcylawyer1.blogspot.com From victor.herasme at gmail.com Thu Jun 5 10:19:07 2008 From: victor.herasme at gmail.com (victor.herasme at gmail.com) Date: Thu, 5 Jun 2008 07:19:07 -0700 (PDT) Subject: Tuples part 2 References: <6d3e6d40-63a6-40d1-8ea4-5ddf40238d8d@m44g2000hsc.googlegroups.com> Message-ID: On Jun 5, 3:49 pm, Ivan Illarionov wrote: > On 5 ???, 01:57, "victor.hera... at gmail.com" > wrote: > > > > > Hi Everyone, > > > i have another question. What if i wanted to make n tuples, each with > > a list of coordinates. For example : > > > coords = list() > > for h in xrange(1,11,1): > > for i in xrange(1, 5, 1) : > > for j in xrange(1, 5, 1) : > > for k in xrange(1,2,1) : > > coords.append((i,j,k)) > > lista+str(h)= tuple coords > > print tuple(coords) > > > so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do > > it the way i show you above but it is not working properly. I wish you > > could help me with that. Thanks again, > >>> from itertools import repeat, izip > >>> coords = tuple((i,j,k) for i in xrange(1,5) for j in xrange(1,5) for k in xrange(1,2)) > >>> locals().update(("tuple%s" % i, coord) for i, coord in izip(xrange(1,11), repeat(coords))) > >>> tuple1 > > ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (2, 1, 1), (2, 2, 1), (2, > 3, 1), (2 > , 4, 1), (3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1), (4, 1, 1), (4, 2, > 1), (4, 3 > , 1), (4, 4, 1)) > > Does this help? > > But I don't understand why you need this? > > Ivan Hi, What i need is, for example: tuple 1=((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)) tuple 2=((2, 1, 1), (2, 2, 1), (2, 3, 1), (2, 4, 1)) tuple 3=((3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1)) and so on. Please help me and sorry for not taking the time to post my questions properly. Victor From wmcbrine at users.sf.net Fri Jun 13 21:46:24 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Sat, 14 Jun 2008 01:46:24 GMT Subject: Python Socket programming References: Message-ID: On Fri, 13 Jun 2008 21:59:06 +0530, srinivasan srinivas wrote: > I am going to do some socket related programming in Python. Before that, > I wish to know the Gotchas of Python Scoket Programming. The only gotcha I see is that you won't want to go back to doing it in C. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From pavel.uvarov at gmail.com Tue Jun 3 11:28:38 2008 From: pavel.uvarov at gmail.com (pavel.uvarov at gmail.com) Date: Tue, 3 Jun 2008 08:28:38 -0700 (PDT) Subject: ThreadPoolingMixIn References: <3d9dac72-ce4d-4ce5-9213-4bb17aff2f9e@r66g2000hsg.googlegroups.com> <1c4d113e-b375-471d-9d54-1401c8844352@t12g2000prg.googlegroups.com> <03ba6980-55d6-433a-a41f-f36a2edb4d72@f36g2000hsa.googlegroups.com> <4804d404-6d74-4391-a073-aaa7f51a7dc9@z66g2000hsc.googlegroups.com> Message-ID: <7e4efa2e-6438-4d3f-b996-c52859e65715@k37g2000hsf.googlegroups.com> On Jun 3, 1:19 am, miller.pau... at gmail.com wrote: > On Jun 2, 12:41 pm, pavel.uva... at gmail.com wrote: > > > > > On Jun 2, 7:15 pm, Michael Str?der wrote: > > > Here are benchmarks for FreeBSD 6.2, amd64 > > > packet_size x y > > 0 499.57 1114.54 > > 1024 499.29 1130.02 > > 3072 500.09 1119.14 > > 7168 498.20 1111.76 > > 15360 499.29 1086.73 > > 31744 500.04 1036.46 > > 64512 499.43 939.60 > > 130048 499.28 737.44 > > 261120 498.04 499.03 > > 523264 307.54 312.04 > > 1047552 173.57 185.32 > > 2096128 93.61 94.39 > > > x = ThreadingMixIn replies/s > > y = ThreadPoolingMixIn replies/s > > Well, I'd say you've got yourself a winner. Performance (at least on > FreeBSD) seems as good or better for your ThreadPoolingMixin than > ThreadingMixin. Is this with the default values of min=5 and max=5 > worker threads? No, I initialized thread pool with min_threads=2, max_threads=200 and min_spare_threads=20. For Linux (2.6.22, amd64) I got even more dramatic improvement: packet_size x y 0 249.97 2014.63 1024 249.98 1782.83 3072 240.09 1859.00 7168 249.98 1900.61 15360 249.98 1787.30 31744 238.96 1808.17 64512 249.85 1561.47 130048 237.26 1213.26 261120 249.98 841.96 523264 249.97 595.40 1047552 236.40 351.96 2096128 216.26 218.15 x = ThreadingMixIn replies/s y = ThreadPoolingMixIn replies/s From cwitts at gmail.com Mon Jun 2 17:34:52 2008 From: cwitts at gmail.com (Chris) Date: Mon, 2 Jun 2008 14:34:52 -0700 (PDT) Subject: Formatting Output References: <6e94b4dc-5920-447e-9971-96ec6a48b9ce@c58g2000hsc.googlegroups.com> <6ea2e85a-d00c-4228-98be-431205fceb7b@34g2000hsf.googlegroups.com> Message-ID: <650fca09-a6de-4d81-a19b-687c63ad429b@l64g2000hse.googlegroups.com> On Jun 2, 9:43?pm, Doug Morse wrote: > On Mon, 2 Jun 2008 12:42:12 -0700 (PDT), Mensanator wrote: > > ?On Jun 2, 3:38?am, Chris wrote: > > > On Jun 2, 9:34?am, "victor.hera... at gmail.com" > > > > wrote: > > > > Hi, > > > > > i am building a little script and i want to output a series of columns > > > > more or less like this: > > > > > 1 ?5 ?6 > > > > 2 ?2 ?8 > > > > 2 ?9 ?5 > > ... > > I have a related question: > > Does Python have (or can emulate) the formatted output capability found in > Perl? > > For example, all I have to do to get nicely formatted (i.e., aligned) output > is provide values for special STDOUT variables (i.e., STDOUT_TOP, STDOUT, > STDOUT_BOTTOM, etc.), exemplified by: > > ? format STDOUT_TOP = > ? ------------------------------------------------------------------------------ > ? ~ > ? . > > ? format STDOUT = > ? @<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<< > ? $res->{'full_name'}, ?$res->{'phone_1'}, ? ? ? ? $res->{'phone_1_type'} > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $res->{'address_1a'}, ? ? ? ? ? ? ? ?$res->{'address_2a'} > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $res->{'address_1b'}, ? ? ? ? ? ? ? ?$res->{'address_2b'} > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $res->{'address_1c'}, ? ? ? ? ? ? ? ?$res->{'address_2c'} > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $city_1 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?$city_2 > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $res->{'email_1'}, ? ? ? ? ? ? ? ? ? $res->{'email_2'} > ? ------------------------------------------------------------------------------ > ? ~ > ? . > > Then, all I have to do is populate my $res object/hash as desired -- in this > example simple the results of a SQL query -- and lastly just call the "write" > function: > > ? write; > > and Perl will produce very nicely formatted results. ?This is useful not only > for producing human readable output, but also fixed-column-width data files, > etc. ?I'd love to learn the Pythonistic way of doing the same thing. > > Thanks! > Doug Can't seem to do this with dictionaries but... preformatted_string = """ %s %20s %20s %s %30s %s %30s """ print preformatted_string % ('first name'[:20], 'contact num 1'[:20], 'contact num type'[:20], 'address line 1'[:30], 'address line 2'[:30] 'address line 3'[:30], 'address line 4'[:30]) You could do something like that. the "[:20]" etc @ the end of the inputs is ofc to trim the strings to a max length. The string formatter supports "%s" so you can use that for alignment. It's a bit late so maybe I buggered up when I tried to use dictionary assignment with it, but who knows :p From martin.nordstrom87 at gmail.com Tue Jun 24 15:59:52 2008 From: martin.nordstrom87 at gmail.com (martin.nordstrom87 at gmail.com) Date: Tue, 24 Jun 2008 12:59:52 -0700 (PDT) Subject: Wrap Numpy with Cython? Message-ID: Hi! I'm trying to wrap numpy with Cython and I've tried to use this guide to manage this: http://wiki.cython.org/WrappingNumpy However when I send an array to mysum() it gives me the right answer only when dtype of the array is float, otherwise it gives me random answers. The problem may be that the array is converted to a C double which is just as long as float for Numpyarrays and therefore it works only when the dtype is float. How do I make a Numpywrapper that works with an arbitrary dtype? I've also tried to convert a tuple or list with only numbers in it to a C array with Cython but I've failed. Does anyone have an example of how to do this? Thanks! Martin From jeff at jmcneil.net Wed Jun 11 14:58:52 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 11 Jun 2008 14:58:52 -0400 Subject: Programming question In-Reply-To: <31C3FE622274D44A8FE8E8D649AE178805E738D4@exch1.wni.com> References: <31C3FE622274D44A8FE8E8D649AE178805E738D4@exch1.wni.com> Message-ID: <82d28c40806111158x542000f0n5a99c39e4eacd9ec@mail.gmail.com> Have a look at os.listdir and os.stat. I've never worked with 1.5, so I don't know what will work with it and what won't,. but I'd imagine the following ought to be fine, though. stat_list = [] for dirent in os.listdir('your_directory'): stat_list.append(os.stat(dirent)) Jeff On Wed, Jun 11, 2008 at 2:33 PM, Brad Navarro wrote: > Greetings, > > > > Being extremely new to Python, I haven't got the experience to figure this > one out on my own and frankly I am not sure I would know where to look. > > > > Basically, what I am trying to do is get a list of each file's attributes > within a directory. Basically, the information that the 'ls ?l' command > would give you in a linux shell, except the results for each file in the > directory are stored as a list. > > > > I am presently using version 1.5 on a linux machine. I have kindly requested > my system administrator to upgrade to 2.5.2, but until then I am afraid I am > stuck with 1.5. > > > > > > Thanks, > > Brad > > -- > http://mail.python.org/mailman/listinfo/python-list > From userprogoogle-139 at yahoo.co.uk Thu Jun 26 05:41:03 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Thu, 26 Jun 2008 02:41:03 -0700 (PDT) Subject: Mobile Devices References: <549d4fcd-7c89-47dc-9a44-8e3e6ac92ed2@d77g2000hsb.googlegroups.com> Message-ID: <9d18a9fb-eac8-47bb-8b68-e65a64957f1e@e53g2000hsa.googlegroups.com> Thanks for your reply, I may dig out my really old Symbian phone and try it out. rod From arslanburney at gmail.com Fri Jun 13 01:32:23 2008 From: arslanburney at gmail.com (arslanburney at gmail.com) Date: Thu, 12 Jun 2008 22:32:23 -0700 (PDT) Subject: Plotting Graphs + Bestfit lines Message-ID: <1a919a2b-6430-4e2e-a190-2e00e43a6138@25g2000hsx.googlegroups.com> Hello. Ive got two functions here. Somehow the program does not go in to the second function wehn i call it. The bestfit function. Could some1 help me identify the problem. Heres the code: import Gnuplot def bestfit(uinput): if not isinstance(uinput, list): return False else: sigmax = sigmay = sigmaxy = sigmaxwhl = sigmaxsq = 0 for i in range(len(uinput)): n = len(uinput) sigmax = uinput[i][0] + sigmax sigmay = uinput[i][1] + sigmay sigmaxy = uinput[i][0] * uinput [i][1] + sigmaxy sigmaxwhl = sigmax * sigmax sigmaxsq = uinput[i][0] * uinput[i][0] + sigmaxsq sigmaxsigmay = sigmax * sigmay num = sigmaxsigmay - (n * sigmaxy) den = sigmaxwhl - (n* sigmaxsq) num2 = (sigmax * sigmaxy) - (sigmay * sigmaxsq) gradient = num / den intercept = num2 / den m = gradient c = intercept p = Gnuplot.Gnuplot() p.plot ('%f * x+%f'%(m,c)) return p def plot(original, expected, actual): if not isinstance(original, list): return False else: gp = Gnuplot.Gnuplot() gp('set data style lines') # Make the plot items plot1 = Gnuplot.PlotItems.Data(original, title="Original") plot2 = Gnuplot.PlotItems.Data(expected, title="Expected") plot3 = Gnuplot.PlotItems.Data(actual, title="Acutal") gp.plot(plot1, plot2, plot3) bestfit(expected) bestfit(actual) return gp ------- import Combine #The name of my file... gp = Combine.plot( [(2,3), (4,8), (5,9), (6,2)], [(1,7), (3,3), (4,5), (5,6)], [(1,3), (3,10), (4,8), (7,9) ] ) raw_input() From jaywgraves at gmail.com Tue Jun 3 09:49:52 2008 From: jaywgraves at gmail.com (jay graves) Date: Tue, 3 Jun 2008 06:49:52 -0700 (PDT) Subject: Cast list of objects to list of strings References: <48546eb1-11f3-4a88-b1ac-97bd485a1823@k30g2000hse.googlegroups.com> <63d3d50d-0e9b-4682-b523-c2ff7d336c6a@m44g2000hsc.googlegroups.com> Message-ID: On Jun 2, 8:36 pm, "Gabriel Genellina" wrote: > Still nitpicking: using a generator expression in this case has no > advantage. The first thing that str.join does is to create a list out of > its argument (unless it is already a list or a tuple). In fact, a list > comprehension is faster here. Really! I stand corrected. I'm not a C programmer but I peeked at the source. I see that it makes a pass to calculate the total size and then another pass to catenate the items, which makes sense from a memory allocation standpoint. To compare and contrast, I looked up the 'sum' built in and saw that it used the iterator protocol, (PyObject_GetIter). I assume that the other similar functions (min,max, etc) would do the same. Thanks for setting me straight. ... Jay From roy at panix.com Thu Jun 5 15:20:15 2008 From: roy at panix.com (Roy Smith) Date: Thu, 05 Jun 2008 15:20:15 -0400 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> <4847d203$0$32733$426a74cc@news.free.fr> Message-ID: In article , "Russ P." wrote: > In C++ (and > Java?), on the other hand, the "protected" keyword *really* prevents > the client from accessing the data or method, but it allows access to > derived classes. The "private" keyword goes further and prevents > access even by derived classes. In C++, it does no such thing. Consider this class declaration in MySecretClass.h: class MySecretClass { private: int foo; }; All somebody has to do to get at the private data is: #define private public # include #undef private If playing preprocessor games isn't your thing, there's a whole multitude of other tricks you can play with pointers and typecasts that will get you access to foo in other ways. But, you protest, you're not supposed to do that! Well, of course not. But you're not supposed to ignore the leading underscore convention in Python either. That's the nice thing about freedom of religion; you get to pick which particular sins you want to get freaked out about. I'm pretty weak on Java, but my understanding is that it's in better shape here, since it has neither textual inclusion of header files, nor pointers. You might have to resort to JNI :-) From no.spam at spam.no Mon Jun 9 07:23:22 2008 From: no.spam at spam.no (Thin Myrna) Date: Mon, 09 Jun 2008 13:23:22 +0200 Subject: Access to CAN-Bus References: <484cd469$0$28520$3b214f66@aconews.univie.ac.at> Message-ID: <484d12aa$0$11610$3b214f66@aconews.univie.ac.at> Thin Myrna wrote: Thanks for all your answers. I've just contacted the vendor for Linux support. If I went for an other vendor (I'm on a notebook, so USB-hardware is needed): Does anyone have especially good experiences with a particular one? Anyone I should stay away from? Kind regards Thin > I'd like to access some drive hardware via CAN bus from Python under Linux > (sending rec'ing PDOs). Googling around I couldn't find a Python package, > but people who said that they are doing this, though. I guess they are > using their home brewn software. > > Any pointer to > - such software (anyone willing to share his experience?) > - how to write such software? > > Under Windows, I guess, I could use some COM or ctypes functionality to > access the hardware vendor's hardware. What if I wanted to access such > hardware from Linux? Is there a package that allows that in a vendor (who > doesn't support Linux) independent way? > > Many thanks in advance > Thin From Robert.Bossy at jouy.inra.fr Wed Jun 18 08:35:28 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 18 Jun 2008 14:35:28 +0200 Subject: dict order In-Reply-To: References: Message-ID: <48590110.2060600@jouy.inra.fr> Peter Otten wrote: > Robert Bossy wrote: > > >> I wish to know how two dict objects are compared. By browsing the >> archives I gathered that the number of items are first compared, but if >> the two dict objects have the same number of items, then the comparison >> algorithm was not mentioned. >> > > If I interpret the comments in > > http://svn.python.org/view/python/trunk/Objects/dictobject.c?rev=64048&view=markup > > correctly it's roughly > > def characterize(d, e): > return min(((k, v) for k, v in d.iteritems() if k not in e or e[k] != v), > key=lambda (k, v): k) > > def dict_compare(d, e): > result = cmp(len(d), len(e)) > if result: > return result > try: > ka, va = characterize(d, e) > except ValueError: > return 0 > kb, vb = characterize(e, d) > return cmp(ka, kb) or cmp(va, vb) Thanks, Peter! That was exactly what I was looking for. Quite clever, I might add. RB From bruno.desthuilliers at gmail.com Fri Jun 20 17:39:33 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 20 Jun 2008 14:39:33 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> <8711b1fe-8256-4f6f-a3d7-f99f44eb23b0@e53g2000hsa.googlegroups.com> Message-ID: <44e5837c-42f9-49b3-9a92-0560ddcda8ba@z66g2000hsc.googlegroups.com> On 20 juin, 21:44, eliben wrote: > On Jun 20, 3:19 pm, George Sakkis wrote: > (snip) > > It's still not clear why the generic version is so slower, unless you > > extract only a few selected fields, not all of them. Can you post a > > sample of how you used to write it without exec to clarify where the > > inefficiency comes from ? > > > George > > The generic version has to make a lot of decisions at runtime, based > on the format specification. > Extract the offset from the spec, extract the length. import operator transformers = [] transformers.append(operator.itemgetter(slice(format.offset,format.offset +format.length))) > Is it msb- > first ? Then reverse. if format.msb_first: transformer.append(reverse) > Are specific bits required ? If so, do bit > operations. etc.... Python functions are objects, you can define your own callable (ie: function like) types, you can define anonymous single-expression functions using lambda, functions are closures too so they can carry the environment they were defined in, implementing partial application (using either closures or callable objects) is trivial (and is in the stdlib functools module since 2.5 FWIW), well... Defining a sequence of transormer functionals is not a problem neither. And applying it to your data bytestring is just trivial: def apply_transformers(data, transormers) : for transformer in transformers: data = transformer(data) return data ... and is not necessarily that bad performance-wide (here you'd have to benchmark both solutions to know for sure). > A dynamically generated function doesn't have to make any decisions - No, but neither does a sequence of callable objects. The decisions are taken where you have the necessary context, and applied somewhere else. Dynamically generating/compiling code is one possible solution, but not the only one. > I guess this is not much different from Lisp macros The main difference is that Lisp macro are not built as raw string, but as first class objects. I've so found this approach more flexible and way easier to maintain, but here again, YMMV. Anyway, even while (as you may have noticed by now) I'm one of these "there's-a-better-way-than-eval-exec" peoples, I'd think you may (depending on benchmarks with both solutions and real-life data) have a valid use case here - and if you encapsulate this part correctly, you can alway start with your current solution (so you make it work), then eventually switch implementation later if it's worth the extra effort... Just my 2 cents. Truth is that as long as it works and is maintainable, then who cares... From goldnery at gmail.com Tue Jun 17 17:49:34 2008 From: goldnery at gmail.com (Gandalf) Date: Tue, 17 Jun 2008 14:49:34 -0700 (PDT) Subject: text alignment References: <39d1c620-9923-46e7-999d-ed86c8b465ff@34g2000hsh.googlegroups.com> <114f3f4c-4004-488b-86c5-4bf6416e15bd@l42g2000hsc.googlegroups.com> <8d563101-53f0-41d3-a544-ee0ba1d58db5@m36g2000hse.googlegroups.com> <657c1cb2-cfeb-4806-960c-15b3f25f6575@w7g2000hsa.googlegroups.com> <39ae3cec-c231-4196-8f9a-b567b9a47b5c@c65g2000hsa.googlegroups.com> Message-ID: On Jun 17, 8:43?pm, Mike Driscoll wrote: > On Jun 17, 1:20?pm, Gandalf wrote: > > > since you brought up this issue, please tell me where can I fine > > menual for this library? > > You want the manual for wxPython? Go to the download page on the > Official wxPython page and get the Docs & Demos package:http://wxpython.org/download.php > > That include the wxWidgets Reference. Also see:http://wxpython.org/onlinedocs.php > > > can i generate dynamic GUI from it? > > Not sure what you mean by this. If you know how to create a "dynamic > GUI" with html/ajax or some such based on the user's interactions with > your website, than it should work in the embedded browser just as well > as it would in a non-embedded one. > > > If not, Is there any way to generate dynamic GUI (one that can change > > according to the user input) with HTML-CSS- javascript similar > > environment? > > Mike Hi Mike, I was referring to the ActiveX_IEHtmlWindow which you talked about, when I asked you for a tutorial. I have lots of experience on developing web application so if I could implement some of my knowledge for developing none web application it can save me trouble thanks From martin at v.loewis.de Thu Jun 5 16:36:00 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 05 Jun 2008 22:36:00 +0200 Subject: How to make py2.5 distutil to use VC2005? In-Reply-To: References: <5b8d13220806040647o1148bf90x6b2b546e9cb339b5@mail.gmail.com> <5b8d13220806050134s3e6ad9dfn15bd4c5924551bdc@mail.gmail.com> Message-ID: <48484e30$0$9694$9b622d9e@news.freenet.de> > I really really wonder how to *force* distutil to use my specified compile. > eg: (pseudo) You need to make sure that both MSSdk and DISTUTILS_USE_SDK are set, see http://docs.python.org/dist/module-distutils.msvccompiler.html Regards, Martin From 42flicks at gmail.com Tue Jun 10 07:03:20 2008 From: 42flicks at gmail.com (Mike) Date: Tue, 10 Jun 2008 23:03:20 +1200 Subject: TWITTER API and urllib2 In-Reply-To: <2b54d4370806100342h7a34f5f3p13ba81a6e873f14f@mail.gmail.com> References: <2b54d4370806100342h7a34f5f3p13ba81a6e873f14f@mail.gmail.com> Message-ID: <2b54d4370806100403k3a65df23nde52d100a5d580ca@mail.gmail.com> On Tue, Jun 10, 2008 at 10:42 PM, Mike <42flicks at gmail.com> wrote: > Hello, > > I've spent the last couple of nights hacking away at a Python wrapper for > the Twitter API that I can use for various things. > > I'm having trouble with one of the methods: user_timeline. ( > http://groups.google.com/group/twitter-development-talk/web/api-documentation#HelpMethods > ). > > This is the only method that is returning a HTTP 401. It seems strange and > I'm not sure how to debug it further as the other methods requring > authentication work. > > Please keep in mind the code is missing alot of polish :) - Though I'm open > to suggestions on improvements. > > If anyone is familiar with this I'd really appreciate a hint as it has me > stumped! (I really need this method for my functionality too!) > > --- > > import urllib2, urllib, urlparse > > class TwitterMethods(object): > def __init__(self): > pass > > def url_request(self,uri,authentication=None): > auth = urllib2.HTTPBasicAuthHandler() > netlock = urlparse.urlparse(uri) > if authentication: > passwdMgr = urllib2.HTTPPasswordMgrWithDefaultRealm() > > passwdMgr.add_password(None,netlock[1],authentication.username,authentication.password) > > auth = urllib2.HTTPBasicAuthHandler(passwdMgr) > req = urllib2.Request(uri) > o = urllib2.build_opener(auth) > try: > f = o.open(req) > print f.readlines([0]) > except o.error: > print "error" > #except: > # print "unknown error" > return > > def UserTimeline(self,authentication): > self.url_request("http://twitter.com/statuses/user_timeline.xml > ",authentication) > > class TwitterAuth(object): > def __init__(self,username,password): > self.username = username > self.password = password > > p = TwitterMethods() > auth = TwitterAuth('email at gmail.com','password') > p.UserTimeline(auth) > > > I did come across this post: http://twitterpatter.wordpress.com/2008/02/11/twitterpatter-update-making-progress-accessing-twitter-timelines/Which only mentions it, does not offer a solution. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Lie.1296 at gmail.com Mon Jun 9 11:41:37 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 9 Jun 2008 08:41:37 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> Message-ID: <49356862-86a6-4df4-886a-cd57827c1b1e@w8g2000prd.googlegroups.com> On Jun 9, 7:20?pm, Antoon Pardon wrote: > On 2008-06-07, BJ?rn Lindqvist wrote: > > > On Wed, Jun 4, 2008 at 2:02 PM, Antoon Pardon wrote: > >> Now of course noone would defend such a limitation on the grounds > >> that one doesn't need the general case and that the general case > >> will only save you some vertical space. > > >> But when it came to the ternary operator that was exactly the > >> argument used, to defend the lack of it. > > > As far as I remember, the primary motivation was developers experience > > with the ternary operator in other languages, especially C, where it > > was found to hurt readability. At least in my experience, it is much > > much more common to see the ternary operator making code more > > obfuscated than easing readability. Time will tell if Python's if-else > > expression will be abused in the same way. > > That seems strange to me. The and-or simulation that was offerd in the > FAQ allowed for about the same kind of structures as the ternary > operator in C and was used in the standard library IIRC. > > So the same unreadable was already possible to write, plus that it > could cause bugs and had to be made even more unreadable in order > to work correctly. Considering this it I find it odd that hurting > readability was a motivation not to have it. In case you didn't notice, the and-or simulation is a hack, it is not to be used by anyone writing real code (instead of for an entry to Obfuscated Python Code Contest) to substitute it for inline if. If inline if is "formalized", that means the language encourages the use of inline if, which we don't want to have. From kyrie at uh.cu Tue Jun 10 01:29:43 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Tue, 10 Jun 2008 01:29:43 -0400 Subject: PEP on breaking outer loops with StopIteration In-Reply-To: References: Message-ID: <1213075783.484e11471be98@comuh.uh.cu> Quoting Kris Kowal : > I had a thought that might be pepworthy. Might we be able to break > outer loops using an iter-instance specific StopIteration type? > > This is the desired, if not desirable, syntax:: > > import string > letters = iter(string.lowercase) > for letter in letters: > for number in range(10): > print letter, number > if letter == 'a' and number == 5: > raise StopIteration() > if letter == 'b' and number == 5: > raise letters.StopIteration() > I must say, I don't even like the idea of having a 'break', but I kind of like this proposal. However, it may be ambiguous [is that a word?] if the outer and inner for loop over the same object. Weird/unlikely situation, I know... but so is having a deep break :D. -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie From maric at aristote.info Tue Jun 24 01:35:55 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 24 Jun 2008 07:35:55 +0200 Subject: Fwd: xml to mysql (vice versa ) too In-Reply-To: References: Message-ID: <200806240735.56237.maric@aristote.info> Le Tuesday 24 June 2008 07:08:46 swapna mudavath, vous avez ?crit?: > can anybody help me in this.... > > -swapna > > ---------- Forwarded message ---------- > From: swapna mudavath > Date: Mon, Jun 23, 2008 at 5:27 PM > Subject: xml to mysql (vice versa ) too > To: Python-list at python.org > > > Hi, > > I need to write a python script to store data which is in XML to MYSQL and > even vice versa.... > what should be the approach? > i am able to establish a connection,create tables and insert data ..... > but how to read an xml file and store in MYSQL.... > my XML structure is like > > > > > > > . > .... > ... > This is not valid xml, there is no commas in attribute list in xml. > can somebody please help me......i am really confused!!!!!! > > thanks in advance :) You could try with minidom if your xml stream isn't too large, else sax parser is to be considered, but minidom is pretty easy to use. Give it a try and come back with more specific questions. In [82]: from xml.dom.minidom import parseString In [83]: xml = """ """ In [89]: def print_nodes(node) : print node if node.attributes : for n, v in node.attributes.items() : print n, v for i in node.childNodes : print_nodes(i) ....: ....: In [94]: dom = parseString(xml) In [95]: print_nodes(dom) id 1 title xyz name abc pos 1 name hgdf pos 3 -- _____________ Maric Michaud From kyosohma at gmail.com Tue Jun 10 13:15:09 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 10 Jun 2008 10:15:09 -0700 (PDT) Subject: problems with opening files due to file's path References: <17759531.post@talk.nabble.com> Message-ID: On Jun 10, 11:45?am, Alexnb wrote: > Gerhard H?ring wrote: > > > Alexnb wrote: > >> Okay, so what I want my program to do it open a file, a music file in > >> specific, and for this we will say it is an .mp3. Well, I am using the > >> system() command from the os class. [...] > > >> system("\"C:\Documents and Settings\Alex\My Documents\My > >> Music\Rhapsody\Bryanbros\Weezer\(2001)\04 - Island In The Sun.wma\"") > >> [...] > > > Try os.startfile() instead. It should work better. > > > -- Gerhard > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > No, it didn't work, but it gave me some interesting feedback when I ran it > in the shell. Heres what it told me: > > >>> os.startfile("C:\Documents and Settings\Alex\My Documents\My > >>> Music\Rhapsody\Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm > >>> Yours.wma") > > Traceback (most recent call last): > ? File "", line 1, in > ? ? os.startfile("C:\Documents and Settings\Alex\My Documents\My > Music\Rhapsody\Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm Yours.wma") > > WindowsError: [Error 2] The system cannot find the file specified: > "C:\\Documents and Settings\\Alex\\My Documents\\My > Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\x01 - I'm > Yours.wma" > > See it made each backslash into two, and the one by the parenthesis and the > 0 turned into an x.... > -- > View this message in context:http://www.nabble.com/problems-with-opening-files-due-to-file%27s-pat... > Sent from the Python - python-list mailing list archive at Nabble.com. Yeah. You need to either double all the backslashes or make it a raw string by adding an "r" to the beginning, like so: os.startfile(r'C:\path\to\my\file') HTH Mike From mdw at distorted.org.uk Thu Jun 19 11:39:05 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Thu, 19 Jun 2008 15:39:05 +0000 (UTC) Subject: advanced listcomprehenions? References: <717129b5-d92f-4be2-ae6a-037870bfa407@2g2000hsn.googlegroups.com> Message-ID: Duncan Booth wrote: > [['Fizz', 'Buzz', 'FizzBuzz', str(i)][62/(pow(i, 4, 15) + 1)%4] for i in > xrange(1, 101)] Cute! ;-) -- [mdw] From inq1ltd at inqvista.com Sat Jun 14 12:00:20 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Sat, 14 Jun 2008 12:00:20 -0400 Subject: sorting a file In-Reply-To: References: Message-ID: <200806141200.20767.inq1ltd@inqvista.com> On Saturday 14 June 2008 03:15, Beema shafreen wrote: > Hi all, > > I have a file with three columns i need > to sort the file with respect to the third > column. How do I do it uisng python. I > used Linux command to do this. Sort but i > not able to do it ? can any body ssuggest > me I have used this method to solve similar problems. This is a consept of how to do what you want, but you will have to work a little to get it right. You might try something like this; Dict = {} ##create a dictionary make a list of all column3 values for loop colum3 values Make these values the key in a dictionary If the values are long, you can use the first 7 to 15 characters if you want. use this key to equal all the values in the other columns on the same row. Dict[column3] = column1, column2, column3 once the dictionary is made get the dictionary key x = Dict.keys() ## get the keys from Dict x.sort() # produce a sorted list of keys of column3 Loop these sorted keys to extract from the dictionary the values related to each jim-on-linux http://:inqvista.com From workitharder at gmail.com Mon Jun 9 01:41:50 2008 From: workitharder at gmail.com (bukzor) Date: Sun, 8 Jun 2008 22:41:50 -0700 (PDT) Subject: Q re documentation Python style References: Message-ID: On Jun 8, 2:17?pm, kj wrote: > I'm a Perlhead trying to learn the Way of Python. ?I like Python > overall, but every once in a while I find myself trying to figure > out why Python does some things the way it does. ?At the moment > I'm scratching my head over Python's docstrings. ?As far as I > understand this is the standard way to document Python code. ?I > think that's fine for simple functions, but I have some functions > that require a very long docstring to document, and somehow I find > it a bit disconcerting to stick a few screenfuls of text between > the top line of a function definition and its body. ?I guess I'm > still a lot more comfortable with Perl's POD, which allows more > flexibility on the placement of the documentation relative to the > source code. > > I expect that the reply to this quibble about very long docstrings > will be something like: if your function requires several screenfuls > of text to document, then it is too complex or it is doing too > much; refactor it into a collection of simpler functions that will > have shorter docstrings. > > Fair enough. ?In general I agree with this sentiment, except that > I think that sometimes even simple functions require a lot of > documentation. ?For example, I want to document a function that > takes a dictionary as argument, and this dictionary is expected to > have 5 keys. ?(When the number of mandatory arguments gets above > 4, I find that it's too difficult to remember their order, so I > resort to using a dictionary as the single argument.) ?The semantics > for each of these keys needs to be described. ?Plus, of course, I > need to describe what the function returns. ?That's a few screenfuls > right there... > > I guess this is a rambling way to ask: are docstrings *it* as far > Python documentation goes? ?Or is there a second, more flexible > system? > > Then again, I suppose that Python's relative formal rigidity is > considered by many to be a strength. ?Which means that, to be > comfortable with Python, one has to learn to like this (relatively) > rigid structure... > > But I thought I'd ask. ?:) > > Kynn > > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. you can assign a documentation string to the function's .__doc__ attribute. This allows you to place your documentation lower in the script, or higher if you use an extra variable. From Code4Hunter at gmail.com Tue Jun 24 21:30:26 2008 From: Code4Hunter at gmail.com (CodeHunter) Date: Tue, 24 Jun 2008 18:30:26 -0700 (PDT) Subject: how to convert '8868' to u'\u8868' Message-ID: <5268385d-04c7-4726-ab55-0f729ce8d883@a9g2000prl.googlegroups.com> a = '8868' b = u'\u8868' I want to convert a to b who can help me ? thank you very much! From casevh at gmail.com Wed Jun 18 01:08:18 2008 From: casevh at gmail.com (casevh) Date: Tue, 17 Jun 2008 22:08:18 -0700 (PDT) Subject: Multiprecision arithmetic library question. References: Message-ID: <183f26a3-26a2-4cf3-8b21-6e2bff4b9c63@a32g2000prf.googlegroups.com> On Jun 17, 5:13?pm, Michael Press wrote: > I already compiled and installed the GNU multiprecision library > on Mac OS X, and link to it in C programs. > How do I link to the library from Python? > I do not want to download and install redundant material. > (I am new to Python) > > -- > Michael Press GMPY provides the interface between Python and GMP. It is available at http://code.google.com/p/gmpy/downloads/list casevh From fairloophole at gmail.com Thu Jun 5 05:11:35 2008 From: fairloophole at gmail.com (Fair Loophole) Date: Thu, 5 Jun 2008 02:11:35 -0700 (PDT) Subject: BetFair Loophole Message-ID: "How Our Simple Betfair System Turned ?100 Into ?1,123 in Just 7 Days..." Over 1,000 customers can't be wrong: the Only System For 9-to-5ers With Little Capital and Time... Fellow Punter, Have you ever felt that it's impossible to make good money from Betfair? Well, I'm here to tell you that it is possible - but only if you abandon everything you know and focus on a "hidden" Betfair market that 90% of punters have never even noticed existed. You're about to discover how you can clone my "hands-off" Betfair formula, proven to generate as much as ?1100 in 7 days, and designed specifically for Betfair punters who have very little starting capital and full-time jobs. I'm also going to explain to you why 90% of the current systems on the market just don't work for the "average Betfair punter". You see, it took me nearly 3 years of sweat, toil, money and time but it paid off... I finally found and fine tuned a Betfair system that has been proven to generate daily profits of upto ?180: Prove it to yourself 100% risk free - you can paper trade the system first to test it out and if you don't like it or it doesn't do everything we say it does you get your money back, no quibbles, no questions, no hard feelings. A system that fits in perfectly with your 9-5 and can generate profits from a starting bank as small as ?25 - you choose how you much you want to make and when. A system that works because it takes advantage of a "hidden" market on Betfair - you work the system for 10 minutes, and siphon off your daily tax-free profits. It's as simple as that. You need to forget everything you've heard about betting systems because I am about to expose a massive underexploited opportunity that is happening right now on Betfair - an opportunity so significant that it could enable you to earn a second income from home by copying an easy step-by-step blueprint... stay with me.. I'm about to reveal it to you... " 3,000 Students, The Secret to Betfair Success ..." My name is Chris and I have trained up over 3,000 Betfair Punters over the last 3 years, beginner and Betfair pro's alike - using my famed Easy Trader Pro System. Through my EasyTrader site, I have interacted with thousands of punters, allowing me to refine my methods and constantly distil what works on Betfair and why. In short, I understand better than anyone what stands between you and a consistent second income from Betfair. Experience has taught me a few very important things about Betfair (stuff that 90% of punters aren't privvy to) - and so when I say I have discovered the ultimate Betfair opportunity, you should listen closely... Please click below for further details:- http://tubeurl.com/ntkwoy From Scott.Daniels at Acm.Org Mon Jun 23 23:09:32 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 23 Jun 2008 20:09:32 -0700 Subject: Passing arguments to subclasses In-Reply-To: <2tlv54d9efp5tngf51oeadin5e0crh3kai@4ax.com> References: <7pgv54l0pfaa2l05c4l8f3bld1rskd4dtf@4ax.com> <2tlv54d9efp5tngf51oeadin5e0crh3kai@4ax.com> Message-ID: <6K6dnSv0d_qH_v3VnZ2dnUVZ_tvinZ2d@pdx.net> John Dann wrote: > ... the answer might have been of the 'yes, but' kind. Well, if you really care, there is a 'yes, but' answer, but it only has to do with multiple inheritance, and hence is a bit esoteric for the issues you are currently addressing. This is not meant to be a tease; I think it would take pages to address the issue in a comprehensible way for someone who hasn't thought about the issues. If you are curious enough to pursue it, image some issues, design experiments, and see if you can ask a coherent question; if not, "YAGNI" (You Aint Gonna Need It). --Scott David Daniels Scott.Daniels at Acm.Org From tamim.shahriar at gmail.com Mon Jun 2 23:31:57 2008 From: tamim.shahriar at gmail.com (subeen) Date: Mon, 2 Jun 2008 20:31:57 -0700 (PDT) Subject: python blogs References: <19d5037f-837d-4f6b-9e56-d4e6d84b277d@y22g2000prd.googlegroups.com> Message-ID: <40851745-15d0-4963-8219-4f0e93953c03@m45g2000hsb.googlegroups.com> On Jun 3, 8:43 am, Benjamin wrote: > On Jun 2, 1:49 pm, pythonbl... at gmail.com wrote: > > > Hello! > > > It seems like Python blogs are gaining popularity. It seems to me that > > they play a crucial role in promoting Python as a language. > > Do you agree with that? > > > Just a few days ago I've finished setting up a dedicated Python > > blogging environment at:http://www.pythonblogs.com > > Do you think it will be useful for Python community? > > By the way, everyone is welcome to join. > > Thanks very much, but the extension says it's written in PHP! > > > > > Sincerely yours, > > ~pyblog A separate place for python blog - the idea is good. I also think that python blog will help python to be more popular. You can also take a look at my blog: http://love-python.blogspot.com/ and suggest me how to make it better. regards, Subeen. From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 9 05:22:12 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 09 Jun 2008 11:22:12 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <4847d39d$0$7614$426a74cc@news.free.fr> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> Message-ID: <484cf5f6$0$15495$426a74cc@news.free.fr> Russ P. a ?crit : > On Jun 6, 8:25 am, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: > >>>>> I also realize, by the way, that Python allows a client of a class to >>>>> define a new class member from completely outside the class >>>>> definition. Obviously, that cannot be declared private. >>>> Why so ? >>> Why should the client of a class not be able to declare a *private* >>> member of the class? You're kidding, right? >> I'm dead serious. I often add implementation attributes to either a >> class or an instance. These *are* implementation parts, not API. > > If a client accesses a data member of a class, Please stop thinking in C++. This is Python, and all you have are attributes. Whether they're callable of not doesn't change much here. > then by definition that > member is not really private, Who cares about it being "private" ? The important point is that it's *implementation*, not *interface*. > so letting the client create a new data > member and declare it as private seems a bit silly to me. There are two ways to decorate a class or instance object (nb: Python's classes are objects too): the "static" way where you wrap the object in a decorator class or instance and use delegation, and the "dynamic" way where you just modify the original class or object at runtime. The fact that an attribute is added (or replaced) outside the class statement doesn't mean it has to be part of the interface. You sometime have pretty legitimate reason to modify the implementation at runtime. > Actually, > just letting the client create the new data member, private or not, > seems like a bit of a stretch to me, but I'll leave that be. You're way too much in the Java/C++ way of thinking. >>> For the record, I have made it abundantly clear that I don't think >>> Python should not have as rigorous an encapsulation regime as C++ or >>> Java. The worst that could happen with my proposition is that you >>> would need to use a "mangled" name to access private data or methods. >> That's already the case - when you use __name_mangling. And if there's >> no effective access restriction, then what the point of having this >> 'priv' keyword ? >> >>> But you will be using the name many times, you can reassign your own >>> name, of course, so the mangled name need not appear more than once >>> where it is needed. >> Once again, I just don't see the point. Either you want effective access >> restriction in Python, or you don't. And if you don't, what would this >> 'priv' keyword be useful to ? > > In the end, I suppose it boils down to aesthetics and personal > preference. > > The leading-underscore convention bothers me for two reasons: (1) like > the OP, I don't like the way it makes my code look, and (2) it is a > signal to a person reading the code, but it has no actual effect in > the interpreter. Indeed. The target of the signal is definitively the person reading the code. > I think the concept of private data and methods is important enough to > be implemented with more than just a tacky naming convention. The concept of "private" attributes is not important. What's important is the concept of implementation attributes. > That is > why I suggested the "priv" keyword. At the same time, I realize that > people will occasionally be frustrated if they are rigorously denied > access to all private data, which is why I suggested an "indirect" > method of access through mangled names. We already have all this. Either you want language-enforced access restriction - then you might be happier with another language - or you just want to have a clear way to know whether an attribute is part of the API or not - in which case a naming convention is not only enough, but even better. > You can argue that such indirect access defeats the whole idea of > private data, but at least it alerts the client to the fact that he > (or she or it) is accessing private data So does the naming convention, with much less work. > -- and it does so without > using Hungarian notation. I wouldn't label this "hungarian notation" - or at least, not the way "hungarian notation" is now commonly understood. > I would let the "priv" keyword also be used for data or functions at > file scope. It just seems logical to me. Again, some name mangling > convention could be concocted for those who think they really need > access. > > Actually, the whole objection to denied access baffles me a bit. Free your mind from the very peculiar, restricted and IMHO braindead conception of "OO" they taught you with Java and C++. Python is older than Java, it's by now a very very commonly used language on all major platforms, and experience prooves that you just don't need anything more than a simple naming convention. > Does > anyone object to not having access from outside a function to local > variables within the function? I doubt it. The other thing is that the > vast majority of Python software, I would guess, is provided with > source code. How many Python applications or libraries are provided > without source code? If you have the source code, you can obviously > just delete the "priv" keyword anywhere or everywhere it appears. Yes, fine. And then have to maintain a fork of the source code, and distribute it with the application. Honking great idea. doh :-( > And > if you have a major client who insists on access to all the internals, > just delete all occurrences of "priv" before you ship the code (or > don't use it to start with). Or don't even bother about this useless access restriction stuff. Which will save you quite a lot of valuable time. From schickb at gmail.com Tue Jun 24 18:29:52 2008 From: schickb at gmail.com (schickb) Date: Tue, 24 Jun 2008 15:29:52 -0700 (PDT) Subject: Sequence iterators with __index__ Message-ID: I think it would be useful if iterators on sequences had the __index__ method so that they could be used to slice sequences. I was writing a class and wanted to return a list iterator to callers. I then wanted to let callers slice from an iterator's position, but that isn't supported without creating a custom iterator class. Are there reasons for not supporting this generally? I realize not all iterators would have the __index__ method, but that seems ok. In Python 3, maybe this could be called a SequenceIterator -Brad From tjreedy at udel.edu Wed Jun 11 16:51:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Jun 2008 16:51:28 -0400 Subject: My fight with classes :) References: <484fde63_1@news.tm.net.my> Message-ID: "TheSaint" wrote in message news:484fde63_1 at news.tm.net.my... | Hi, | I'm very new with classes. I still reading something around ;) | | I got started to try a concatenation of 2 type of string, which have a | particular property to start with A or D. | | My class here: | """ Small class to join some strings according to the leading first | letter""" You left out the class statement. | def __init__(self): | self.valueA= '' | self.valueD= '' | | def __add__(self, value): I agree with P. Pearson that 'add' methods should generaly not be used for mutation. Certainly, they are generally used to combine two objects of the same or compatible classes, even if the result replaces one of them. This method is equivalent to list.append. | if not isinstance(value, str): return Do you really want to just return None when there is bad input? | if value.lower().startswith('a'): | self.valueA += value | if value.lower().startswith('d'): | self.valueD += value | return self.valueA ,self.valueD List mutation methods return None so one cannot forget that they mutate. In any case, the alternative is to return self. You seem to be returning this tuple because you did not write an __str__ method. Doing two different things in one method is what got you in trouble. So return None or self and add def __str__(self): return self.valueA + ', ' + self.valueB | __call__= __add__ | __iadd__= __add__ This requires that __add__ return self. Better to use .append() and def __iadd__(self, val): self.append(val) return self | my test on the shell: [snip good tests] | >>> k += 'liu' k is now a tuple! Hence the below | >>> k += 'aliu' | Traceback (most recent call last): | File "", line 1, in | TypeError: can only concatenate tuple (not "str") to tuple | >>> k | ('aksaboi', 'daksdhksduboi') | Do I miss something? That augmented assignment is assigment. Always. You are not the first ;-)/ | I'd rather like to avoid class, but a function won't allow me to store so | easily data between several call. Classes are the general mechanism for bundling stored data and functions. You can easily bundle *one* function and stored data with a nested function. def makeappender(): data = ['',''] def appender(val): return appender For multiple functions, use classes. | Mostly I'd expect to pass to the built instance in a more elaborated | function. Then I mean call will be the primer goal. __call__ can be an alias for append just as well as for __add__. Terry Jan Reedy From rentlong at gmail.com Sat Jun 14 03:19:17 2008 From: rentlong at gmail.com (rent) Date: Sat, 14 Jun 2008 00:19:17 -0700 (PDT) Subject: How to sort very large arrays? References: Message-ID: <4e596cda-8f84-46c5-a5df-b7e8d4ab7942@p25g2000pri.googlegroups.com> On Jun 14, 1:54 am, kj wrote: > I'm downloading some very large tables from a remote site. I want > to sort these tables in a particular way before saving them to > disk. In the past I found that the most efficient way to do this > was to piggy-back on Unix's highly optimized sort command. So, > from within a Perl script, I'd create a pipe handle through sort > and then just print the data through that handle: This is a python clone of your code from a python rookie :) from os import popen p = popen("sort -t '\t' -k1,1 -k2,2 -u > %s" % out_file) for line in data: print >> p, line there is no "die $!" here, I think it is good to let python throw the exception to your console > > open my $out, "|$sort -t '\t' -k1,1 -k2,2 -u > $out_file" or die $!; > print $out $_ for @data; > > But that's distinctly Perlish, and I'm wondering what's the "Python > Way" to do this. > > TIA! > > kynn > > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. From arazak73 at yahoo.com.my Wed Jun 25 00:54:13 2008 From: arazak73 at yahoo.com.my (ajak_yahoo) Date: Wed, 25 Jun 2008 12:54:13 +0800 Subject: Send output to printer Message-ID: <013c01c8d67f$869bfea0$1f01a8c0@RAZAK> Need some help from you all, I already manage to write a program to print a packaging label. The output on screen is as below, Part Number : PWEE1111AA Quantity : 100 pcs Lot Number : 10A2008 Customer : ABC Pte. Ltd. My questions is how can I send this output to my Panasonic KX-P1121 dot matric printer, Is it a module that i can used, previously i wrote my program using foxpro 2.6, i have no experience in python. Regards, Ajak -------------- next part -------------- An HTML attachment was scrubbed... URL: From bob at mellowood.ca Mon Jun 16 23:32:57 2008 From: bob at mellowood.ca (bvdp) Date: Mon, 16 Jun 2008 20:32:57 -0700 Subject: Simple and safe evaluator References: <1de31143-7d8e-42e9-ae9d-8b0a0274ddc3@e53g2000hsa.googlegroups.com> Message-ID: sweeneym at acm.org wrote: > On Jun 17, 8:02 am, bvdp wrote: > >> Thanks. That was easy :) >> >>> The change to the _ast version is left as an exercise to the reader ;) >> And I have absolutely no idea on how to do this. I can't even find the >> _ast import file on my system. I'm assuming that the _ast definitions >> are buried in the C part of python, but that is just a silly guess. >> >> Bob. > > If you just need numeric expressions with a small number of functions, > I would suggest checking the expression string first with a simple > regular expression, then using the standard eval() to evaluate the > result. This blocks the attacks mentioned above, and is simple to > implement. This will not work if you want to allow string values in > expressions though. > > import re > def safe_eval( expr, safe_cmds=[] ): > toks = re.split( r'([a-zA-Z_\.]+|.)', expr ) > bad = [t for t in toks if len(t)>1 and t not in safe_cmds] > if not bad: > return eval( expr ) > Yes, this appears to be about as good (better?) an idea as any. Certainly beats writing my own recursive decent parser for this :) And it is not dependent on python versions. Cool. I've run a few tests with your code and it appears to work just fine. Just a matter of populating the save_cmds[] array and putting in some error traps. Piece of cake. And should be fast as well. Thanks!!! Bob. From madhurrajn at gmail.com Mon Jun 9 10:33:06 2008 From: madhurrajn at gmail.com (Madhur) Date: Mon, 9 Jun 2008 07:33:06 -0700 (PDT) Subject: _POSIX_C_SOURCE Message-ID: Hi, I would like to know the difference between using the C_INCLUDE_PATH and using the -I option with compilers. How are they different? The problem which I am facing is that I am having a source base which uses python. I am currently enabling compile time option _POSIX_C_SOURCE in my Makefile. The compilaiton fails if i include -I option to /usr/include/python2.4 /usr/include/python2.4/pyconfig-32.h:838:1: error: "_POSIX_C_SOURCE" redefined but if i do export C_INCLUDE_PATH=/usr/include/python2.4 I do not face any compilation issues. I would like to know if there is anything i am missing on this. Regards, Madhur From python at rcn.com Sun Jun 15 06:16:10 2008 From: python at rcn.com (Raymond Hettinger) Date: Sun, 15 Jun 2008 03:16:10 -0700 (PDT) Subject: marshal.dumps quadratic growth and marshal.dump not allowing file-like objects References: Message-ID: On Jun 15, 1:04?am, bkus... at gmail.com wrote: > However it seems that marshal.dumps() for large objects has a > quadratic performance issue which I'm assuming is that it grows its > memory buffer in constant increments. Looking at the source in http://svn.python.org/projects/python/trunk/Python/marshal.c , it looks like the relevant fragment is in w_more(): . . . size = PyString_Size(p->str); newsize = size + size + 1024; if (newsize > 32*1024*1024) { newsize = size + 1024*1024; } if (_PyString_Resize(&p->str, newsize) != 0) { . . . When more space is needed, the resize operation over-allocates by double the previous need plus 1K. This should give amortized O(1) performance just like list.append(). However, when that strategy requests more than 32Mb, the resizing becomes less aggressive and grows only in 1MB blocks and giving your observed nasty quadratic behavior. Raymond From brian_vanderburg2 at yahoo.com Mon Jun 30 23:09:45 2008 From: brian_vanderburg2 at yahoo.com (Allen) Date: Mon, 30 Jun 2008 23:09:45 -0400 Subject: PyPy questions Message-ID: I read the website of some information about PyPy, and how a translator translates the RPython code to C/CLI/Java/etc to be compiled to a native executable or something like that. Would it be possible, in PyPy, to write such an extension that could easily be compiled to native code from Python code? Is this functionality planned in a future release of it? Also, how is the source distributed (If I opt to use it I will end up compiling it on a system without an initial python install (a scratch linux system)), so does the source include the generated C code? B. Vanderburg II From david at hlacik.eu Wed Jun 4 14:49:32 2008 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Wed, 4 Jun 2008 20:49:32 +0200 Subject: python: error , ('No module named py', ), No module named py Message-ID: Hello, what this beautifull mesage which is messing me whole day means : *python: error , ('No module named py',), No module named py* as a result of class pdg.py which is called from nnrpd_auth.py. To be detailed ... news server inn is calling that when doing autentification , it calls nnrpd_auth.py where instance of my class is hooked into inn , when authentification begins it calls method authenticate(arguments) from pdg. I will provide as many information as needed to solve this mistery, becouse i really need to solve it. Thanks! #!/usr/bin/env python import ldap from nnrpd import syslog class news: server = 'ldap://dev01.net.hlacik.eu' user_dn = 'cn=pdg,ou=Operators,o=Polarion' user_pw = 'Pdg1' connectcodes = { 'READPOST':200, 'READ':201, 'AUTHNEEDED':480, 'PERMDENIED':502 } authcodes = { 'ALLOWED':281, 'DENIED':502 } def newsauth(self,match_username,match_password): base_dn = 'ou=Users,o=Polarion' filter = "(uid=" + match_username + ")" attrs = ['userPassword'] try : l = ldap.initialize(self.server) l.bind_s(self.user_dn, self.user_pw) raw_res = l.search_s( base_dn, ldap.SCOPE_SUBTREE, filter, attrs ) l.unbind() except ldap.SERVER_DOWN: print "Error, server down" return 2 except ldap.INVALID_CREDENTIALS: print "Error, invalid credentials" return 2 except ldap.LDAPError, e: print "Error, %s" % e for results in raw_res: (cn,search) = results for password in search["userPassword"]: if password == match_password: return 1 return 0 def authenticate(self, attributes): # just for debugging purposes syslog('notice', 'nnrpd_auth authenticate() invoked: hostname %s, ipaddress %s, interface %s, user %s' % (\ attributes['hostname'], \ attributes['ipaddress'], \ attributes['interface'], \ attributes['user'])) try: syslog('notice', "result %s" % self.newsauth('boss','bbbb')) except Exception, msg: syslog('notice', "error %s, %s, %s" % (type(msg),msg.args,msg)) # do username passworld authentication #if self.newsauth(attributes['user'], str(attributes['pass'])): # syslog('notice', 'authentication by username succeeded') # return ( self.authcodes['ALLOWED'], 'No error' ) #else: # syslog('notice', 'authentication by username failed') # return ( self.authcodes['DENIED'], 'Access Denied!') ------------------- nnrpd_auth_py : # # This is a sample authentication and authorization module for python # nnrpd hook # # For details, see the file doc/hook-python that came with INN. # # # This file is loaded when one of the python_* readers.conf parameters # is encountered. An instance of AUTH class is passed to nnrpd via # set_auth_hook() function imported from nnrpd. The following methods # of that class are known to nnrpd: # # __init__() - Use this method to initilalize your # general variables or open a common # database connection. May be omitted. # access_init() - Init function specific to access # control. May be omitted # access(attributes) - Called when a python_access # statement is reached in the # processing of readers.conf. Returns # a dictionary of values representing # statements to be included in an # access group. # access_close() - Called on nnrpd termination. Save # your state variables or close a # database connection. May be omitted # authen_init() - Init function specific to # authentication. May be omitted # authenticate(attributes) - Called when a python_auth statement # is reached in the processing of # readers.conf. Returns a response # code, an error string and an # optional string to appear in the # logs as the username. # authen_close() - Called on nnrpd termination. Save # your state variables or close a database # connection. May be omitted # dynamic_init() - Init function specific to # authentication. May be omitted # dynamic(attributes) - Called whenever a reader requests either # read or post access to a # newsgroup. Returns None to grant # access, or a non-empty string (which # will be reported back to reader) # otherwise. # dynamic_close() - Called on nnrpd termination. Save # your state variables or close a database # connection. May be omitted # # If there is a problem with return codes from any of these methods then nnrpd # will die and syslog the exact reason. # # There are also a few Python functions defined in nnrpd: # # set_auth_hook() - Called by nnrpd as this module is loaded. # It is used to pass a reference to an # instance of authentication class to nnrpd. # syslog() - An equivalent replacement for regular syslog. # One consideration for using it is to # uniform nnrpd logging. # # Sample authentication and authorization class. It defines all methods known # to nnrpd. # # Import functions exposed by nnrpd. This import must succeed, or nothing # will work! from nnrpd import * from pdg import * myauth = news() # ...and try to hook up on nnrpd. This would make auth object methods visible # to nnrpd. try: set_auth_hook(myauth) syslog('notice', "authentication module successfully hooked into nnrpd") except Exception, errmsg: syslog('error', "Cannot obtain nnrpd hook for authentication method: %s" % errmsg[0]) -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhamph at gmail.com Mon Jun 9 05:14:53 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 9 Jun 2008 02:14:53 -0700 (PDT) Subject: Trying out safethread patch References: Message-ID: <849dc1ee-ab31-4b85-a521-7406534d6529@x1g2000prh.googlegroups.com> On Jun 8, 9:55 am, s... at pobox.com wrote: > I'd like to take the python-safethread code out for a spin, but I'm not sure > where to start. I downloaded the latest diff: > > http://python-safethread.googlecode.com/files/safethread-bzr-36020.diff > > checked out Python 3.0 from the bzr mirror, then ran patch in the typical > way. That doesn't apply cleanly at all (too much water under the bridge > since this the patch was made). I was thinking if I back up my bzr > repository to r36020, apply the patch then sync with the latest bzr revision > that might work, but I have no bzr experience. I haven't any idea how to do > that. Any suggestions? Yeah, the 36020 in the file name indicates the bzr revision that matches. Going into the branch and using "bzr pull -r 36020" should be sufficient. However, do *not* sync with the latest upstream version after patching - there WILL be conflicts. Dealing with a merge isn't congruent with taking it for a spin. ;) From eatrnr at gmail.com Sat Jun 7 16:05:18 2008 From: eatrnr at gmail.com (eatrnr at gmail.com) Date: Sat, 7 Jun 2008 13:05:18 -0700 (PDT) Subject: Need help porting Perl function References: Message-ID: On Jun 7, 2:42?pm, "Daniel Fetchinson" wrote: > > Hi. ?I'd like to port a Perl function that does something I don't > > know how to do in Python. ?(In fact, it may even be something that > > is distinctly un-Pythonic!) > > > The original Perl function takes a reference to an array, removes > > from this array all the elements that satisfy a particular criterion, > > and returns the list consisting of the removed elements. ?Hence > > this function returns a value *and* has a major side effect, namely > > the target array of the original argument will be modified (this > > is the part I suspect may be un-Pythonic). > > > Can a Python function achieve the same effect? ?If not, how would > > one code a similar functionality in Python? ?Basically the problem > > is to split one list into two according to some criterion. > > This function will take a list of integers and modify it in place such > that it removes even integers. The removed integers are returned as a > new list (disclaimer: I'm 100% sure it can be done better, more > optimized, etc, etc): > > def mod( alist ): > ? ? old = alist[:] > ? ? ret = [ ] > ? ? for i in old: > ? ? ? ? if i % 2 == 0: > ? ? ? ? ? ? ret.append( alist.pop( alist.index( i ) ) ) > > ? ? return ret > > x = range(10,20) > > print x > r = mod( x ) > print r > print x > > HTH, > Daniel > -- > Psss, psss, put it down! -http://www.cafepress.com/putitdown def mod( alist ): return [ alist.pop( alist.index( x ) ) for x in alist if x % 2 == 0 ] alist = range(10,20) blist = mod( alist ) print alist print blist The same thing with list comprehensions. From socyl at 987jk.com.invalid Fri Jun 6 18:00:36 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 6 Jun 2008 22:00:36 +0000 (UTC) Subject: How to send a POST request? Message-ID: Hi. Sorry for this very clueless question, but how does one write in Python an HTTP client that can send a POST request? The modules I've found (e.g. urllib, urllib2), as far as I can tell, seem to be limited to GET requests. (I could be wrong though; please correct me if this is so.) TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From lists at cheimes.de Fri Jun 27 11:47:24 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 27 Jun 2008 17:47:24 +0200 Subject: Use of the "is" statement In-Reply-To: <4865098A.3070502@islandtraining.com> References: <4865098A.3070502@islandtraining.com> Message-ID: Gary Herron wrote: > In short: *never* use "is". Never use "is" unless you want to check "if something is None or something is not None" Christian From mensanator at aol.com Tue Jun 10 19:45:59 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 10 Jun 2008 16:45:59 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> <484ad07b$0$25721$607ed4bc@cv.net> <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> <484b3464$0$25724$607ed4bc@cv.net> <09d98480-c834-42bd-b97f-481133be9cb4@s50g2000hsb.googlegroups.com> <77d2d56a-7ab6-4d33-81d4-b15cc8fc63d6@u36g2000prf.googlegroups.com> Message-ID: On Jun 10, 6:09?pm, Lie wrote: > On Jun 8, 11:11?pm, Mensanator wrote: > > > > > > > On Jun 8, 4:04?am, Lie wrote: > > > > On Jun 8, 8:56?am, Mensanator wrote: > > > > > On Jun 7, 8:22?pm, John Salerno wrote: > > > > > > Mensanator wrote: > > > > > > What I DID say was that how the builtins actually > > > > > > work should be understood and it APPEARED that the > > > > > > OP didn't understand that. Maybe he understood that > > > > > > all along but his example betrayed no evidence of > > > > > > that understanding. > > > > > > Well, the truth is that I know zip truncates to the shorter of the two > > > > > arguments, > > > > > Ok, sorry I thought otherwise. > > > > > > and also in my case the two arguments would always be the > > > > > same length. > > > > > Yes, because you're controlling the source code. > > > > But since lists are mutable, source code literals > > > > don't always control the length of the list. > > > > Since when source code literals ever control the length of a list? > > > Isn't score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] > > considered a literal? > > Yep, but it's not the sole controller of the length of a list. There > are other things that might control the length of the list like del, > append, etc. I believe I just said that. Perhaps I should have said at the instant it's created, the length is determined by the literal. Remember, score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] is preceeded by range(11), so of course AT THAT INSTANT, the lengths match. But, as you say, there's no guarantee that the list lengths will remain unchanged. And that's why I'm saying it isn't necessarily a good idea to assume that. For the way it's used, the zip function IS assuming that. > > > > What controls the length of the list is the semantic meaning of the > > > list, > > > Wha do you mean by that? The list contains 11 objects. > > How could the length be any different? > > What I meant is in some cases (not all) the list might semantically be > nonsense if it is of different length (i.e. it have fixed length). Sure, but remember, the OP was asking how to do this in a list comprehension where he doesn't have the option of iterating through both lists like he does with zip. When I mentioned that could be solved by enumerate, I said it simultaneously guaratees that the index numbers automatically end up the same length as the target list and avoids the hypothetical case where the list lengths somehow don't match. Of course nothing can be done if the actual list length is semantically nonsense and you actually might need to exploit the truncating of the list to a fixed range. But there are many cases where you DON'T want that to happen (if you deposit 5 checks at the bank, you certainly want credit for ALL of them, not just some idiot's notion that only 4 can be deposited in a single transaction.) > > > > in some cases it just makes no sense that the list would ever > > > have different length. > > > And in such case there won't be any problem, will there? > > > Is that a good habit to teach a newbie? To write > > code that only works for special cases? > > I think it is up to the programmer to decide whether special case is > enough or a general case is necessary. Yes, he can certainly decide. Provided he knows what all the options are. There's no way to tell if the OP understands what the options are. I say it's always better to supply too much information than not enough. Assume the reader is clever enough to seperate the wheat from the chaff. If it turns out he's not, then I at least _I_ will be blameless. From socyl at 987jk.com.invalid Sat Jun 7 15:34:05 2008 From: socyl at 987jk.com.invalid (kj) Date: Sat, 7 Jun 2008 19:34:05 +0000 (UTC) Subject: Need help porting Perl function References: Message-ID: >This function will take a list of integers and modify it in place such >that it removes even integers. The removed integers are returned as a >new list Great! Thanks! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From omer at no-log.org Sun Jun 29 15:24:15 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Sun, 29 Jun 2008 21:24:15 +0200 Subject: Function to import module to namespace In-Reply-To: References: Message-ID: <200806292124.15811.omer@no-log.org> Le Sunday 29 June 2008 21:08:36 bvdp, vous avez ?crit?: > Is it possible to do this from a function: import a module and append > the defs in that module to an existing module/namesapce. > > So, in my code I have something like: > > # main code > import mods > > def loadmore(n): > import_module(n, mods) > > .... > # end of main > > this will permit the addition of the the stuff in file 'n.py' to 'mods'. > > Assuming that foo1() is defined in newmod, I should now be able to do > something like mods.foo1(). > You can dynamically add objects to a module: >>> import os >>> os.foo = 'bar' >>> os.foo 'bar' >>> setattr(os, 'foo2', 'bar2') >>> os.foo2 'bar2' and for the loading part you can use the __import__ builtin or maybe execfile (see the 'built-in functions' chapter of the library reference for more about these). -- C?dric Lucantis From __peter__ at web.de Thu Jun 12 10:03:39 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Jun 2008 16:03:39 +0200 Subject: Plotting Graphs using Gnuplot References: <17f71342-0cc4-4eea-b99a-668096302b8b@a70g2000hsh.googlegroups.com> Message-ID: arslanburney at gmail.com wrote: > Hello. Was trying to create a simple plotting function. Wasnt working > however. If i write the same code without putting it inside a function > it works. :S. Could some1 tell me the problem? Judging from the demo you have to keep a Gnuplot.Gnuplot instance alive. If you don't, the display window is immediately garbage-collected. > Heres the code: > > > # File name Plotting2 > > import Gnuplot > > def plot(original, expected, actual): > > > if type (original) != type([]): > return False > > else: > > gp = Gnuplot.Gnuplot() > gp('set data style lines') > > > # Make the plot items > plot1 = Gnuplot.PlotItems.Data(original, title="Original") > plot2 = Gnuplot.PlotItems.Data(expected, title="Expected") > plot3 = Gnuplot.PlotItems.Data(actual, title="Acutal") > > gp.plot(plot1, plot2, plot3) return gp > > > ---- > > import Plotting2 #The name of my file... > gp = Plotting2.plot( [(2,3), (3,4)], [(4,5), (5,6)], [(1,3), (4,8)] ) raw_input() By the way, I recommend that you raise an Exception instead of returning a special value when plot() cannot deal with the arguments passed to it. Peter From cmpython at gmail.com Sun Jun 8 23:24:50 2008 From: cmpython at gmail.com (CM) Date: Sun, 8 Jun 2008 20:24:50 -0700 (PDT) Subject: How to close app after x seconds. References: Message-ID: <6f16a047-32ea-4e72-9870-1f80f7673f55@8g2000hse.googlegroups.com> On Jun 8, 8:51 pm, ralphz wrote: > Hi > > I have small app that I want to close tself after x seconds. Basically > start show some message and close. > > I come up with something like this but it does not work. Can anyone help > me with it? > > #!/usr/bin/env python > > import wx > import time > > class MyFrame(wx.Frame): > def __init__(self, title, pos, size): > wx.Frame.__init__(self, None, -1, title, pos, size) > self.CreateStatusBar() > self.SetStatusText("Some message here") > > class MyApp(wx.App): > def OnInit(self): > > self.frame = MyFrame('TITLE', (100, 100), (400,100)) > self.frame.Show() > > self.SetTopWindow(self.frame) > self.ID_Timer = wx.NewEventType() > self.timer = wx.Timer(self, self.ID_Timer) > self.timer.Start(5000, False) > self.Bind(wx.EVT_TIMER, self.appclose, self.timer) > # wx.EVT_TIMER(self, self.ID_Timer, self.appclose) > return True > > def appclose(self, evt): > self.frame.Destroy() > > if __name__ == '__main__': > app = MyApp(0) > app.MainLoop() > > Ralphhttp://TheOrangeIT.org It works for me just fine. How is it not working for you? By the way, showing your message in the statusbar is not a good display method--it's small and it is only seen in conjunction with a frame above it that is doing something. You could just put the message as staticText. From mail at timgolden.me.uk Fri Jun 13 06:44:29 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 13 Jun 2008 11:44:29 +0100 Subject: How to set directory in save as combo box In-Reply-To: <000a01c8cd11$c5566210$2fc513ac@pwit.com> References: <000a01c8cd11$c5566210$2fc513ac@pwit.com> Message-ID: <48524F8D.4040406@timgolden.me.uk> Couple of things, Gopal, which you might want to remember when posting to mailing lists etc. One is that it's *much* better (and more considerate) to post in plain text, not in HTML. (You should be able to tell Outlook to use plain text). *Especially* when posting code. And even *more* especially when posting Python code where the layout is uber-important. The other thing is that top-posting is not the norm in this group, although it may be in others. The usual thing is to trim the email you're replying to (or the newsgroup post or GGroup entry) so that only the relevant text remains, and then put your replies beneath or interspersed depending on what makes sense. Now to the code itself: > I am trying to save a file, it is working fine. > > But if the file is not on the foreground while setting combo box > directory, changing the value in the combo box by setLookIn() appear on > the foreground window. [... snip code which finds a "Save As" window and sends it mouse messages ...] I'm honestly not sure what you're trying to achieve here. I assumed that *your* application was initiating the "Save As..." dialog. But this code looks as though you're trying to automate some *other* application's dialog box. Can you explain better what's going on? Trying to poke values into other application's windows is fragile at best, but if that's really what you want to do, have a look at a couple of projects which specialise in that kind of thing: + WATSUP: http://www.tizmoi.net/watsup/intro.html + PyWinAuto: http://pywinauto.openqa.org/ Trying to poke values into *your own* application's windows is entirely suspect: there's almost certainly a better way of doing it. TJG From nick at craig-wood.com Tue Jun 24 08:32:12 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 24 Jun 2008 07:32:12 -0500 Subject: calling a .exe from Python References: Message-ID: evidentemente.yo wrote: > Hi, i am trying to call a .exe from my .py file, i have found the exec > function, but i'm not sure of how to use it:S > > would it be f.e.: > > execl (mypath/myfile.exe,myfile,arg1,arg2,...) > > ???? > > Another question is, when i call my .exe with exec, i understand that > my .py file will stop running, and instead the new process will be > launched instead of it. Is it true? > Is there a way to launch my .exe without finishing my .py file?? > > thank you very much:) Probably what you want is this... from subprocess import call rc = call(["mypath/myfile.exe",arg1,arg2]) rc will contain the exit status See the subprocess module for more things you can do -- Nick Craig-Wood -- http://www.craig-wood.com/nick From fc14301589 at icqmail.com Wed Jun 11 10:28:04 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Wed, 11 Jun 2008 22:28:04 +0800 Subject: can't assign to literal References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> <1a244dc4-4d10-491d-8ec7-224f3a1f0df5@m73g2000hsh.googlegroups.com> <8264ea7d-50ce-4fac-9b59-1acbcbafcbb2@w7g2000hsa.googlegroups.com> Message-ID: <484fe17d_2@news.tm.net.my> On 16:47, mercoled? 11 giugno 2008 Chris wrote: > SciTE and Notepad++ Pype, spe, just to point it out. Jedit, but rather a bloatware. I'd like to know which is the litest multi platform and indipendent. Pype is very good when compiled in exe, but not doing in Linux in that way. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From apardon at forel.vub.ac.be Wed Jun 4 03:08:45 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Jun 2008 07:08:45 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <2930ad39-a3ef-49fa-9e37-26ada87f2d95@m44g2000hsc.googlegroups.com> Message-ID: On 2008-06-03, sturlamolden wrote: > On Jun 2, 12:40 pm, Antoon Pardon wrote: > >> I think you completed missed the point. >> >> This is just a proof of concept thing. In a real example there would >> of course no Set en Get methods but just methods that in the course >> of their execution would access or update the hidden attributes > > I have to agree with Banks here, you have not provided an example of > data hiding. It does not discriminate between attribute access from > within and from outside the class. You just assume that the attribute > named 'hidden' will be left alone. Also naming it hidden is stupid as > it is visible. No I don't assume that hidden wil be left alone. hidden is a free variable in a closure and thus simply can't be accessed except by local functions that were made accessible (and some mechanism dependant on the CPython implementation). > What you need is a mechanism that will thrown an exception whenever an > attribue is accessed from outside the class, but not from inside. And my example does this. It threw an AttributeError > The mechanism must also be impossible to override with additional > code. Which as far as I know it is. -- Antoon Pardon From george.sakkis at gmail.com Fri Jun 20 13:07:56 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 20 Jun 2008 10:07:56 -0700 (PDT) Subject: Python "is" behavior References: <02d58c63-f8d8-44a8-ac09-d483a0fa8c0f@v1g2000pra.googlegroups.com> <725bcf7a-3d6a-4a38-a906-bb397bdd447f@26g2000hsk.googlegroups.com> <03a030b7-1d47-4386-9826-435ce936c130@p39g2000prm.googlegroups.com> Message-ID: <537daeff-e283-47bf-b539-3e6c99aabe5a@m45g2000hsb.googlegroups.com> On Jun 20, 12:45 pm, michalis.avr... at gmail.com wrote: > On Jun 20, 9:42 am, George Sakkis wrote: > > > > > On Jun 20, 12:31 pm, michalis.avr... at gmail.com wrote: > > > > I am not certain why this is the case, but... > > > > >>> a = 256 > > > >>> b = 256 > > > >>> a is b > > > > True > > > > >>> a = 257 > > > >>> b = 257 > > > >>> a is b > > > > False > > > > Can anyone explain this further? Why does it happen? 8-bit integer > > > differences? > > > No, implementation-dependent optimization (caching). For all we know, > > the next python version may cache up to 1024 or it may turn off > > caching completely; do not rely on it. More generally, do not use 'is' > > when you really mean '=='. > > > George > > Thank you George. I am very curious about some of these internal > Python things that I keep stumbling upon through friends. And thank > you for all the help! As far it's plain curiosity it's ok, but it's a small implementation detail you shouldn't rely on. There's nothing magic about 256, just the size decided for 2.5. If you tried it on 2.4 you'd get: Python 2.4.2 (#1, Mar 8 2006, 13:24:00) [GCC 3.4.4 20050721 (Red Hat 3.4.4-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a=99 >>> b=99 >>> a is b True >>> a=100 >>> b=100 >>> a is b False I was more surprised by the following: Python 2.5.1 (r251:54863, May 8 2007, 14:46:30) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a= 123456; b=123456; a is b True For some reason, stacking multiple statements reuses the same object. George From rhamph at gmail.com Tue Jun 10 15:27:52 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Tue, 10 Jun 2008 12:27:52 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <6e6df35e-e641-44d9-9f56-c0732306eec2@q27g2000prf.googlegroups.com> Message-ID: <98ce48ed-c7c7-43c5-8c9c-f08628a2e98e@y22g2000prd.googlegroups.com> On Jun 10, 1:55 am, Antoon Pardon wrote: > On 2008-06-09, Rhamphoryncus wrote: > > > > > On Jun 9, 5:33 am, Antoon Pardon wrote: > >> On 2008-06-07, Rhamphoryncus wrote: > > >> > On Jun 6, 12:44 pm, The Pythonista wrote: > >> >> It's always been my understanding that you can't forcibly kill a thread > >> >> in Python (at least not in a portable way). The best you can do is > >> >> politely ask it to die, IIRC. > > >> > Inherently, the best you can do in most languages is ask them politely > >> > to die. Otherwise you'll leave locks and various other datastructures > >> > in an inconvenient state, which is too complex to handle correctly. > >> > The exception is certain functional languages, which aren't capable of > >> > having threads and complex state in the same sense. > > >> Well it would of course depend on what is considered asking politely? > > >> If one thread could cause an exception being thrown in an other thread, > >> would this be considered a polite way to ask? Would it be considered > >> an acceptable way? > > > The exception must not be raised until a point explicitly designed as > > safe is hit. Otherwise, any function that manipulates data you'll > > still use will potentially be buggered. Consider sys.stdout: codecs, > > buffering, lots to go wrong. > > I don't see the point. Exceptions are raised now without the ability > of an explicitly designed safe point. If something unexpected happens > your code can raise an exception and leave your data buggered too if > you didn't anticipate it propely. Although in theory you could get any exception at any point, in practise you shouldn't unless your program is broken. If it is broken the exceptions shouldn't be caught and should cause the program to terminate, so the harm is reduced. The exceptions that should happen (such as IOError) should be from predicted points, and anticipated. A notable exception is MemoryError, which can show up from anywhere at any time. Nobody's come up with a solution to that one, so we usually just let the program die. Cancelling a thread implies your program will continue. Otherwise you'd just exit the whole process (either via _exit() or via daemon threads.) From armin.ronacher at active-4.com Wed Jun 18 06:47:44 2008 From: armin.ronacher at active-4.com (Armin Ronacher) Date: Wed, 18 Jun 2008 10:47:44 +0000 (UTC) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <4856e80c$0$30401$9b622d9e@news.freenet.de> <2d1e9b84-3dc7-4822-9c61-73991a527c67@s50g2000hsb.googlegroups.com> <48574b41$0$30410$9b622d9e@news.freenet.de> <31defced-c60d-45dc-a32a-af01a2b84c89@2g2000hsn.googlegroups.com> <48583bf9$0$14752$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis v.loewis.de> writes: > > > I think I have lost the thread here, sorry. So I explain again what I > > mean. I think for this data structure it's important to keep all the > > normal dict operations at the same speed. If you use a C > > implementation vaguely similar to my pure python recipe you can > > perform the del in O(1) too, because pairs are joined in (double) > > linked list. But such data structure is O(n) to find the n-th item > > inserted into the sequence. > > Right. So byindex(n) would be O(n) then, right? If so, what's the > purpose of having that method in the first place? What's the purpose of having list.insert? > The PEP doesn't give a rationale, but just proposes that the method > be there. My guess is that it includes it for performance reasons. > However, I think the PEP (author) is misguided in assuming that > making byindex() a method of odict, you get better performance than > directly doing .items()[n] - which, as you say, you won't. Without byindex the only way to cherry pick an item is either doing something like i = od.iteritems() for idx in xrange(offset): value = idx.next() return value Or return od.items()[offset] One creates tons of unnecessary method calls, the other creates a full blown list object just to throw it away later. Both less than optimal solutions that can be implemented in a more efficient way on the C layer where one only has to iterate over the linked list offset times and return the item. And iteration for that linked list is most likely something like "for (n = 0; n != offset; ++n) iter = iter->next". Regards, Armin From ananth99899 at gmail.com Fri Jun 20 12:07:23 2008 From: ananth99899 at gmail.com (www.hollywoodpopstars.blogspot.com) Date: Fri, 20 Jun 2008 09:07:23 -0700 (PDT) Subject: secret WEB CAMS at LADIES HOTELS Message-ID: Hi....Friends, watch and enjoy SECRET WEB-CAMS at LADIES HOSTELS and INTERNET CAFE SEX SCANDALS VIDEOS... http://www.hollywoodpopstars.blogspot.com http://www.googlemobilesphones.blogspot.com From pfreixes at milnou.net Sun Jun 8 06:07:26 2008 From: pfreixes at milnou.net (Pau Freixes) Date: Sun, 8 Jun 2008 12:07:26 +0200 Subject: Different execution time in python code between embedded or standalone In-Reply-To: <207312b70806031258n68b9dfl942e098e5119c1dc@mail.gmail.com> References: <207312b70806031258n68b9dfl942e098e5119c1dc@mail.gmail.com> Message-ID: <207312b70806080307m92fa477s83e9e4d4521b444d@mail.gmail.com> HI list, I found the problem guys, when I embedded python code didn't call to PyEval_InitThreads(); This function initialize GIL and other data structures for do a python code thread safe. I believe the python traditional ( python name_script.py ) run always a thread safe interpreter. Therefore, it's normal found best performance in no thread safe environment and thread safe environment. But I have a small question, if I have a typical PyObject_CallObject environment and main code don't call to PyEval_InitThreads() after Py_Initialize(), if in python code function called launch some threads this interpreter will be prepare for handle more one thread with python thread safe environment, can everybody help me ? Thks On Tue, Jun 3, 2008 at 9:58 PM, Pau Freixes wrote: > Hi list, > > First Hello to all, this is my and hope not end message to the list :P > > This last months I have been writting a program in c like to mod_python > for embedding python language, it's a middleware for dispatch and execute > python batch programs into several nodes. Now I'm writing some python > program for test how scale this into several nodes and comparing with > "standalone" performance. > > I found a very strange problem with one application named md5challenge, > this aplication try to calculate the max number md5 digest in several > seconds, md5challenge use a simple signal alarm for stop program when time > has passed. This is the code of python script > > def handler_alrm(signum, frame): > global _signal > global _nrdigest > global _f > > > _signal = True > > def try_me(): > global _nrdigest > global _f > global _signal > > _f = open("/dev/urandom","r") > while _signal is not True: > buff = _f.read(_const_b) > md5.md5(buff).hexdigest() > _nrdigest = _nrdigest + 1 > > if _f is not None : > _f.close() > > def main( req ): > global _nrdigest > > > signal.signal(signal.SIGALRM, handler_alrm) > signal.alarm(req.input['time']) > > > try_me() > > req.output['count'] = _nrdigest > > return req.OK > > > if __name__ == "__main__": > > # test code > class test_req: > pass > > req = test_req() > req.input = { 'time' : 10 } > req.output = { 'ret' : 0, 'count' : 0 } > req.OK = 1 > > main(req) > > print "Reached %d digests" % req.output['count'] > > > When I try to run this program in standalone into my Pentium Dual Core > md4challenge reached 1.000.000 milion keys in 10 seconds but when i try to > run this in embedded mode md5challenge reached about 200.000 more keys !!! I > repeat this test many times and always wins embedded mode !!! What's > happen ? > > Also I tested to erase read dependencies from /dev/random, and calculate > all keys from same buffer. In this case embedded mode win always also, and > the difference are more bigger !!! > > Thks to all, can anybody help to me ? > -- > Pau Freixes > Linux GNU/User -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Mon Jun 2 00:38:29 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 02 Jun 2008 05:38:29 +0100 Subject: Better performance References: <14a9bf9c-1605-43a1-a6ad-8720c3df06d9@c58g2000hsc.googlegroups.com> Message-ID: Franck Y writes: > Hello Folks, > > I am facing a problem where i need to parse around 200 files, i have a > bit of knowledge in PHP/Perl/Python (the magic P :-P) > > Which one would you suggest me since i have to generate a web > interface ? > And each one has his area of 'work' > > > Thanks for your help ! Python, of course. -- Arnaud From duncan.booth at invalid.invalid Tue Jun 3 04:13:03 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Jun 2008 08:13:03 GMT Subject: Code correctness, and testing strategies References: Message-ID: jacob at cd.chalmers.se (Jacob Hallen) wrote: > The most important aspect of usnit testing is actually that it makes > the code testable. This may sound lik an oxymoron but it is actually a > really important property. Testable code has to have a level of > modularity as well as simplicity and clarity in its interfaces that > you will not achieve in code that lacks automated unit tests. Excellent clear description, thanks Jacob. I made the mistake at one point when I was trying to sell the concept of TDD telling the people I was trying to persuade that by writing the tests up front it influences the design of the code. I felt the room go cold: they said the customer has to sign off the design before we start coding, and once they've signed it off we can't change anything. I wish I'd had your words then. -- Duncan Booth http://kupuguy.blogspot.com From noreply at yahoo.com Wed Jun 25 11:20:04 2008 From: noreply at yahoo.com (Kirk) Date: 25 Jun 2008 15:20:04 GMT Subject: Freeze problem with Regular Expression Message-ID: <6cf614F3f8ocoU1@mid.individual.net> Hi All, the following regular expression matching seems to enter in a infinite loop: ################ import re text = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA) una ' re.findall('[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-z]*\s*(?:[0-9] *[A-Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$', text) ################# No problem with perl with the same expression: ################# $s = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA) una '; $s =~ /[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-z]*\s*(?:[0-9]*[A- Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$/; print $1; ################# I've python 2.5.2 on Ubuntu 8.04. any idea? Thanks! -- Kirk From frigoris.ma at gmail.com Wed Jun 18 21:01:55 2008 From: frigoris.ma at gmail.com (Cong) Date: Wed, 18 Jun 2008 18:01:55 -0700 (PDT) Subject: Looking for lots of words in lots of files References: Message-ID: <38ccf4ff-aa9e-4fda-8fce-bebf85ae96de@q27g2000prf.googlegroups.com> On Jun 18, 11:01?pm, Kris Kennaway wrote: > Calvin Spealman wrote: > > Upload, wait, and google them. > > > Seriously tho, aside from using a real indexer, I would build a set of > > thewordsI'mlookingfor, and then loop over each file, looping over > > thewordsand doing quick checks for containment in the set. If so, add > > to a dict of file names to list ofwordsfound until the list hits 10 > > length. I don't think that would be a complicated solution and it > > shouldn't be terrible at performance. > > > If you need to run this more than once, use an indexer. > > > If you only need to use it once, use an indexer, so you learn how for > > next time. > > If you can't use an indexer, and performance matters, evaluate using > grep and a shell script. ?Seriously. > > grep is a couple of orders of magnitude faster at pattern matching > strings infiles(and especially regexps) than python is. ?Even if you > are invoking grep multiple times it is still likely to be faster than a > "maximally efficient" single pass over the file in python. ?This > realization was disappointing to me :) > > Kris Alternatively, if you don't feel like writing shell scripts, you can write a Python program which auto-generate the desired shell script which utilizes grep. E.g. use Python for generating the file list which is passed to grep as arguments. ;-P From pavel.uvarov at gmail.com Mon Jun 2 11:09:35 2008 From: pavel.uvarov at gmail.com (pavel.uvarov at gmail.com) Date: Mon, 2 Jun 2008 08:09:35 -0700 (PDT) Subject: ThreadPoolingMixIn References: <3d9dac72-ce4d-4ce5-9213-4bb17aff2f9e@r66g2000hsg.googlegroups.com> <1c4d113e-b375-471d-9d54-1401c8844352@t12g2000prg.googlegroups.com> Message-ID: On May 31, 9:13 pm, Rhamphoryncus wrote: > On May 30, 2:40 pm, pavel.uva... at gmail.com wrote: > > > Hi, everybody! > > > I wrote a useful class ThreadPoolingMixIn which can be used to create > > fast thread-based servers. This mix-in works much faster than > > ThreadingMixIn because it doesn't create a new thread on each request. > > Do you have any benchmarks demonstrating the performance difference/ > To benchmark this I used a simple tcp server which writes a small (16k) string to the client and closes the connection. I started 100 remote clients and got 500 replies/s for ThreadingMixIn and more than 1500 replies/s for ThreadPoolingMixIn. I tested it on FreeBSD 6.2 amd64. I'm very curious about the exactness of the number 500 for ThreadingMixIn. It seems to be the same for various packet sizes. I suspect there is some OS limit on thread creating rate. Below I include a bugfixed ThreadPoolingMixIn and the benchmarking utility. The utility can be used to start clients on localhost, though the reply rate will be slower (around 1000 replies/s). To start benchmarking server with localhost clients use: python ./TestServer.py --server=threading --n-clients=100 or python ./TestServer.py --server=threadpooling --n-clients=100 #------- ThreadPoolingMixIn.py from __future__ import with_statement from SocketServer import ThreadingMixIn import threading import Queue class ThreadPoolingMixIn(ThreadingMixIn): """Mix-in class to handle requests in a thread pool. The pool grows and thrinks depending on load. For instance, a threadpooling TCP server class is created as follows: class ThreadPoolingUDPServer(ThreadPoolingMixIn, TCPServer): pass """ __author__ = 'Pavel Uvarov ' def init_thread_pool(self, min_workers = 5, max_workers = 100, min_spare_workers = 5): """Initialize thread pool.""" self.q = Queue.Queue() self.min_workers = min_workers self.max_workers = max_workers self.min_spare_workers = min_spare_workers self.num_workers = 0 self.num_busy_workers = 0 self.workers_mutex = threading.Lock() self.start_workers(self.min_workers) def start_workers(self, n): """Start n workers.""" for i in xrange(n): t = threading.Thread(target = self.worker) t.setDaemon(True) t.start() def worker(self): """A function of a working thread. It gets a request from queue (blocking if there are no requests) and processes it. After processing it checks how many spare workers are there now and if this value is greater than self.min_spare_workers then the worker exits. Otherwise it loops infinitely. """ with self.workers_mutex: self.num_workers += 1 while True: (request, client_address) = self.q.get() with self.workers_mutex: self.num_busy_workers += 1 self.process_request_thread(request, client_address) self.q.task_done() with self.workers_mutex: self.num_busy_workers -= 1 if (self.num_workers > self.min_workers and self.num_workers - self.num_busy_workers > self.min_spare_workers): self.num_workers -= 1 return def process_request(self, request, client_address): """Puts a request into queue. If the queue size is too large, it adds extra worker. """ self.q.put((request, client_address)) with self.workers_mutex: if self.q.qsize() > 3 and self.num_workers < self.max_workers: self.start_workers(1) def join(self): """Wait for all busy threads""" self.q.join() #------- TestServer.py from __future__ import with_statement from SocketServer import * import socket import sys import threading import time import os from ThreadPoolingMixIn import * class ThreadPoolingTCPServer(ThreadPoolingMixIn, TCPServer): pass class TestServer(ThreadingTCPServer): allow_reuse_address = True request_queue_size = 128 def __init__(self, server_address, RequestHandlerClass, packet_size): TCPServer.__init__(self, server_address, RequestHandlerClass) self.packet_size = packet_size self.sum_t = 0 self.total_num_requests = 0 self.num_requests = 0 self.t0 = time.time() self.lock = threading.Lock() def reset_stats(self): with self.lock: self.total_num_requests += self.num_requests self.num_requests = 0 self.sum_t = 0 self.t0 = time.time() def update_stats(self, t0, t1): with self.lock: self.num_requests += 1 self.sum_t += t1 - t0 n = self.num_requests sum_t = self.sum_t avg_t = sum_t / n rate = n / (t1 - self.t0) return (n, avg_t, rate) def handle_request(self): """Handle one request, possibly blocking.""" try: request, client_address = self.get_request() except KeyboardInterrupt: raise except socket.error: return if self.verify_request(request, client_address): try: self.process_request(request, client_address) except KeyboardInterrupt: raise except: self.handle_error(request, client_address) self.close_request(request) class TestServerThreadPool(ThreadPoolingMixIn,TestServer): def __init__(self, server_address, RequestHandlerClass, packet_size): TestServer.__init__(self, server_address, RequestHandlerClass, packet_size) self.init_thread_pool(2, 200, 20) class TestRequestHandler(StreamRequestHandler): def __init__(self, request, client_address, server): self.t0 = time.time() StreamRequestHandler.__init__(self, request, client_address, server) def handle(self): self.wfile.write('a'*(self.server.packet_size)) t1 = time.time() (n, avg_t, rate) = self.server.update_stats(self.t0, t1) if n % 10000 == 0: print('rate=%.2f ' % rate) self.server.reset_stats() from optparse import OptionParser def server(o): HandlerClass = TestRequestHandler if o.server == "threading": ServerClass = TestServer elif o.server == "threadpooling": ServerClass = TestServerThreadPool else: return server_address = ('', o.port) try: srv = ServerClass(server_address, HandlerClass, o.packet_size) sa = srv.socket.getsockname() print "Serving on", sa[0], "port", sa[1], "..." srv.serve_forever() except Exception, val: print "Exception: %s" % str(val) raise def client(o): for f in xrange(0,o.n_clients): if os.fork(): while True: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("localhost",o.port)) while len(sock.recv(4096)): pass sock.close() except Exception, val: print val time.sleep(1) if __name__ == '__main__': args = sys.argv[1:] usage = "usage: %prog [options]" parser = OptionParser(usage) parser.add_option( "-p", "--port", help="Server port", type="int", default=8123 ) parser.add_option( "", "--n-clients", help="Number of client forks", type="int", default=0 ) parser.add_option( "", "--server", help="Type of the server (threading or threadpooling)", type="string", default="" ) parser.add_option( "", "--packet-size", help="Packet size", type="int", default=16*1024 ) (o,a) = parser.parse_args(args) if os.fork() == 0: server(o) else: client(o) From martin at v.loewis.de Thu Jun 26 12:46:39 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 26 Jun 2008 18:46:39 +0200 Subject: Bind compiled code to name? In-Reply-To: References: <485e9aea$0$637$9b622d9e@news.freenet.de> Message-ID: <4863c7ef$0$25963$9b622d9e@news.freenet.de> >> d = {} >> exec source_code in d >> some_name = d['some_name'] > > This works quite well! I can't believe after googling for half on hour I > didn't notice this "exec ... in ..." syntax. > One more thing though, is there a way to access "some_name" as a > attribute, instead as a dictionary: > > some_name = d.some_name Sure: class D:pass d = D() exec source_code in d.__dict__ print d.some_name Notice that this will also give you d.__builtins__, which you might want to del afterwards. Regards, Martin From circularfunc at yahoo.se Fri Jun 27 22:17:35 2008 From: circularfunc at yahoo.se (defn noob) Date: Fri, 27 Jun 2008 19:17:35 -0700 (PDT) Subject: Pygame, how to show window without loop? no loop=popupand close... Message-ID: <8ecb6375-356a-4e73-be21-18ffe0f5c4f2@r66g2000hsg.googlegroups.com> Im using PyGame to draw images of graphs and trees. Howver right now i am looping using: while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() screen.fill(screencolor) pygame.draw.circle(screen, linecolor, (500, 20), 12, 0) draw((500, 20), 3) pygame.display.flip() if i do screen.fill(screencolor) pygame.draw.circle(screen, linecolor, (500, 20), 12, 0) draw((500, 20), 3) pygame.display.flip() it just pops up and closes. how can i make it stay until i close it without using a loop? From alexnbryan at gmail.com Fri Jun 27 19:28:56 2008 From: alexnbryan at gmail.com (Alexnb) Date: Fri, 27 Jun 2008 16:28:56 -0700 (PDT) Subject: using urllib2 In-Reply-To: References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> Message-ID: <18165634.post@talk.nabble.com> I have read that multiple times. It is hard to understand but it did help a little. But I found a bit of a work-around for now which is not what I ultimately want. However, even when I can get to the page I want lets say, "Http://dictionary.reference.com/browse/cheese", I look on firebug, and extension and see the definition in javascript,

1.the curd of milk separated from the whey and prepared > >> in > >> >> many ways as a food.
Jeff McNeil-2 wrote: > > > the problem being that if I use code like this to get the html of that > page in python: > > response = urllib2.urlopen("the webiste....") > html = response.read() > print html > > then, I get a bunch of stuff, but it doesn't show me the code with the > table that the definition is in. So I am asking how do I access this > javascript. Also, if someone could point me to a better reference than the > last one, because that really doesn't tell me much, whether it be a book > or anything. > > > > I stumbled across this a while back: > http://www.voidspace.org.uk/python/articles/urllib2.shtml. > It covers quite a bit. The urllib2 module is pretty straightforward > once you've used it a few times. Some of the class naming and whatnot > takes a bit of getting used to (I found that to be the most confusing > bit). > > On Jun 27, 1:41 pm, Alexnb wrote: >> Okay, I tried to follow that, and it is kinda hard. But since you >> obviously >> know what you are doing, where did you learn this? Or where can I learn >> this? >> >> >> >> >> >> Maric Michaud wrote: >> >> > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit : >> >> I have never used the urllib or the urllib2. I really have looked >> online >> >> for help on this issue, and mailing lists, but I can't figure out my >> >> problem because people haven't been helping me, which is why I am >> here! >> >> :]. >> >> Okay, so basically I want to be able to submit a word to >> dictionary.com >> >> and >> >> then get the definitions. However, to start off learning urllib2, I >> just >> >> want to do a simple google search. Before you get mad, what I have >> found >> >> on >> >> urllib2 hasn't helped me. Anyway, How would you go about doing this. >> No, >> >> I >> >> did not post the html, but I mean if you want, right click on your >> >> browser >> >> and hit view source of the google homepage. Basically what I want to >> know >> >> is how to submit the values(the search term) and then search for that >> >> value. Heres what I know: >> >> >> import urllib2 >> >> response = urllib2.urlopen("http://www.google.com/") >> >> html = response.read() >> >> print html >> >> >> Now I know that all this does is print the source, but thats about all >> I >> >> know. I know it may be a lot to ask to have someone show/help me, but >> I >> >> really would appreciate it. >> >> > This example is for google, of course using pygoogle is easier in this >> > case, >> > but this is a valid example for the general case : >> >> >>>>[207]: import urllib, urllib2 >> >> > You need to trick the server with an imaginary User-Agent. >> >> >>>>[208]: def google_search(terms) : >> > return >> urllib2.urlopen(urllib2.Request("http://www.google.com/search?" >> > + >> > urllib.urlencode({'hl':'fr', 'q':terms}), >> > headers={'User-Agent':'MyNav >> > 1.0 >> > (compatible; MSIE 6.0; Linux'}) >> > ).read() >> > .....: >> >> >>>>[212]: res = google_search("python & co") >> >> > Now you got the whole html response, you'll have to parse it to recover >> > datas, >> > a quick & dirty try on google response page : >> >> >>>>[213]: import re >> >> >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

> class=r>.*?

', >> > res) ] >> > ...[229]: >> > ['Python Gallery', >> > 'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des Monty >> ...', >> > 'Re: os x, panther, python & co: msg#00041', >> > 'Re: os x, panther, python & co: msg#00040', >> > 'Cardiff Web Site Design, Professional web site design services ...', >> > 'Python Properties', >> > 'Frees < Programs < Python < Bin-Co', >> > 'Torb: an interface between Tcl and CORBA', >> > 'Royal Python Morphs', >> > 'Python & Co'] >> >> > -- >> > _____________ >> >> > Maric Michaud >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> -- >> View this message in >> context:http://www.nabble.com/using-urllib2-tp18150669p18160312.html >> Sent from the Python - python-list mailing list archive at Nabble.com. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/using-urllib2-tp18150669p18165634.html Sent from the Python - python-list mailing list archive at Nabble.com. From kirk at daycos.com Fri Jun 27 12:52:57 2008 From: kirk at daycos.com (Kirk Strauser) Date: Fri, 27 Jun 2008 11:52:57 -0500 Subject: Django or TurboGears for a new project Message-ID: <8763ru6cra.fsf@internal.daycos.com> We're looking to migrate a Zope site to Django, but before getting beyond the dreaming stage, I thought I'd see what others are doing these days. If you were going to start a fairly complex site today with lots of DB integration, would you begin with Django or TurboGears, or something else entirely? I'm more interested in social, rather than technical reasons (unless there's something you absolutely love or despise about one or the other). Popularity is actually a pretty big consideration because I'd like to work with an eager community who's doing cool new things. I know asking for comparisons like this is potentially flamebait-ish, but I really don't mean it that way. It's just that I don't have a lot of friends in the industry in this particular development niche who I can ask for recommendations, and this seems like as good a place as any to find subject matter experts. Thanks, -- Kirk Strauser The Day Companies From Russ.Paielli at gmail.com Sun Jun 8 15:27:14 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 8 Jun 2008 12:27:14 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> Message-ID: <5c617585-8664-4aa7-95bf-fa33f20d98c1@j1g2000prb.googlegroups.com> On Jun 8, 5:52 am, Mark Wooding wrote: > By enforcing your `data hiding', you're effectively telling me that I'm > too stupid to make rational decisions of this sort. And that's actually > extremely insulting. 1) I suggest you not take it personally. 2) Local data within functions is hidden. Should you have access to that too? Are you insulted that you don't? 3) I have suggested that "indirect" or "back door" access could be provided to private data and methods via some sort of name mangling rule akin to the current rule for leading double underscores. This would provide access in a pinch, but it would make sure the client is aware that he or she or it is accessing private data (and it would do so without leading underscores). 4) My understanding is that most Python software is released or shipped as source code (or at least with the source code included). That means that the client would need only to remove my suggested "priv" keyword to gain access. Have you ever actually had to use Python software for which you had no access to the source code? From dyamins at gmail.com Fri Jun 13 21:38:24 2008 From: dyamins at gmail.com (Dan Yamins) Date: Fri, 13 Jun 2008 21:38:24 -0400 Subject: A package import question In-Reply-To: References: <15e4667e0806131601r14759c54jac431a8fc531414d@mail.gmail.com> Message-ID: <15e4667e0806131838p7258b00by66db0fe8393ddfa5@mail.gmail.com> You have removed the "archive" attribute from the object to which the > "Operations" name is referring to. > > >>> import Operations.archive >> > > Python keeps a reference to all imported modules in sys.modules; if a > module was already imported, any subsequent imports of the same module just > return the existing reference. > If you want to force Python to re-read the module from file, use the reload > function. But please read the warnings at > http://docs.python.org/lib/built-in-funcs.html#l2h-61 > > Gabriel, thanks. I understood about the fact that import only loads the first time, but didn't realize that "del" only removes the bound reference to the object, not as I had hoped the thing from the namespace itself. Also, I did _try_ to use reload. however, that failed since .archive was no longer an attribute associated with Operations: >>> import Operations.archive >>> del Operations.archive >>> reload(Operations.archive) Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'archive' It seems unfortunately that the "del" operation on the one hand doesn't really remove the .archive from memory but just it's bound name, but nonetheless prevents me from reloading the object kept in memory. I guess I'm trying to find a clean way to remove all the attributes associated with a module when I reload it. Is there any way to do this? (The operation of recursively searching through the attributes of the module and deleting those first seems to be bad since when I did that and then try to _reload_ the module, the attributes I deleted are _not_ reloaded.) On Fri, Jun 13, 2008 at 9:09 PM, Gabriel Genellina wrote: > En Fri, 13 Jun 2008 20:01:56 -0300, Dan Yamins > escribi?: > > I'm having a problem importing a package in python, deleting some of >> what's >> been imported, and then reimporting. (I'm the sure the problem is >> trivial, >> but I just don't understand it.) >> >> I have a directory of python modules called Operations. It contains a >> python module called archive.py. Here's a import of the archive module >> via package import: >> >> Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) >> [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import Operations.archive >> >>> Operations.archive >> >> >> So far, so good. >> > > Note that if you execute dir() at this point, you'll see the Operations > name, *not* Operations.archive. > The statement "import Operations.archive" first tries to locate and load a > module named Operations - and *that* name is added to the current namespace, > not Operations.archive (which is an invalid name by itself). > > But now, suppose I want to delete Operations.archive. then, I can't >> reimport it. instead, I >> >> >>> del Operations.archive >> > > You have removed the "archive" attribute from the object to which the > "Operations" name is referring to. > > >>> import Operations.archive >> > > Python keeps a reference to all imported modules in sys.modules; if a > module was already imported, any subsequent imports of the same module just > return the existing reference. > If you want to force Python to re-read the module from file, use the reload > function. But please read the warnings at > http://docs.python.org/lib/built-in-funcs.html#l2h-61 > > >>> dir() >> ['Operations', '__builtins__', '__doc__', '__name__'] >> >>> >> >> Instead of getting 'Operations.archive', I just seem to get 'Operations'. >> > > You would never get a dotted name from dir(), unless you play tricks with > locals()/globals() > > I can't seem to be able to import Operations.archive without quitting the >> python interpreter and starting again. >> >> What's going on here, and how do I fix it? >> > > reload() may be what you need, but again, make sure you read the > documentation before using it. reload is not a magic wand. Remember that > names imported from the old module definition continue to be bound to the > old objects, and all instances of classes defined in the old module continue > to use the old class definitions, among other things. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From s0suk3 at gmail.com Wed Jun 18 20:23:16 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Wed, 18 Jun 2008 17:23:16 -0700 (PDT) Subject: Personal project announcement Message-ID: <0e423dc3-9a7c-4e46-bf3d-af7d8c77cd82@a70g2000hsh.googlegroups.com> Hi, Just wanted to announce a little project I've just uploaded. It's a web server written in Python. You can get it at http://code.google.com/p/sws-d/ . Any suggestions or comments are welcome! Regards, Sebastian From hyugaricdeau at gmail.com Fri Jun 13 09:37:36 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Fri, 13 Jun 2008 06:37:36 -0700 (PDT) Subject: Setting Focus References: <976f51d2-bbb2-4806-a1d0-9481f5aae887@d45g2000hsc.googlegroups.com> <2cf8ed15-e297-42d2-997e-7cf41993b0d9@m3g2000hsc.googlegroups.com> Message-ID: <1c39fb6c-f18c-4e48-9d2d-c4bbf590cc23@25g2000hsx.googlegroups.com> On Jun 13, 9:34 am, Hyuga wrote: > On Jun 12, 11:04 pm, Gandalf wrote: > > > You know these application like ICQ or winamp which stay at the front > > of the desktop as long as the user doesn't minimize it. I wont to do > > the same with my application in python. > > I still didn't manage to make pywinauto to auto set my window frame in > > focus reliability so I was hoping this will solve my problem. > > > I'm working with WX lib on 2.5 python on Microsoft Windows XP > > > I'm not sure if there's a way to do this purely in wx, as it's sort of > a Windows-specific functionality as far as I know. I know in win32 > you can use SetWindowPos() and pass it HWND_TOP (seehttp://msdn.microsoft.com/en-us/library/ms633545(VS.85).aspx). So you Sorry, I meant you actually want HWND_TOPMOST as the second argument to SetWindowPos(). That puts the window above all other windows and keeps it there. Erik From stefan_ml at behnel.de Fri Jun 27 11:20:32 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 27 Jun 2008 17:20:32 +0200 Subject: Design principles and architecture of an information transfer standard based on XML and SOAP In-Reply-To: <070a2cec-5c4b-44ab-93ff-a0811f7c226b@u6g2000prc.googlegroups.com> References: <070a2cec-5c4b-44ab-93ff-a0811f7c226b@u6g2000prc.googlegroups.com> Message-ID: <48650540.9080700@behnel.de> xkenneth wrote: > I'm looking for a bit of advice. There's an oilfield standard > called WITSML (Wellsite Information Transfer Standard Markup Language > - witsml.org), it's basically a collection of XML schemas and a spec For implementing XML languages, I (biasedly) advocate lxml's element class features. http://codespeak.net/lxml/dev/element_classes.html I'll give a tutorial on them at EuroPython, in case you're interested. Stefan From badmuthahubbard at gmail.com Sat Jun 7 10:53:50 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Sat, 7 Jun 2008 17:53:50 +0300 Subject: More than one element of list changing when only one should be Message-ID: <8200bab70806070753y69652e74v73a280cfacb23af2@mail.gmail.com> Hello. This program is clunky, I know; I'm not a programmer, but I need to use this program, so I'm writing it. The problem: I have a cursor following the mouse that shows frequency ratios of potential notes in relation to 1/1 (something like Middle C). At any time, the user may hit "t" to move 1/1 to wherever the cursor is. There is also the option to use many regions, so that some of the notes in the score, in region 0, for instance, can have 1/1 as their base, and others, in region 1 for instance, could have perhaps 3/2 as their base. The program starts out with 2 existing regions, region 0 = 1/1, and region 1 = 3/2. If the user hits r+NUM, the cursor switches to region NUM. If NUM is longer than the list of regions (self.regionlist), a new region is appended with the same base as the current one, and the cursor goes to that region. SO, if you start this program, then: 1) move the cursor around a little; 2) hit 'r' and '1' at the same time - now you are in region 1; 3) hit 'r' and '0', now region 0; 4) hit 'r' and '2', now a new region 2 is created with the same parameters as region 0, and self.regionlist is appended with the new info - now you're in region 2; 5) move the mouse until the fraction reads anything other than 1/1; 6) hit 't' to transpose the current region by that fraction; You can see by the output in the text window that self.regionlist[0] AND self.regionlist[2] have been updated. Only [2] should have been changed. 7) hit 'r' and '0', and see that region 0 has now changed its base to match region 2. I hope someone is curious enough to get through this and help me. I tried extracting the function in question into its own mini-file and the problem didn't happen. I can't think of any reason these lines: self.regionlist[self.hregion][0] = self.curnum self.regionlist[self.hregion][1] = self.curden self.regionlist[self.hregion][3] = self.octave11 = self.yadj should change self.regionlist[0] AND self.regionlist[2] in the same call, but they do. Also, if I add more regions in series, they all update each other. Thanks for your time. -Chuckk -- http://www.badmuthahubbard.com From tjreedy at udel.edu Tue Jun 24 14:52:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Jun 2008 14:52:34 -0400 Subject: sending executable data over network.. In-Reply-To: <19ac19520806240547m172941b2k52777e47b9a84711@mail.gmail.com> References: <19ac19520806232359r31f74c7bk9f5d47eb3540e457@mail.gmail.com> <200806241245.35047.omer@no-log.org> <19ac19520806240547m172941b2k52777e47b9a84711@mail.gmail.com> Message-ID: Piyush Anonymous wrote: > any idea or pointer how i could link it to running code in server? > for example, i get a new method definition for a method and i wish to > change it. > client sent new definition, i compile it in server. how can i link it to > old code? Code to be hot-updated (while running) must have update capability builtin. But please consider security. If a remote system can log in and *push* code, an attacker can potentially do the same. Notice that self-updating programs and systems generally log out to a hardwired location, ask if there are updates, and *pull* the new code. From srilyk at gmail.com Wed Jun 11 11:25:17 2008 From: srilyk at gmail.com (W W) Date: Wed, 11 Jun 2008 10:25:17 -0500 Subject: [Tutor] python gui In-Reply-To: <9d68e4e90806110818q18c57bd2v8b3219de9b2a1ca1@mail.gmail.com> References: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> <333efb450806110818g134b930cj6e36f7bd79a9083@mail.gmail.com> <9d68e4e90806110818q18c57bd2v8b3219de9b2a1ca1@mail.gmail.com> Message-ID: <333efb450806110825i376b9e45we2e6d98d6bdb0396@mail.gmail.com> On Wed, Jun 11, 2008 at 10:18 AM, Gabriela Soares wrote: > How ? That's an extremely broad question, and shows little initiative, and offers little information. Most of us are happy to help you solve problems for free, but few, if any, are willing to write your programs for free. > Any references ? www.google.com Norman linked to a fairly interesting project. Hope this helps, Wayne > On Wed, Jun 11, 2008 at 4:18 PM, W W wrote: >> >> On Wed, Jun 11, 2008 at 8:03 AM, Gabriela Soares >> wrote: >> > Greetings, >> > >> > I want to make a dynamic dashboard, something like: >> > >> > http://examples.adobe.com/flex3/labs/dashboard/main.html# >> > >> > but using python. Is it possible ? >> >> Yes. >> >> -Wayne > > > > -- > Gabriela Soares > > "I learned that courage was not the absence of fear, but the triumph over > it. The brave man is not he who does not feel afraid, but he who conquers > that fear." > Nelson Mandela -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From larry.bates at websafe.com` Thu Jun 5 15:50:24 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 05 Jun 2008 14:50:24 -0500 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <359a09bf-ffc4-403f-b19f-a4565eabcb44@l64g2000hse.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <7xhccbe5sr.fsf@ruckus.brouhaha.com> <359a09bf-ffc4-403f-b19f-a4565eabcb44@l64g2000hse.googlegroups.com> Message-ID: Russ P. wrote: > On Jun 2, 5:11 pm, Paul Rubin wrote: >> "Russ P." writes: >>> I also realize, by the way, that Python allows a client of a class to >>> define a new class member from completely outside the class >>> definition. Obviously, that cannot be declared private. >> This is bogus about 95% of the time though. For the cases where it is >> really desired, I think it's best to require the target class to be >> enable it specifically somehow, maybe by inheriting from a special >> superclass. That could let the compiler statically resolve member >> lookups the rest of the time. > > It did seem a bit odd to me when I realized that you can add data > members (or even a "methods") to a class from completely outside the > class definition. That can be risky, of course, and as you suggest, > perhaps it shouldn't even be allowed by default. > > I usually find that it's safer to initialize in the constructor all > (or nearly all) of the data members that will be needed in a class. If > I need a list that will be populated later, for example, I reserve the > name with an empty list in the constructor. Then, if for some reason > the list gets accessed before it is populated, I don't get an > exception. That is EXACTLY when I want an exception, I did something that shouldn't happen. You also are missing the nice ability of python to use hasattr() to find out if a class instance has a method/attribute. I use hasattr() to test for presence or absence of methods/attributes quite a lot. In the past I did what you describe, but found that to be limiting and a throwback to when I used languages that could not do introspection. I can test to see if the attribute exists, if it is empty, which can be two very different conditions that require two different actions. The only way you can do that is to initialize it to None. While this works it is a fictitious construct that we all learned when we were writing Fortran, Basic or Cobol years ago (oops I think I just revealed that I'm an 'old timer'). Now I just do: if hasattr(self, 'listInQuestion') and I can tell if it has been created (either by constructor) or by some other method. This works particularly well when I do caching of data in objects that are shared among methods. I can also do hasattr(object, 'methodInQuestion') to see if the object implements an interface that I require. May be a little off topic, but I think it is relevant. -Larry From alexnbryan at gmail.com Sun Jun 29 14:59:25 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sun, 29 Jun 2008 11:59:25 -0700 (PDT) Subject: using urllib2 In-Reply-To: <18184087.post@talk.nabble.com> References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> <25d97d35-6d28-43ef-9e54-d8ae7a03bc8f@b1g2000hsg.googlegroups.com> <27fbd1c7-6735-4fb0-9758-726b2fd8b86e@m3g2000hsc.googlegroups.com> <18184087.post@talk.nabble.com> Message-ID: <18184170.post@talk.nabble.com> Actually after looking at this, the code is preactically the same, except the definitions. So what COULD be going wrong here? Alexnb wrote: > > Okay, so i've hit a new snag and can't seem to figure out what is wrong. > What is happening is the first 4 definitions of the word "simple" don't > show up. The html is basicly the same, with the exception of noun turning > into adj. Ill paste the html of the word cheese, and then the one for > simple, and the code I am using to do the work. > > line of html for the 2nd def of cheese: > >
1. the curd of milk separated from the whey and prepared in many ways as a food.
2. valign="top">a definite mass of this substance, often in the shape of a > wheel or cylinder.
> > line of html for the 2nd def of simple: > >
2. valign="top">not elaborate or artificial; plain: a simple style. >
> > code: > > import urllib > from BeautifulSoup import BeautifulSoup > > > def get_defs(term): > soup = > BeautifulSoup(urllib.urlopen('http://dictionary.reference.com/search?q=%s' > % term)) > > for tabs in soup.findAll('table', {'class': 'luna-Ent'}): > yield tabs.findAll('td')[-1].contents[-1].string > > word = raw_input("What word would you like to define: ") > > mainList = list(get_defs(word)) > > n=0 > q = 1 > > for x in mainList: > print str(q)+". "+str(mainList[n]) > q=q+1 > n=n+1 > > Now, I don't think it is the italics because one of the definitions that > worked had them in it in the same format. Any Ideas??! > > > Jeff McNeil-2 wrote: >> >> On Jun 29, 12:50?pm, Alexnb wrote: >>> No I figured it out. I guess I never knew that you aren't supposed to >>> split a >>> url like "http://www.goo\ >>> gle.com" But I did and it gave me all those errors. Anyway, I had a >>> question. On the original code you had this for loop: >>> >>> for tabs in soup.findAll('table', {'class': 'luna-Ent'}): >>> ? ? ? ? yield tabs.findAll('td')[-1].contents[-1].string >>> >>> I hate to be a pain, but I was looking at the BeautifulSoup docs, and >>> found >>> the findAll thing. But I want to know why you put "for tabs," also why >>> you >>> need the "'table', {'class': 'luna-Ent'}):" Like why the curly braces >>> and >>> whatnot? >>> >>> Jeff McNeil-2 wrote: >>> >>> > On Jun 27, 10:26?pm, Alexnb wrote: >>> >> Okay, so I copied your code(and just so you know I am on a mac right >>> now >>> >> and >>> >> i am using pydev in eclipse), and I got these errors, any idea what >>> is >>> >> up? >>> >>> >> Traceback (most recent call last): >>> >> ? File >>> >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", >>> >> line 14, in >>> >> ? ? print list(get_defs("cheese")) >>> >> ? File >>> >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", >>> >> line 9, in get_defs >>> >> ? ? dictionary.reference.com/search?q=%s' % term)) >>> >> ? File >>> >> >>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >>> lib.py", >>> >> line 82, in urlopen >>> >> ? ? return opener.open(url) >>> >> ? File >>> >> >>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >>> lib.py", >>> >> line 190, in open >>> >> ? ? return getattr(self, name)(url) >>> >> ? File >>> >> >>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >>> lib.py", >>> >> line 325, in open_http >>> >> ? ? h.endheaders() >>> >> ? File >>> >> >>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >>> plib.py", >>> >> line 856, in endheaders >>> >> ? ? self._send_output() >>> >> ? File >>> >> >>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >>> plib.py", >>> >> line 728, in _send_output >>> >> ? ? self.send(msg) >>> >> ? File >>> >> >>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >>> plib.py", >>> >> line 695, in send >>> >> ? ? self.connect() >>> >> ? File >>> >> >>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >>> plib.py", >>> >> line 663, in connect >>> >> ? ? socket.SOCK_STREAM): >>> >> IOError: [Errno socket error] (8, 'nodename nor servname provided, or >>> not >>> >> known') >>> >>> >> Sorry if it is hard to read. >>> >>> >> Jeff McNeil-2 wrote: >>> >>> >> > Well, what about pulling that data out using Beautiful soup? If you >>> >> > know the table name and whatnot, try something like this: >>> >>> >> > #!/usr/bin/python >>> >>> >> > import urllib >>> >> > from BeautifulSoup import BeautifulSoup >>> >>> >> > def get_defs(term): >>> >> > ? ? soup = BeautifulSoup(urllib.urlopen('http:// >>> >> > dictionary.reference.com/search?q=%s' % term)) >>> >>> >> > ? ? for tabs in soup.findAll('table', {'class': 'luna-Ent'}): >>> >> > ? ? ? ? yield tabs.findAll('td')[-1].contents[-1].string >>> >>> >> > print list(get_defs("frog")) >>> >>> >> > jeff at martian:~$ python test.py >>> >> > [u'any tailless, stout-bodied amphibian of the order Anura, >>> including >>> >> > the smooth, moist-skinned frog species that live in a damp or >>> >> > semiaquatic habitat and the warty, drier-skinned toad species that >>> are >>> >> > mostly terrestrial as adults. ', u' ', u' ', u'a French person or a >>> >> > person of French descent. ', u'a small holder made of heavy >>> material, >>> >> > placed in a bowl or vase to hold flower stems in position. ', u'a >>> >> > recessed panel on one of the larger faces of a brick or the like. >>> ', >>> >> > u' ', u'to hunt and catch frogs. ', u'French or Frenchlike. ', u'an >>> >> > ornamental fastening for the front of a coat, consisting of a >>> button >>> >> > and a loop through which it passes. ', u'a sheath suspended from a >>> >> > belt and supporting a scabbard. ', u'a device at the intersection >>> of >>> >> > two tracks to permit the wheels and flanges on one track to cross >>> or >>> >> > branch from the other. ', u'a triangular mass of elastic, horny >>> >> > substance in the middle of the sole of the foot of a horse or >>> related >>> >> > animal. '] >>> >>> >> > HTH, >>> >>> >> > Jeff >>> >>> >> > On Jun 27, 7:28?pm, Alexnb wrote: >>> >> >> I have read that multiple times. It is hard to understand but it >>> did >>> >> help >>> >> >> a >>> >> >> little. But I found a bit of a work-around for now which is not >>> what I >>> >> >> ultimately want. However, even when I can get to the page I want >>> lets >>> >> >> say, >>> >> >> "Http://dictionary.reference.com/browse/cheese", I look on >>> firebug, >>> >> and >>> >> >> extension and see the definition in javascript, >>> >>> >> >> >>> >> >> >>> >> >> >>> >> >> >>> >> >> >>> >>> >> >> Jeff McNeil-2 wrote: >>> >>> >> >> > the problem being that if I use code like this to get the html >>> of >>> >> that >>> >>> >> >> > page in python: >>> >>> >> >> > response = urllib2.urlopen("the webiste....") >>> >> >> > html = response.read() >>> >> >> > print html >>> >>> >> >> > then, I get a bunch of stuff, but it doesn't show me the code >>> with >>> >> the >>> >> >> > table that the definition is in. So I am asking how do I access >>> this >>> >> >> > javascript. Also, if someone could point me to a better >>> reference >>> >> than >>> >> >> the >>> >> >> > last one, because that really doesn't tell me much, whether it >>> be a >>> >> >> book >>> >> >> > or anything. >>> >>> >> >> > I stumbled across this a while back: >>> >> >> >http://www.voidspace.org.uk/python/articles/urllib2.shtml. >>> >> >> > It covers quite a bit. The urllib2 module is pretty >>> straightforward >>> >> >> > once you've used it a few times. ?Some of the class naming and >>> >> whatnot >>> >> >> > takes a bit of getting used to (I found that to be the most >>> >> confusing >>> >> >> > bit). >>> >>> >> >> > On Jun 27, 1:41 pm, Alexnb wrote: >>> >> >> >> Okay, I tried to follow that, and it is kinda hard. But since >>> you >>> >> >> >> obviously >>> >> >> >> know what you are doing, where did you learn this? Or where can >>> I >>> >> >> learn >>> >> >> >> this? >>> >>> >> >> >> Maric Michaud wrote: >>> >>> >> >> >> > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit : >>> >> >> >> >> I have never used the urllib or the urllib2. I really have >>> >> looked >>> >> >> >> online >>> >> >> >> >> for help on this issue, and mailing lists, but I can't >>> figure >>> >> out >>> >> >> my >>> >> >> >> >> problem because people haven't been helping me, which is why >>> I >>> >> am >>> >> >> >> here! >>> >> >> >> >> :]. >>> >> >> >> >> Okay, so basically I want to be able to submit a word to >>> >> >> >> dictionary.com >>> >> >> >> >> and >>> >> >> >> >> then get the definitions. However, to start off learning >>> >> urllib2, I >>> >> >> >> just >>> >> >> >> >> want to do a simple google search. Before you get mad, what >>> I >>> >> have >>> >> >> >> found >>> >> >> >> >> on >>> >> >> >> >> urllib2 hasn't helped me. Anyway, How would you go about >>> doing >>> >> >> this. >>> >> >> >> No, >>> >> >> >> >> I >>> >> >> >> >> did not post the html, but I mean if you want, right click >>> on >>> >> your >>> >> >> >> >> browser >>> >> >> >> >> and hit view source of the google homepage. Basically what I >>> >> want >>> >> >> to >>> >> >> >> know >>> >> >> >> >> is how to submit the values(the search term) and then search >>> for >>> >> >> that >>> >> >> >> >> value. Heres what I know: >>> >>> >> >> >> >> import urllib2 >>> >> >> >> >> response = urllib2.urlopen("http://www.google.com/") >>> >> >> >> >> html = response.read() >>> >> >> >> >> print html >>> >>> >> >> >> >> Now I know that all this does is print the source, but thats >>> >> about >>> >> >> all >>> >> >> >> I >>> >> >> >> >> know. I know it may be a lot to ask to have someone >>> show/help >>> >> me, >>> >> >> but >>> >> >> >> I >>> >> >> >> >> really would appreciate it. >>> >>> >> >> >> > This example is for google, of course using pygoogle is >>> easier in >>> >> >> this >>> >> >> >> > case, >>> >> >> >> > but this is a valid example for the general case : >>> >>> >> >> >> >>>>[207]: import urllib, urllib2 >>> >>> >> >> >> > You need to trick the server with an imaginary User-Agent. >>> >>> >> >> >> >>>>[208]: def google_search(terms) : >>> >> >> >> > ? ? return >>> >> >> >> urllib2.urlopen(urllib2.Request("http://www.google.com/search?" >>> >> >> >> > + >>> >> >> >> > urllib.urlencode({'hl':'fr', 'q':terms}), >>> >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? >>> >> >> ?headers={'User-Agent':'MyNav >>> >> >> >> > 1.0 >>> >> >> >> > (compatible; MSIE 6.0; Linux'}) >>> >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ).read() >>> >> >> >> > ? ?.....: >>> >>> >> >> >> >>>>[212]: res = google_search("python & co") >>> >>> >> >> >> > Now you got the whole html response, you'll have to parse it >>> to >>> >> >> recover >>> >> >> >> > datas, >>> >> >> >> > a quick & dirty try on google response page : >>> >>> >> >> >> >>>>[213]: import re >>> >>> >> >> >> >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

>> >> >> >> class=r>.*?

', >>> >> >> >> > res) ] >>> >> >> >> > ...[229]: >>> >> >> >> > ['Python Gallery', >>> >> >> >> > ?'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie >>> des >>> >> Monty >>> >> >> >> ...', >>> >> >> >> > ?'Re: os x, panther, python & co: msg#00041', >>> >> >> >> > ?'Re: os x, panther, python & co: msg#00040', >>> >> >> >> > ?'Cardiff Web Site Design, Professional web site design >>> services >>> >> >> ...', >>> >> >> >> > ?'Python Properties', >>> >> >> >> > ?'Frees < Programs < Python < Bin-Co', >>> >> >> >> > ?'Torb: an interface between Tcl and CORBA', >>> >> >> >> > ?'Royal Python Morphs', >>> >> >> >> > ?'Python & Co'] >>> >>> >> >> >> > -- >>> >> >> >> > _____________ >>> >>> >> >> >> > Maric Michaud >>> >> >> >> > -- >>> >> >> >> >http://mail.python.org/mailman/listinfo/python-list >>> >>> >> >> >> -- >>> >> >> >> View this message in >>> >>> >> context:http://www.nabble.com/using-urllib2-tp18150669p18160312.html >>> >> >> >> Sent from the Python - python-list mailing list archive at >>> >> Nabble.com. >>> >>> >> >> > -- >>> >> >> >http://mail.python.org/mailman/listinfo/python-list >>> >>> >> >> -- >>> >> >> View this message in >>> >> >> >>> context:http://www.nabble.com/using-urllib2-tp18150669p18165634.html >>> >> >> Sent from the Python - python-list mailing list archive at >>> Nabble.com. >>> >>> >> > -- >>> >> >http://mail.python.org/mailman/listinfo/python-list >>> >>> >> -- >>> >> View this message in... >>> >>> read more ? >> >> The definitions were embedded in tables with a 'luna-Ent' class. I >> pulled all of the tables with that class out, and then returned the >> string value of td containing the actual definition. The findAll >> method takes an optional dictionary, thus the {}. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > -- View this message in context: http://www.nabble.com/using-urllib2-tp18150669p18184170.html Sent from the Python - python-list mailing list archive at Nabble.com. From armin.ronacher at active-4.com Mon Jun 16 04:37:44 2008 From: armin.ronacher at active-4.com (Armin Ronacher) Date: Mon, 16 Jun 2008 01:37:44 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections Message-ID: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> Abstract ======== This PEP proposes an ordered dictionary as a new data structure for the ``collections`` module, called "odict" in this PEP for short. The proposed API incorporates the experiences gained from working with similar implementations that exist in various real-world applications and other programming languages. Rationale ========= In current Python versions, the widely used built-in dict type does not specify an order for the key/value pairs stored. This makes it hard to use dictionaries as data storage for some specific use cases. Some dynamic programming languages like PHP and Ruby 1.9 guarantee a certain order on iteration. In those languages, and existing Python ordered-dict implementations, the ordering of items is defined by the time of insertion of the key. New keys are appended at the end, keys that are overwritten and not moved. The following example shows the behavior for simple assignments: >>> d = odict() >>> d['parrot'] = 'dead' >>> d['penguin'] = 'exploded' >>> d.items() [('parrot', 'dead'), ('penguin', 'exploded')] That the ordering is preserved makes an odict useful for a couple of situations: - XML/HTML processing libraries currently drop the ordering of attributes, use a list instead of a dict which makes filtering cumbersome, or implement their own ordered dictionary. This affects ElementTree, html5lib, Genshi and many more libraries. - There are many ordererd dict implementations in various libraries and applications, most of them subtly incompatible with each other. Furthermore, subclassing dict is a non-trivial task and many implementations don't override all the methods properly which can lead to unexpected results. Additionally, many ordered dicts are implemented in an inefficient way, making many operations more complex then they have to be. - PEP 3115 allows metaclasses to change the mapping object used for the class body. An ordered dict could be used to create ordered member declarations similar to C structs. This could be useful, for example, for future ``ctypes`` releases as well as ORMs that define database tables as classes, like the one the Django framework ships. Django currently uses an ugly hack to restore the ordering of members in database models. - Code ported from other programming languages such as PHP often depends on a ordered dict. Having an implementation of an ordering-preserving dictionary in the standard library could ease the transition and improve the compatibility of different libraries. Ordered Dict API ================ The ordered dict API would be mostly compatible with dict and existing ordered dicts. (Note: this PEP refers to the Python 2.x dictionary API; the transfer to the 3.x API is trivial.) The constructor and ``update()`` both accept iterables of tuples as well as mappings like a dict does. The ordering however is preserved for the first case: >>> d = odict([('a', 'b'), ('c', 'd')]) >>> d.update({'foo': 'bar'}) >>> d collections.odict([('a', 'b'), ('c', 'd'), ('foo', 'bar')]) If ordered dicts are updated from regular dicts, the ordering of new keys is of course undefined again unless ``sort()`` is called. All iteration methods as well as ``keys()``, ``values()`` and ``items()`` return the values ordered by the the time the key-value pair was inserted: >>> d['spam'] = 'eggs' >>> d.keys() ['a', 'c', 'foo', 'spam'] >>> d.values() ['b', 'd', 'bar', 'eggs'] >>> d.items() [('a', 'b'), ('c', 'd'), ('foo', 'bar'), ('spam', 'eggs')] New methods not available on dict: ``odict.byindex(index)`` Index-based lookup is supported by ``byindex()`` which returns the key/value pair for an index, that is, the "position" of a key in the ordered dict. 0 is the first key/value pair, -1 the last. >>> d.byindex(2) ('foo', 'bar') ``odict.sort(cmp=None, key=None, reverse=False)`` Sorts the odict in place by cmp or key. This works exactly like ``list.sort()``, but the comparison functions are passed a key/value tuple, not only the value. >>> d = odict([(42, 1), (1, 4), (23, 7)]) >>> d.sort() >>> d collections.odict([(1, 4), (23, 7), (42, 1)]) ``odict.reverse()`` Reverses the odict in place. ``odict.__reverse__()`` Supports reverse iteration by key. Questions and Answers ===================== What happens if an existing key is reassigned? The key is not moved but assigned a new value in place. This is consistent with existing implementations and allows subclasses to change the behavior easily:: class movingcollections.odict): def __setitem__(self, key, value): self.pop(key, None) odict.__setitem__(self, key, value) What happens if keys appear multiple times in the list passed to the constructor? The same as for regular dicts: The latter item overrides the former. This has the side-effect that the position of the first key is used because the key is actually overwritten: >>> odict([('a', 1), ('b', 2), ('a', 3)]) collections.odict([('a', 3), ('b', 2)]) This behavior is consistent with existing implementations in Python, the PHP array and the hashmap in Ruby 1.9. Why is there no ``odict.insert()``? There are few situations where you really want to insert a key at an specified index. To avoid API complication, the proposed solution for this situation is creating a list of items, manipulating that and converting it back into an odict: >>> d = odict([('a', 42), ('b', 23), ('c', 19)]) >>> l = d.items() >>> l.insert(1, ('x', 0)) >>> odict(l) collections.odict([('a', 42), ('x', 0), ('b', 23), ('c', 19)]) Example Implementation ====================== A poorly performing example implementation of the odict written in Python is available: `odict.py `_ The version for ``collections`` should be implemented in C and use a linked list internally. Other implementations of ordered dicts in various Python projects or standalone libraries, that inspired the API proposed here, are: - `odict in Babel`_ - `OrderedDict in Django`_ - `The odict module`_ - `ordereddict`_ (a C implementation of the odict module) - `StableDict`_ - `Armin Rigo's OrderedDict`_ .. _odict in Babel: http://babel.edgewall.org/browser/trunk/babel/util.py?rev=374#L178 .. _OrderedDict in Django: http://code.djangoproject.com/browser/django/trunk/django/utils/datastructures.py?rev=7140#L53 .. _The odict module: http://www.voidspace.org.uk/python/odict.html .. _ordereddict: http://www.xs4all.nl/~anthon/Python/ordereddict/ .. _StableDict: http://pypi.python.org/pypi/StableDict/0.2 .. _Armin Rigo's OrderedDict: http://codespeak.net/svn/user/arigo/hack/pyfuse/OrderedDict.py Future Directions ================= With the availability of an ordered dict in the standard library, other libraries may take advantage of that. For example, ElementTree could return odicts in the future that retain the attribute ordering of the source file. Copyright ========= This document has been placed in the public domain. From tjreedy at udel.edu Sun Jun 29 18:53:26 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 29 Jun 2008 18:53:26 -0400 Subject: UnboundLocalError problems In-Reply-To: <637159.47140.qm@web54507.mail.re2.yahoo.com> References: <637159.47140.qm@web54507.mail.re2.yahoo.com> Message-ID: Mr SZ wrote: > > Hi, > > I am writing a small script that changes my pidgin status to away when I > lock my screen.I'm using the DBUS API for pidgin and > gnome-screensaver.Here's the code: > > #!/usr/bin/env python > > import dbus, gobject > from dbus.mainloop.glib import DBusGMainLoop > dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) > bus = dbus.SessionBus() > > obj = bus.get_object("im.pidgin.purple.PurpleService", > "/im/pidgin/purple/PurpleObject") > purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface") > > > STATUS_AVAILABLE = 2 > STATUS_AWAY = 5 > > ORIG_TYPE = 0 > ORIG_MSG = "" > > > def my_func2(IsEnabled): you need global ORIG_TYPE,ORIG_MSG > if IsEnabled: > ORIG_TYPE,ORIG_MSG = get_current() because this otherwise marks them as local. [snip] > When I run it,it errors out at : > > set_status(ORIG_TYPE,ORIG_MSG) > > giving the error "UnboundLocalError: local variable 'ORIG_TYPE' > referenced before assignment" .This happens In the future, copy and paste the full traceback, which often has additional useful information -- like the line # of the call -- which is not so obvious to someone who has not read the code. > > Aren't ORIG_TYPE and ORIG_MSG global variables? Where am I going > wrong?Everything works fine if I set the arguments manually to the > set_status function. *Any* assignment to a name, including with def, class, import, and augmented assignment, even if the statement is unreachable and cannot be executed, marks the name as local -- unless you specify it as global (or nonlocal in 3.0). tjr From paul.hankin at gmail.com Mon Jun 9 04:54:31 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Mon, 9 Jun 2008 01:54:31 -0700 (PDT) Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: <54c6339a-9119-43b4-af39-3f3c2fb709f1@q24g2000prf.googlegroups.com> On Jun 9, 5:11?pm, Frank Millman wrote: > I have a standard requirement for a 'decimal' type, to instantiate and > manipulate numeric data that is stored in a database. I came up with a > solution long before the introduction of the Decimal type, which has > been working well for me. I know the 'scale' (number of decimal > places) of the number in advance. When I read the number in from the > database I scale it up to an integer. When I write it back I scale it > down again. All arithmetic is done using integers, so I do not lose > accuracy. > > There is one inconvenience with this approach. For example, if I have > a product quantity with a scale of 4, and a price with a scale of 2, > and I want to multiply them to get a value with a scale of 2, I have > to remember to scale the result down by 4. This is a minor chore, and > errors are quickly picked up by testing, but it does make the code a > bit messy, so it would be nice to find a solution. > > I am now doing some refactoring, and decided to take a look at the > Decimal type. My initial impressions are that it is quite awkward to > use, that I do not need its advanced features, and that it does not > help solve the one problem I have mentioned above. > > I therefore spent a bit of time experimenting with a Number type that > suits my particular requirements. I have come up with something that > seems to work, which I show below. > > I have two questions. > > 1. Are there any obvious problems in what I have done? > > 2. Am I reinventing the wheel unnecessarily? i.e. can I do the > equivalent quite easily using the Decimal type? Hi Frank, I don't know why you think Decimal is complicated: it has some advanced features, but for what you seem to be doing it should be easy to replace your 'Number' with it. In fact, it makes things simpler since you don't have to worry about 'scale'. Your examples convert easily: from decimal import Decimal qty = Decimal('12.5') price = Decimal('123.45') print price * qty print qty * price print (qty * price).quantize(Decimal('0.01')) -- Paul Hankin From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 30 10:57:50 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 30 Jun 2008 16:57:50 +0200 Subject: How do web templates separate content and logic? In-Reply-To: <4866ff46$0$7333$607ed4bc@cv.net> References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> Message-ID: <4868f46d$0$24451$426a74cc@news.free.fr> John Salerno a ?crit : > bruno.desthuilliers at gmail.com wrote: > >> For which definitions of "content" and "logic" ??? >> >> The point of mvc is to keep domain logic separated from presentation >> logic, not to remove logic from presentation (which just couldn't >> work). Templating systems are for presentation logic. Whether they >> work by embedding an existing complete programmation language or by >> providing they're own specialised mini-language (or a mix of both) is >> not the point here IMHO. > > No, I don't mean presentation logic at all. I mean something along the > lines of combining HTML (which is what I refer to as "content") and > Python (which is what I meant by "logic"). Some (if not most) templating systems use their own mini-language to handle presentation logic. > So for example, if you have > code like this (and this isn't necessarily proper code, I'm just making > this up, but you'll see what I mean): > > >

Big Important Topic

>

This is where I say something important about

>
    > % for topic in topics: >
  1. ${topic}
  2. >
> In Django's template system, this would looks like:

Big Important Topic

This is where I say something important about

    {% for topic in topics %}
  1. {{ topic }}
  2. {% endfor %}
In ZPT, it would be:

Big Important Topic

This is where I say something important about

  1. Yadda
> Humph, I just made up that example to make the point that when you no > longer have pure HTML, but instead have programmatic logic (Python) > mixed in with the HTML, then you are mixing content and logic. > > However, as soon as I finished typing it out, it occurred to me that > even the so-called logic in this example is really only producing more > "content" to display. Indeed. > So maybe my question was a little premature. The meme "thou shall not mix domain logic with presentation" is very often misunderstood as "you must not have anything else than html in templates", which is just plain non-sense. Even declarative templating systems (cf Has's post) require some special (ie: non standard) stuff to work. > Or could it just be that > this is a *good* way to mix HTML and Python, and there are other ways > which may be bad? Bingo. > (For example, connecting to a database, like > Sebastian's example. That definitely seems out of place in an HTML file.) Yeps. From alexfama80 at gmail.com Mon Jun 23 13:39:13 2008 From: alexfama80 at gmail.com (AlexFama) Date: Mon, 23 Jun 2008 10:39:13 -0700 (PDT) Subject: Shop and make money Message-ID: <4276e2d1-41bb-4780-a294-3dd7f8c1eafe@r66g2000hsg.googlegroups.com> Shop and make money Wana get nice watches, Jewelleries, Coins and Medallions Or may be you are interested in Unique Wellness products How about holidays All of this and more valuable products in this website http://www.quest.net/products/en/ Then enter https://portal.quest.net/qnver14/verifyreferrer.aspx IR ID of my referrer * : HY865731 Country I live in * : (your country) Click Shop Now Processed and enjoy shopping Regards... From __peter__ at web.de Mon Jun 16 13:09:52 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Jun 2008 19:09:52 +0200 Subject: 'string'.strip(chars)-like function that removes from the middle? References: Message-ID: Ethan Furman wrote: > The strip() method of strings works from both ends towards the middle. > Is there a simple, built-in way to remove several characters from a > string no matter their location? (besides .replace() ;) >>> identity = "".join(map(chr, range(256))) >>> 'www.example.com'.translate(identity, 'cmowz.') 'exaple' Peter From cokofreedom at gmail.com Tue Jun 24 05:16:50 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 24 Jun 2008 02:16:50 -0700 (PDT) Subject: Python 3000 vs Perl 6 References: Message-ID: <89fbe834-68b7-49e6-8136-62dee53c2f40@t54g2000hsg.googlegroups.com> On Jun 24, 10:36 am, "Corey G." wrote: > What I meant, in terms of dealing with accurate or non-accurate rumors > is with speed, yes. There are plenty of comparisons where Perl is > 4-15x faster then Python for 'some' operations regarding regular > expressions, etc. > > For me personally, this means absolutely nothing because if I spend > 50x more time comprehending spaghetti, obfuscated Perl code it's > irrelevant. The main concern (my concern) is whether or not Perl 6 is > more like Java with pre-compiled byte code (did I say that right) and > whether or not individuals without the ability to see past the surface > will begin to migrate towards Perl 6 for its seemingly faster > capabilities. > > With Perl 6 taking 10+ years, if/when it actually gets released, will > it be technically ahead of Python 3000? Is Parrot worth the extra > wait the Perl 6 project is enduring? My own answer would be a > resounding no, but I am curious as to what others think. :) > > -Thanks! > >From a quick read of the Parrot Wiki page it would appear they hope to one day allow the compilation of BOTH Perl 6 and Python, which could be interesting. Towards the speed, http://shootout.alioth.debian.org/debian/benchmark.php?test=all&lang=all puts Python ahead of perl, and Python Psyco ahead of Parrot PIR. Though I haven't looked at each benchmark comparison so it is hard to tell. Towards what Perl 6 offers, the Wiki on it seems to indicate it will be a clean up of Perl 5 as well as adding of many features from other languages. It seems like Lary has gone for the TAKE IT ALL approach which could work out well in providing practically any format for creating Perl scripts. Or it could cause huge confusion as users ask for help and received a 1001 different approaches... Towards it being more advanced than Python 3k, time will tell. Both are still active and getting updated. So while I personally will stay with Python, others may move, or use both. From johnjsal at gmailNOSPAM.com Sat Jun 14 21:40:24 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sat, 14 Jun 2008 21:40:24 -0400 Subject: Creating a TCP/IP connection on already-networked computers In-Reply-To: References: <4853f269$0$11615$607ed4bc@cv.net> <4854123f$0$5017$607ed4bc@cv.net> <485413d0$0$4997$607ed4bc@cv.net> <485425b2$0$11631$607ed4bc@cv.net> Message-ID: <4854730e$0$11637$607ed4bc@cv.net> Grant Edwards wrote: > If the two computers are in no way connected via any type of > network, then the two programs won't be able to talk to each > other. > > The programs can't create a network, they can only use one that > already exists. But isn't that the point of the program, to create a network between the two computers? Isn't that what the host and port are used for, to open a connection? (Just to clarify, when I say "in no way connected", I don't mean not connected to the internet in general. I know they need access to the internet for any kind of networking program to work at all.) From shriphanip at gmail.com Sun Jun 1 09:25:09 2008 From: shriphanip at gmail.com (Shriphani) Date: Sun, 1 Jun 2008 06:25:09 -0700 (PDT) Subject: SPOJ, Problem Code: sumtrian, Reducing time taken to solve. Message-ID: Hi, I was trying to solve the sumtrian problem in the SPOJ problem set ( https://www.spoj.pl/problems/SUMTRIAN/ ) and this is the solution I submitted: http://pastebin.ca/1035867 The result was, "Your solution from 2008-06-01 15:13:06 to problem SUMTRIAN, written in Python, has exceeded the allowed time limit." I suspect that the first portion of my solution which looks at the input, figures out the number of triangles and forms a list that contains lists containing each row of the triangle, is wrong. I am not too sure how to optimize it. I would appreciate help. Thanks, Shriphani Palakodety From auch-ich-m at g-kein-spam.com Fri Jun 6 13:03:23 2008 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Fri, 06 Jun 2008 19:03:23 +0200 Subject: lots of futex_wait calls References: Message-ID: <26384647.rjfOZSXm3s@news.perlig.de> skunkwerk wrote: > I've got a python program written for the django web framework that > starts about 100 threads. When I start the server, it sometimes eats > up 100% of the CPU for a good minute or so... though none of the > threads are CPU-intensive > > doing a strace on the program, i found lots of calls like this: > > select(5, [4], [], [], {1, 0}) = 0 (Timeout) > futex(0x86a3ce0, FUTEX_WAIT, 0, NULL) = 0 > > i've read the man page for futex... but is this normal? More or less. Most of the futex calls (if not all) are grabbing or releasing the global interpreter lock (GIL). It's usually helpful to increase the thread-schedule-checkinterval in order to lessen the system load (especially the number of context switches). See sys.setcheckinterval. nd From circularfunc at yahoo.se Fri Jun 13 11:00:39 2008 From: circularfunc at yahoo.se (cirfu) Date: Fri, 13 Jun 2008 08:00:39 -0700 (PDT) Subject: weird iteration/assignment problem Message-ID: <61936860-de3f-4bb1-8806-08f9f21ad113@m36g2000hse.googlegroups.com> for i in xrange(0, len(texts)): texts[i] = "yes" for i in texts: i = "no" why is the first one working but not the second. i mean i see why the firts one works but i dont udnerstand why the second doesnt. From kurt.mueller at aerodynamics.ch Tue Jun 24 04:56:21 2008 From: kurt.mueller at aerodynamics.ch (Kurt Mueller) Date: Tue, 24 Jun 2008 10:56:21 +0200 Subject: String split with " and/or ' and/or \ Message-ID: <4860B6B5.3000902@aerodynamics.ch> How to (super)split a string (literal) containing " and/or ' and/or \. example: ' a " b b " c\ c '.supersplit(' ') -> ['a', ' b b ', 'c c'] Thanks and Gr?essli -- Kurt M?ller: kurt.mueller at aerodynamics.ch From george.sakkis at gmail.com Sun Jun 1 12:42:01 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 1 Jun 2008 09:42:01 -0700 (PDT) Subject: Conjunction List References: <2d1bbc53-0c98-4d6e-aedd-1bf4c966410b@v26g2000prm.googlegroups.com> Message-ID: On May 31, 8:01 pm, ccy56... at gmail.com wrote: > http://codepad.org/MV3k10AU > > I want to write like next one. > > def conjunction(number=a[1],name=b[1],size=c[1]): > flag = a[0]==b[0]==c[0] > if flag: > for e in zip(number,name,size): > print e > > conjunction(a,b,c) > > ----------------------------------------------------------------------------------------------------- > function args receive sequence element: > > def somefunc(name=elm1[1], size=elm2[1], color=elm3[1]): > for e in zip(name, size, color): > print e, > > conjunction(a,b,c) > ----------------------------------------------------------------------------------------------------- > > not like two case: > ----------------------------------------------------------------------------------------------------- > > def somefunc(elm1, elm2, elm3): > name = elm1[1]; size = elm1[1]; color = elm1[1] # best solution? > for e in zip(name, size, color): > print e, > > conjunction(a,b,c) > ----------------------------------------------------------------------------------------------------- > > def somefunc(elm1, elm2, elm3, **attr): > for e in zip(attr['name'], attr['size'], attr['color']): > print e, > > conjunction(a,b,c, name=a[1], size=b[1], color=c[1]) # many args... > ----------------------------------------------------------------------------------------------------- > > What's a good approach to get the conjunction nest-list-data? The one you comment with "best solution?" is ok for this example. If you dislike the repetitive part of setting the flag and getting the second element of each argument, or especially if you want to generalize it to more than three arguments, here's one way to do it: def conjunction(*args): if not args: return first = args[0][0] if all(arg[0]==first for arg in args): for e in zip(*(arg[1] for arg in args)): print e >>> conjuction(a,b,c) ('0', 'one', '0%') ('1', 'two', '50%') ('2', 'three', '100%') HTH, George From ptmcg at austin.rr.com Fri Jun 20 10:35:52 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 20 Jun 2008 07:35:52 -0700 (PDT) Subject: Strange re problem References: <2a0a6f87-f72e-4190-85f8-6e43821e313a@r66g2000hsg.googlegroups.com> Message-ID: <43b2c9ad-059a-4261-9b0c-715f86652469@m73g2000hsh.googlegroups.com> On Jun 20, 6:01?am, TYR wrote: > OK, this ought to be simple. I'm parsing a large text file (originally > a database dump) in order to process the contents back into a SQLite3 > database. The data looks like this: > > 'AAA','PF',-17.416666666667,-145.5,'Anaa, French Polynesia','Pacific/ > Tahiti','Anaa';'AAB','AU',-26.75,141,'Arrabury, Queensland, > Australia','?','?';'AAC','EG',31.133333333333,33.8,'Al Arish, > Egypt','Africa/Cairo','El Arish International';'AAE','DZ', > 36.833333333333,8,'Annaba','Africa/Algiers','Rabah Bitat'; > > which goes on for another 308 lines. As keen and agile minds will no > doubt spot, the rows are separated by a ; so it should be simple to > parse it using a regex. So, I establish a db connection and cursor, > create the table, and open the source file. Using pyparsing, you can skip all that "what happens if there is a semicolon or comma inside a quoted string?" noise, and get the data in a trice. If you add results names (as I've done in the example), then loading each record into your db should be equally simple. Here is a pyparsing extractor for you. The parse actions already do the conversions to floats, and stripping off of quotation marks. -- Paul data = """ 'AAA','PF',-17.416666666667,-145.5,'Anaa, French Polynesia','Pacific/ Tahiti','Anaa';'AAB','AU',-26.75,141,'Arrabury, Queensland, Australia','?','?';'AAC','EG',31.133333333333,33.8,'Al Arish, Egypt','Africa/Cairo','El Arish International';'AAE','DZ', 36.833333333333,8,'Annaba','Africa/Algiers','Rabah Bitat'; """.splitlines() data = "".join(data) from pyparsing import * num = Regex(r'-?\d+(\.\d+)?') num.setParseAction(lambda t: float(t[0])) qs = sglQuotedString.setParseAction(removeQuotes) CMA = Suppress(',') SEMI = Suppress(';') dataRow = qs("field1") + CMA + qs("field2") + CMA + \ num("long") + CMA + num("lat") + CMA + qs("city") + CMA + \ qs("tz") + CMA + qs("field7") + SEMI for dr in dataRow.searchString(data): print dr.dump() print dr.city,dr.long,dr.lat Prints: ['AAA', 'PF', -17.416666666666998, -145.5, 'Anaa, French Polynesia', 'Pacific/ Tahiti', 'Anaa'] - city: Anaa, French Polynesia - field1: AAA - field2: PF - field7: Anaa - lat: -145.5 - long: -17.4166666667 - tz: Pacific/ Tahiti Anaa, French Polynesia -17.4166666667 -145.5 ['AAB', 'AU', -26.75, 141.0, 'Arrabury, Queensland, Australia', '?', '?'] - city: Arrabury, Queensland, Australia - field1: AAB - field2: AU - field7: ? - lat: 141.0 - long: -26.75 - tz: ? Arrabury, Queensland, Australia -26.75 141.0 ['AAC', 'EG', 31.133333333332999, 33.799999999999997, 'Al Arish, Egypt', 'Africa/Cairo', 'El Arish International'] - city: Al Arish, Egypt - field1: AAC - field2: EG - field7: El Arish International - lat: 33.8 - long: 31.1333333333 - tz: Africa/Cairo Al Arish, Egypt 31.1333333333 33.8 ['AAE', 'DZ', 36.833333333333002, 8.0, 'Annaba', 'Africa/Algiers', 'Rabah Bitat'] - city: Annaba - field1: AAE - field2: DZ - field7: Rabah Bitat - lat: 8.0 - long: 36.8333333333 - tz: Africa/Algiers Annaba 36.8333333333 8.0 From ustrum at gmail.com Tue Jun 10 07:05:04 2008 From: ustrum at gmail.com (ustrum at gmail.com) Date: Tue, 10 Jun 2008 04:05:04 -0700 (PDT) Subject: DICOM library Message-ID: <8c79237c-4e75-4908-93f2-393f750d90fc@m36g2000hse.googlegroups.com> Hi everybody! I've been looking for a python library wich allows me to work with with DICOM files, for medical image processing. Finding nothing at first, evenctually i've find the gdcm library, wich is suposed to be for c developement, but they say that you can use it with python, as "It is automatically wrapped to python (using swig)". So, the cuestion is: how can I use this kind of library, wich is suposed to be used with c, in python? When I download the tarball there ae only 2 .py files. shall I install the whole library for using in C, and then try to import the gdcm module in python? becouse i'm afraid it won't work. Thanks in advance, and sorry for my english, wich is not very good actually. Sorry for asking for something before trying everything, but i'm almost desperate to find a library like that. From aweraw at gmail.com Thu Jun 12 10:45:46 2008 From: aweraw at gmail.com (Aidan) Date: Fri, 13 Jun 2008 00:45:46 +1000 Subject: Summing a 2D list In-Reply-To: References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <6bcokhF3b2mo7U1@mid.uni-berlin.de> <485131a1$0$11175$c3e8da3@news.astraweb.com> Message-ID: Aidan wrote: > Mark wrote: >> John, it's a QuerySet coming from a database in Django. I don't know >> enough about the structure of this object to go into detail I'm >> afraid. >> >> Aidan, I got an error trying your suggestion: 'zip argument #2 must >> support iteration', I don't know what this means! > > well, if we can create 2 iterable sequences one which contains the user > the other the scores, it should work > > the error means that the second argument to the zip function was not an > iterable, such as a list tuple or string > > can you show me the lines you're using to retrieve the data sets from > the database? then i might be able to tell you how to build the 2 lists > you need. > wait you already did... predictions = Prediction.objects.all() pairs = [(p.predictor.id,p.predictionscore) for p in predictions] those 2 lines will will build a list of user/score pairs. you can then replace the call to zip with pairs any luck? From kylotan at gmail.com Fri Jun 13 10:27:57 2008 From: kylotan at gmail.com (Ben Sizer) Date: Fri, 13 Jun 2008 07:27:57 -0700 (PDT) Subject: Create list from string References: Message-ID: On Jun 13, 3:15?pm, ericdaniel wrote: > Hi, > > I'm new to Python and I need to do the following: > > from this: ? s = "978654321" > to this : ? ? ?["978", "654", "321"] What are your criteria for splitting this string? Every 3 characters? If there isn't an even multiple of 3, which group should be shorter, the first, the last, or maybe some other? And do you even really need this as a string at all? Perhaps you really just wanted to format the output of an integer? (I think that may be done via the locale, but I am not sure.) Often it's best to specify why you want to do something, as when using a new language there is often a better way to achieve what you want than the first way that occurs to you. -- Ben Sizer From see.signature at no.spam Mon Jun 23 05:08:43 2008 From: see.signature at no.spam (Eric Brunel) Date: Mon, 23 Jun 2008 11:08:43 +0200 Subject: inheritance question... References: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> <09ec833f-7751-4991-8d09-45c200fb4c18@z72g2000hsb.googlegroups.com> Message-ID: Preamble: when posting a brand new question, you'd better not replying to an existing completely unrelated message. In most viewers, this will cause your message to appear in the thread for the original question and far less people will see it. So better create a brand new thread. On Fri, 20 Jun 2008 23:19:37 +0200, Hamish McKenzie wrote: > I have this class: > > class Vector(object): > TOL = 1e-5 > def __eq__( self, other, tolerance=TOL ): > print tolerance > > > shortened for clarity obviously. so I want to subclass this class like > so: > > class BigVector(Vector) > TOL = 100 > > > for example if I was working with large vectors which I knew would never > be very close hence the large tolerance. this doesn't work however - > the TOL class variable, while overridden in BigVector, is still using > the Vector.TOL variable in the __eq__ method. > > > which kinda makes sense to a certain degree, but how do I get the > behaviour where doing: > > BigVector().__eq__( otherVec ) > > > prints 100 instead of 1e-5? > > does this question make sense? not sure how clearly I'm phrasing my > question... any of you guys python experts? There's just no way. The default values for function/method arguments are evaluated when the function definition is interpreted. When the __eq__ method is defined, TOL is 1e-5, so that will be the value used in the method, whatever you may do afterwards. > > I *could* do this, but its ugly: > > class Vector(object): > TOL = 1e-5 > def __eq__( self, other, tolerance=None ): > if tolerance is None: tolerance = self.TOL > print tolerance Well, ugliness is in the eye of the beholder... ;-) Even if you find it ugly, that's the Python way to do it. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From bruno.desthuilliers at gmail.com Mon Jun 30 13:49:57 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 30 Jun 2008 10:49:57 -0700 (PDT) Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> Message-ID: On 30 juin, 19:19, Mike wrote: > On Jun 30, 10:57 am, Bruno Desthuilliers > 42.desthuilli... at websiteburo.invalid> wrote: > > > Some (if not most) templating systems use their own mini-language to > > handle presentation logic. > > IMHO this is the funniest (worst) part of all this 'templating' > buss :) > It reminds me the good old slogan: "Have you invented your own GUI > library yet?" Yeps, there's something true here. FWIW, my favorite templating system so for is still Mako, for it doesn't try to reinvent yet another language - just uses Python as both the target runtime and the scripting language. (snip) > > > Or could it just be that > > > this is a *good* way to mix HTML and Python, and there are other ways > > > which may be bad? > > > Bingo. > > Then what is so *good* about it, why embedding HTML into Python is not > good? Who said embedding HTML in Python was bad ? Did you _carefully_ read John's question ?-) wrt/ what's so good about it: web designers are usually better at working with this approach (whatever scripting language embedded in html) than they are writing Python code - either as plain strings or using a more declarative syntax like the one provided by Stan or equivalent html generators. But nothing prevents you from using Mako's internals directly if you find it easier and more maintainable !-) From dullrich at sprynet.com Thu Jun 12 13:57:52 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 12 Jun 2008 12:57:52 -0500 Subject: get keys with the same values References: <3fdafa74-2043-4052-bdec-843f69d9e5fa@e39g2000hsf.googlegroups.com> Message-ID: In article <3fdafa74-2043-4052-bdec-843f69d9e5fa at e39g2000hsf.googlegroups.com>, Paul McGuire wrote: > On Jun 12, 6:41?am, David C. Ullrich wrote: > > On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader > > wrote: > > > > >Hello, > > > > >I have a dictionary and will get all keys which have the same values. > > > > > > > d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} > > > > dd = {} > > > > for key, value in d.items(): > > ? try: > > ? ? dd[value].append(key) > > ? except KeyError: > > ? ? dd[value] = [key] > > > > > Instead of all that try/except noise, just use the new defaultdict: That's certainly much better. The machine where I am in the early morning is still stuck with Python 1.5.3... > >>> from collections import defaultdict > >>> > >>> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} > >>> > >>> dd = defaultdict(list) > >>> for key, value in d.items(): > ... dd[value].append(key) > ... > >>> for k,v in dd.items(): > ... print k,':',v > ... > 1 : ['a', 'e'] > 2 : ['c'] > 3 : ['b', 'd'] > 4 : ['f'] > > -- Paul -- David C. Ullrich From jeff at jmcneil.net Wed Jun 18 12:58:05 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 18 Jun 2008 09:58:05 -0700 (PDT) Subject: Looking for lots of words in lots of files References: <6bskfpF3d3v42U1@mid.uni-berlin.de> Message-ID: <4df60f85-9c5c-41b2-b3d0-5891a1d33e4b@27g2000hsf.googlegroups.com> On Jun 18, 10:29?am, "Diez B. Roggisch" wrote: > brad wrote: > > Just wondering if anyone has ever solved this efficiently... not looking > > for specific solutions tho... just ideas. > > > I have one thousand words and one thousand files. I need to read the > > files to see if some of the words are in the files. I can stop reading a > > file once I find 10 of the words in it. It's easy for me to do this with > > a few dozen words, but a thousand words is too large for an RE and too > > inefficient to loop, etc. Any suggestions? > > Use an indexer, like lucene (available as pylucene) or a database that > offers word-indices. > > Diez I've been toying around with Nucular (http://nucular.sourceforge.net/) a bit recently for some side projects. It's pure Python and seems to work fairly well for my needs. I haven't pumped all that much data into it, though. From serbulentu at gmail.com Mon Jun 30 10:29:11 2008 From: serbulentu at gmail.com (python_newbie) Date: Mon, 30 Jun 2008 07:29:11 -0700 (PDT) Subject: insertion sorts... References: <06adb999-c7e2-4475-a49f-dbfbe042f4fd@r66g2000hsg.googlegroups.com> <5f0111a3-c1b9-4864-bae3-32fa324c4e5e@j22g2000hsf.googlegroups.com> <841dd5b8-d99d-4a60-ad39-b7c9563fca1d@d1g2000hsg.googlegroups.com> <8ceb6019-6474-485c-8daf-91111c85040c@m36g2000hse.googlegroups.com> Message-ID: On 25 Haziran, 17:44, MRAB wrote: > On Jun 25, 11:37?am, "A.T.Hofkamp" wrote: > > > > > On 2008-06-25, python_newbie wrote: > > > > On 24 Haziran, 04:33, Terry Reedy wrote: > > > Thanks for all answers. At the end i ve only one point. If a decide to > > > copy list to iterate when will i have to do this ? Before the > > > iteration ? And then iterate through one list and change value of the > > > other ? > > > Before starting the iteration would be a good point.... > > > I usually do in such cases: > > > for x in mylist[:]: > > ? ?... > > > making a copy just before the for loop starts. > > > Lately, I have started avoiding in-place modification of lists. Instead, I > > construct a new list from scratch inside the for-loop, and replace the old list > > with the newly constructed list afterwards like: > > > new_list = [] > > for x in mylist: > > ? ?.... > > ? ?new_list.append(x) > > > mylist = new_list > > > by appending a different value than the original or by not appending, you can > > influence the contents of the new list. > > > I find this solution nicer than in-place modification of an existing list. > > > Sincerely, > > Albert > > And if you were originally doing in-place modification because there > were also other references to the list then you could just do: > > mylist[:] = new_list Thanks again. I see that you use two different syntax for lists "mylist = new_list" and "mylist[:] = new_list" these are same i think ? From fc14301589 at icqmail.com Sat Jun 14 05:29:54 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Sat, 14 Jun 2008 17:29:54 +0800 Subject: Checking list by using of exception References: <3bdcc52d-2432-4b28-8188-bf7c811859d1@d45g2000hsc.googlegroups.com> Message-ID: <48538f92_2@news.tm.net.my> On 15:37, venerd? 13 giugno 2008 Nader wrote: > try: > list_of_files != [] > get the files > For file in list_of_files: try: myfile = open(file, 'r') except (IOError, OSError): print"Your %s file wasn't open" %file # here you can do something with your open file as read option myfile.readlines() # for example -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From danb_83 at yahoo.com Tue Jun 24 23:32:45 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Tue, 24 Jun 2008 20:32:45 -0700 (PDT) Subject: newb question on strings References: <998616c1-8b96-49a7-b830-f122f5f0ee54@a32g2000prf.googlegroups.com> Message-ID: <5a29e27d-c1b4-4028-8e20-841c58e3f006@27g2000hsf.googlegroups.com> On Jun 24, 4:04?pm, "shand... at gmail.com" wrote: > Are you trying to escape for a regular expression? > > Just do re.escape(). > > >>> print re.escape('Happy') > Happy > >>> print re.escape("Frank's Diner") > > Frank\'s\ Diner > > If you're escaping for URLs, there's urllib2.quote(), for a command > line, use subprocess.list2cmdline. And if you're escaping for string literals in Python (or C and its descendants), you can do: >>> print "Frank's Diner".encode('string-escape') Frank\'s Diner From paul.hankin at gmail.com Thu Jun 12 23:19:19 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 12 Jun 2008 20:19:19 -0700 (PDT) Subject: Notify of change to list References: <8b34cc2b-aa3a-4788-b849-1f926284c7ca@m36g2000hse.googlegroups.com> Message-ID: <90336d65-1537-46a5-92e1-9a8712d56e88@8g2000hse.googlegroups.com> On Jun 13, 12:00?pm, "Alan J. Salmoni" wrote: > My question is how can my program be notified of a change to a class > attribute that is a list? You can't. But you can replace lists inside your class with a list that notifies changes. Something like this: class NotifyingList(list): def __setitem__(self, i, v): print 'setting', i, 'to', v list.__setitem__(self, i, v) [[You'll likely need to redefine __setslice__, __delitem__, __delslice__, append and extend as well]]. >>> x = NotifyingList([1, 2, 3]) >>> x[1] = 4 setting 1 to 4 >>> x [1, 4, 3] If users of your class are allowed to replace attributes with their own lists, you'll have to catch these and convert to NotifyingLists; and it may be somewhat messy. I hope this is useful to you. -- Paul Hankin From jeffrey at fro.man Wed Jun 18 17:03:51 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Wed, 18 Jun 2008 14:03:51 -0700 Subject: Who is using python-ldap with Python 1.5.x and 2.0-2.2? References: <6h7ii5-l9m.ln1@nb2.stroeder.com> Message-ID: Michael Str?der wrote: > Please tell me > which Python version you're using We do have one venerable machine here at work using python2.2 with python-ldap2.0.0pre04. As you can see, we haven't bothered to update either in quite a while ;-) > and why it'd be important for you to > have python-ldap updates still supporting it. For us, it is not important. Should we want or need to update python-ldap on that one machine, we'll update python along with it (and vice versa.) Thank you, Jeffrey From mensanator at aol.com Mon Jun 30 19:45:36 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 30 Jun 2008 16:45:36 -0700 (PDT) Subject: The Yield statement References: Message-ID: <95354739-b4ba-47cb-b2c3-437365cc986b@z72g2000hsb.googlegroups.com> On Jun 30, 5:31?pm, Alex Bryan wrote: > Okay, so i don't really understand the Yield thing and i know it is ? > useful. I've read a few things about it but it is all programming ? > jargon and so basically it is hard for me to understand. So can anyone ? > give me a description or link me to a site that has a good definition ? > and/or examples of it? If you could I would really appreciate it. You know what a function does, right? If I were to say x = NextPrime(3) then x should be set to 5. The NextPrime function does this by evaluating the input argument (3) and doing return p as the last statement (p having been determined to be 5). Now, suppose you had a function Primes (i.e., a function that returns ALL the primes). Obviously, since there are an infinite number of them, the function would never end since it would eventually eat up all your memory trying to create a list with infinite elements. However, if Primes were a generator, you could have it return just 1 result at a time. The generator would keep track of the last prime issued so that every .next() call would give you the next prime in the sequence. That's what "yield" does. It functions like a return, only returning a single element of an iteration. For infinite loops, the program simply stops calling the function when it has enough (or tells the function to stop). Here's an example. Note that before it enters the output loop it does a couple things. First, it checks for valid input. If not valid, it executes a "return" statement which kills the generator. If valid, it issues a "yield" prior to the loop. It must do this to issue the first partition. The loop will issue all subsequent partitions with its "yield" statements. This particular generator is always a finite loop. Although the number of generated partitions can be quite large, best to test by doing C(depth-1,width-1) before asking for all the results (which is what "for i in p" does). def partition_generator(depth,width): """creates all partions of a given depth,widtth (depth>=width) depth objects in width bins such that each bin has at least 1 object this function is a generator (does comb(depth-1,width-1) partitions) partition_generator(depth,width) depth: total inverse rule 1 count (p of 2**p) width: total inverse rule 2 count (q of 3**q) sv: sequence vector (the partition) returns sequence vector [sv] """ def move_col(c): sv[c-1] += 1 sv[c] -= 1 def find_c(): i = -1 while i<0: if sv[i]>1: return i i -= 1 def rollover(c): move_col(c) sv[-1] = sv[c] sv[c] = 1 if depth= to width',width return # kills generator max_element = depth - width + 1 sv = [1 for i in range(width)] sv[-1] = max_element yield sv[:] # first partition while sv[0] <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> <484cf5f6$0$15495$426a74cc@news.free.fr> <127975a3-b3d9-4799-9673-b292ec8d37e3@x19g2000prg.googlegroups.com> <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> <484e3526$0$30894$426a74cc@news.free.fr> <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> <783c55ec-a294-4600-91d9-4a0d78632c49@t12g2000prg.googlegroups.com> <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> <484f880c$0$6412$426a74cc@news.free.fr> Message-ID: On Jun 11, 2:36 am, Paul Boddie wrote: > Maybe, but I'd hope that some of those programmers would be at least > able to entertain what Russ has been saying rather than setting > themselves up in an argumentative position where to concede any > limitation in Python might be considered some kind of weakness that > one should be unwilling to admit. Thanks. I sometimes get the impression that Desthuilliers thinks of this forum like a pack of dogs, where he is the top dog and I am a newcomer who needs to be put in his place. I just wish he would take a chill pill and give it a rest. I am not trying to challenge his position as top dog. All I did was to suggest that a keyword be added to Python to designate private data and methods without cluttering my cherished code with those ugly leading underscores all over the place. I don't like that clutter any more than I like all those semi-colons in other popular languages. I was originally attracted to Python for its clean syntax, but when I learned about the leading-underscore convention I nearly gagged. If Desthuilliers doesn't like my suggestion, then fine. If no other Python programmer in the world likes it, then so be it. But do we really need to get personal about it? Python will not be ruined if it gets such a keyword, and Desthuilliers would be perfectly free to continue using the leading-underscore convention if he wishes. Where is the threat to his way of life? From gh at ghaering.de Wed Jun 11 07:50:48 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 11 Jun 2008 13:50:48 +0200 Subject: Parallel python + ?? In-Reply-To: References: Message-ID: Thor wrote: > Hi, > > I am running a program using Parallel Python and I wonder if there is a > way/module to know in which CPU/core the process is running in. Is that > possible? This is of course OS-specific. On Linux, you can parse the proc filesystem: >>> open("/proc/%i/stat" % os.getpid()).read().split()[39] You can use the "taskset" utility to query or set CPU affinity on Linux. -- Gerhard From casey.mcginty at gmail.com Fri Jun 27 21:21:39 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Fri, 27 Jun 2008 15:21:39 -1000 Subject: Help with Borg design Pattern Message-ID: Hi, I'm trying to implement a simple Borg or Singleton pattern for a class that inherits from 'dict'. Can someone point out why this code does not work? class MyDict( dict ): __state = {} def __init__(self): self.__dict__ = self.__state a = MyDict() a['one'] = 1 a['two'] = 2 print a print MyDict() -------------- next part -------------- An HTML attachment was scrubbed... URL: From hat at se-162.se.wtb.tue.nl Tue Jun 17 05:40:56 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 17 Jun 2008 11:40:56 +0200 Subject: Showing a point in Gnuploy.py References: <5360d45b-7b62-4154-bb08-855dfafeae61@m36g2000hse.googlegroups.com> Message-ID: On 2008-06-16, arslanburney at gmail.com wrote: > Hello. Could some1 tell me how i could "display" a specific point in > gnuplot.py. Supposingly if i have a point of intersection (2,3). How > can i show this on the graph? As in how can i write near the point of > intersection the value :(2,3). > Thnx 1. Find out in the Gnuplot manual what command to enter 2. Send the command to Gnuplot using g() function-call From space.captain.face at gmail.com Sat Jun 7 00:35:26 2008 From: space.captain.face at gmail.com (Kalibr) Date: Fri, 6 Jun 2008 21:35:26 -0700 (PDT) Subject: Dynamically naming objects. References: <8a99c3fa-1eeb-49b3-a714-b6063ec1daab@d19g2000prm.googlegroups.com> Message-ID: <3d2a85b2-255d-4e93-8cfb-e2772f57b69a@u6g2000prc.googlegroups.com> On Jun 7, 1:20 pm, Hans Nowak wrote: > Kalibr wrote: > > I've been developing a small script to fiddle with classes, and came > > accross the following problem. Assuming I get some user input asking > > for a number, how would I spawn 'n' objects from a class? > > > i.e. I have a class class 'user' and I don't know how many of them I > > want to spawn. > > > Any ideas? > > Sure. This will give you a list of n instances of user: > > [user() for i in range(n)] > > Of course, you could also use a good old for loop: > > for i in range(n): > u = user() > ...do something with u... > > Hope this helps! > > -- > Hans Nowak (zephyrfalcon at gmail dot com)http://4.flowsnake.org/ whoops, replied to author.... What I wanted to ask before was won't 'u' be overwritten with a new object each time the loop ticks over? what I want to do is have, say 5 users in a game, so I'd have to spawn 5 objects. I can't do that because I have'nt hardcoded any object names for them. or does it somehow work? how would I address them if they all have the name 'u'? From gagsl-py2 at yahoo.com.ar Thu Jun 19 18:16:25 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 19 Jun 2008 19:16:25 -0300 Subject: py2exe & application add-ons References: Message-ID: En Thu, 19 Jun 2008 08:00:32 -0300, Alex Gusarov escribi?: > Hello, I've met a problem - I want my program working without Python > installation but I have some add-on mechanism (add-ons represented by > separate .py files, and application auto-recognize such files on > start). > > So, if I will using py2exe for main program and separate .py files for > add-ons, will I need Python installation on client machine? > Maybe other ways exist for such tasks? It should work fine. Note that when py2exe scans your project, it collects only the modules actually used by your code. Any module that you don't use (directly or indirectly) won't be available to the add-ons. -- Gabriel Genellina From george.sakkis at gmail.com Tue Jun 3 07:21:55 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 3 Jun 2008 04:21:55 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> Message-ID: On Jun 3, 1:42?am, "Russ P." wrote: > On Jun 2, 10:23 pm, alex23 wrote: > > > Then again, I have no issue with the current convention and personally > > find the idea of adding a "private" keyword makes as much sense as > > being able to syntactically define "model", "view" and "controller" > > methods. > > Well, the designers of C++, Java, and Ada, to name just three very > popular languages (well, two) seem to think it makes sense. But maybe > you know more than they know. And even more (well, almost all) languages use explicit delimiters for defining blocks instead of indentation, so what's your point ? From paul at boddie.org.uk Wed Jun 11 18:16:19 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 11 Jun 2008 15:16:19 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> <484cf5f6$0$15495$426a74cc@news.free.fr> <127975a3-b3d9-4799-9673-b292ec8d37e3@x19g2000prg.googlegroups.com> <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> <484e3526$0$30894$426a74cc@news.free.fr> <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> <783c55ec-a294-4600-91d9-4a0d78632c49@t12g2000prg.googlegroups.com> <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> <484f880c$0$6412$426a74cc@news.free.fr> Message-ID: On 11 Jun, 21:28, "Russ P." wrote: > > All I did was to suggest that a keyword be added to Python to > designate private data and methods without cluttering my cherished > code with those ugly leading underscores all over the place. I don't > like that clutter any more than I like all those semi-colons in other > popular languages. I was originally attracted to Python for its clean > syntax, but when I learned about the leading-underscore convention I > nearly gagged. I'm not bothered about having private instance data, but I think there's definitely a case to be answered about the double-underscore name-mangling convention. In the remote past, people were fairly honest about it being something of a hack, albeit one which had mostly satisfactory results, and unlike the private instance data argument which can often be countered by emphasising social measures, there has been genuine surprise about this particular method of preventing attribute name collisions - it's an issue which can trip up even careful programmers. Note also that the double-underscore convention is listed as a Python wart [1] and is described by Kuchling thus: "But it's a hack and a kludge; making privacy depend on an unrelated property such as the attribute's name is clumsy. At least this ugliness is limited to one specific and little-used case; few Python programmers ever bother to use this private variable feature." In my opinion there are too many people either defending the status quo (warts and all) or pushing the envelope in many areas that didn't overly bother people before (various Python 3000 features). Paul [1] http://wiki.python.org/moin/PythonWarts From eduardo.padoan at gmail.com Wed Jun 11 10:01:50 2008 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Wed, 11 Jun 2008 11:01:50 -0300 Subject: Does the python library of Google Data API is truly free? In-Reply-To: References: <3ac654b2-61b4-44ce-8e03-75f2344d5869@s50g2000hsb.googlegroups.com> <6fb57ab1-b0d2-4b7d-93c1-b919ca0e51a0@i36g2000prf.googlegroups.com> <3a296d00-d4e0-4f03-b6b3-bef4c5d628dd@x35g2000hsb.googlegroups.com> <6b5mloF3aeui4U1@mid.uni-berlin.de> <18115776-edf7-41b8-a5e9-639847c57a6a@x41g2000hsb.googlegroups.com> Message-ID: On Wed, Jun 11, 2008 at 10:28 AM, Kless wrote: > I understand very well that a service is a software which is accessed > through a network. > > And the description given on Wikipedia [1] is "A 'Web service' (also > Web Service) is defined by the W3C as "a software system designed to > support interoperable Machine to Machine interaction over a network." > > Now, to ending with this. I understand that (almos) everybody is pro > Google (and anti Microsoft), thinking that they have given a lot of > services for free. And it's very hard that people understand my > thinking. > > All that "free service" has a great price, that are the rights > about those data, and when Google want can to disable the free access > to that information. > > People don't realize that it's one more a company and like so it has > only an end, that is to obtain the greater number of benefits which > will be distributed between his shareholders. Within any years Google > will be as hated as Microsoft. > > At least I try to use the less possible those services than limit my > freedoms about data that has been contributed by me and another users. > > > [1] http://en.wikipedia.org/wiki/Web_service > -- > http://mail.python.org/mailman/listinfo/python-list > It is not a pro-GOOG/anti-MSFT child-thing. Google is a for-profit company. They are in it for the money. There is nothing wrong with it in a capitalist world, if you play by the rules. Also, services like this are scarce resources, it demands storage space, processing power, bandwidth, and etc to provide it, so it makes absolute sense that one would want money to keep providing it. Software per-se isn't scarce resources - you can copy it infinite times (but the work of writing it is, that is why there are programmers payed to write Free Software). Now you seem to be saying that if Google doesn't provide a scarce resource to you for Free (as in "Free Beer"), they will be hated just as you seem to hate Microsoft. I would hate Google if, after proving so much good stuff as free software, they gonne bankrupt for providing services without restrictions, completely for free. http://en.wikipedia.org/wiki/Scarcity -- Eduardo de Oliveira Padoan http://www.advogato.org/person/eopadoan/ http://twitter.com/edcrypt Bookmarks: http://del.icio.us/edcrypt From em00100 at hotmail.com Fri Jun 27 03:23:27 2008 From: em00100 at hotmail.com (em00100 at hotmail.com) Date: Fri, 27 Jun 2008 00:23:27 -0700 (PDT) Subject: the problem about the DLL file generate by py2exe References: <26b30d17-f6b4-45b3-b7fa-eb9702ac873c@u6g2000prc.googlegroups.com> <6che9sF3gadfaU1@mid.uni-berlin.de> Message-ID: <0cf910f5-d53b-4abc-8147-0c94da52503b@w5g2000prd.googlegroups.com> On Jun 26, 7:52?pm, "Diez B. Roggisch" wrote: > em00... at hotmail.com wrote: > > Dear All, > > > I have try to use the py2exe to compile the DLL file > > > first i write the simple python script "test01.py": > > def test001(): > > ? ? return 1 > > > then write the setup.py: > > # setup.py > > from distutils.core import setup > > import py2exe > > import sys > > > if len(sys.argv) == 1: > > ? ? sys.argv.append("py2exe") > > ? ? sys.argv.append("-q") > > > class Target: > > ? ? def __init__(self, **kw): > > ? ? ? ? self.__dict__.update(kw) > > ? ? ? ? # for the version info resources (Properties -- Version) > > ? ? ? ? self.version = "0.0.1" > > ? ? ? ? self.company_name = "Nil" > > ? ? ? ? self.copyright = "Nil" > > ? ? ? ? self.name = "test" > > > testTK = Target( > > ? ? # used for the versioninfo resource > > ? ? description = "test app", > > ? ? # what to build > > ? ? modules = ["test01"], > > ? ? script = "test01.py", > > ? ? # specify which type of com server you want (exe and/or dll) > > ? ? create_exe = False, > > ? ? create_dll = True) > > > #setup(windows=["hkcity_ide_main.py"]) > > setup( > > ? ? name='Test', > > ? ? options={"py2exe": {"bundle_files": 1, }}, > > ? ? zipfile=None, > > ? ? version='1.0', > > ? ? description='Test', > > ? ? author='', > > ? ? author_email='', > > ? ? url='', > > ? ? ctypes_com_server=[testTK], > > ? ? ) > > > and compile the it by the command: > > > C:\Python25\python setup.py py2exe > > > I use the script try to call the function "test001" in the "test01.py" > > from ctypes import * > > test01 = cdll.LoadLibrary("test01.dll") > > test001 = test01.test001 > > print test01() > > > However, this is out the error: > > AttributeError: function 'test001' not found > > > Is it any problem when i define the function? > > I guess you should define a python-function, inside which you call your > dll-function. > > Diez How to define the "python-function"? can you write the statement with my testing script, please. the "python-function" is place in "test01.py"? is it also need to define the "python-function" in "setup.py" thanks for you time From ncoghlan at gmail.com Wed Jun 4 08:09:08 2008 From: ncoghlan at gmail.com (NickC) Date: Wed, 4 Jun 2008 05:09:08 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> <873antn9il.fsf@benfinney.id.au> <6ammujF38poe2U2@mid.uni-berlin.de> <87y75llp5x.fsf@benfinney.id.au> <6an5a7F38poe2U3@mid.uni-berlin.de> <87tzg9l8fp.fsf@benfinney.id.au> Message-ID: <2378abb8-c0b6-4471-8572-7db78232ccfe@d19g2000prm.googlegroups.com> On Jun 4, 9:56 pm, Ben Finney wrote: > Those unit tests should *not*, though, exercise anything but the > public API, otherwise they're breaking encapsulation. Their assertion > should continue to be just as true after a refactoring of the internal > components as before. Python must have bad unit tests then - the CPython test suite explicitly tests private methods all the time. There's actually an extremely good reason for doing it that way: when the implementation of an internal method gets broken, the unit tests flag it explicitly, rather than having to derive the breakage from the breakage of 'higher level' unit tests (after all, you wouldn't factor something out into its own method or function if you weren't using it in at least a couple of different places). Black box testing (testing only the public API) is certainly important, but grey box and white box testing that either exploits knowledge of the implementation when crafting interesting test cases, or explicitly tests internal APIs can be highly beneficial in localising faults quickly when something does break (and as any experienced maintenance programmer will tell you, figuring out what you actually broke is usually harder than fixing it after you find it). From pfreixes at gmail.com Mon Jun 9 14:26:09 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Mon, 9 Jun 2008 20:26:09 +0200 Subject: GIL cpu multi core usage problem Message-ID: <207312b70806091126t6d9c3479hfe39368cd06b029e@mail.gmail.com> Hi List, Surly this is a recurring theme into python dev world, but I need your help for confirm if the follow image it's really http://www.milnou.net/~pfreixes/img/cpu_usage_gil_problem.png I'm writing a brief article for my blog and I need to make sure about the current problem with GIL and multi core environments, this picture try to explain with images the problem for scheduling multiple threads running python code of same interpreter into multiple cpu cores. Can anyone confirm to me this picture ? -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From karthikinfotech1985 at gmail.com Fri Jun 20 09:39:24 2008 From: karthikinfotech1985 at gmail.com (Lilly) Date: Fri, 20 Jun 2008 06:39:24 -0700 (PDT) Subject: SEXY__AUNTY__NEED__HARD__SEX Message-ID: SEXY__AUNTY__NEED__HARD__SEX *** WANT HAVE SECRET DATE WITH HOT SEXY SCHOOL GIRLS , HOUSEWIFE, AUNTIES ETC @@@CLICK MY PHOTO ---> GO TO MY PROFILE AND GET DETAIL FIND HOT GIRLS IN YOUR AREA FOR SEX http://glamourpriya.blogspot.com IMPRESS GIRLS WITH LOVE QUOTATIONS http://glamourpriya.blogspot.com MASALA PICS VIDEOS OF HOT CELEBRITY http://glamourpriya.blogspot.com JOIN COMMUNITY " SEX FRIENDS" TO FIND REAL SEX MATES http://glamourpriya.blogspot.com From bedouglas at earthlink.net Fri Jun 13 14:10:09 2008 From: bedouglas at earthlink.net (bruce) Date: Fri, 13 Jun 2008 11:10:09 -0700 Subject: python screen scraping/parsing In-Reply-To: Message-ID: <206701c8cd80$b7e5d560$0301a8c0@tmesa.com> Hi... got a short test app that i'm playing with. the goal is to get data off the page in question. basically, i should be able to get a list of "tr" nodes, and then to iterate/parse them. i'm missing something, as i think i can get a single node, but i can't figure out how to display the contents of the node.. nor how to get the list of the "tr" nodes.... my test code is: -------------------------------- #!/usr/bin/python #test python script import re import libxml2dom import urllib import urllib2 import sys, string from mechanize import Browser import mechanize #import tidy import os.path import cookielib from libxml2dom import Node from libxml2dom import NodeList ######################## # # Parse pricegrabber.com ######################## # datafile tfile = open("price.dat", 'wr+') efile = open("price_err.dat", 'wr+') urlopen = urllib2.urlopen ##cj = urllib2.cookielib.LWPCookieJar() Request = urllib2.Request br = Browser() user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values1 = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } headers = { 'User-Agent' : user_agent } url ="http://www.pricegrabber.com/rating_summary.php/page=1" #======================================= if __name__ == "__main__": # main app txdata = None #---------------------------- # get the kentucky test pages #br.set_cookiejar(cj) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.addheaders = [('User-Agent', 'Firefox')] br.open(url) #cj.save(COOKIEFILE) # resave cookies res = br.response() # this is a copy of response s = res.read() # s contains HTML not XML text d = libxml2dom.parseString(s, html=1) print "d = d",d #get the input/text dialogs #tn1 = "//div[@id='main_content']/form[1]/input[position()=1]/@name" t1 = "/html/body/div[@id='pgSiteContainer']/div[@id='pgPageContent']/table[2]/tbo dy" tr = "/html/body/div[@id='pgSiteContainer']/div[@id='pgPageContent']/table[2]/tbo dy/tr[4]" tr_=d.xpath(tr) print "len =",tr_[1].nodeValue print "fin" ----------------------------------------------- my issue appears to be related to the last "tbody", or tbody/tr[4]... if i leave off the tbody, i can display data, as the tr_ is an array with data... with the "tbody" it appears that the tr_ array is not defined, or it has no data... however, i can use the DOM tool with firefox to observe the fact that the "tbody" is there... so.. what am i missing... thoughts/comments are most welcome... also, i'm willing to send a small amount via paypal!! -bruce From python-url at phaseit.net Mon Jun 16 12:15:44 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 16 Jun 2008 16:15:44 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Jun 16) Message-ID: QOTW: "The problem [with C++] is, I never feel like I'm programing the *problem*, I always feel like I'm programming the *language*." - Roy Smith Alternatives to the Decimal type: http://groups.google.com/group/comp.lang.python/browse_thread/thread/9cd6dae725268afb/ How to invert a dictionary: http://groups.google.com/group/comp.lang.python/browse_thread/thread/a8222b9dd036e4ef/ Why wxPython is not a standard module (and why some consider it "unpythonic"): http://groups.google.com/group/comp.lang.python/browse_thread/thread/fde7680a07b79cb0/ Why map(None, ...) behaves in the specific way it does: http://groups.google.com/group/comp.lang.python/browse_thread/thread/fe79adf209747a52/ Raw strings, backslashes, filenames, GUI input... A big confusion finally resolved: http://groups.google.com/group/comp.lang.python/browse_thread/thread/43940eb4de069f63/ A simple and suposedly "safe" eval() that isn't safe at all - malicious users can execute arbitrary code: http://groups.google.com/group/comp.lang.python/browse_thread/thread/40d765b5eedfb57/ How networks work - mostly off topic, but clearly and simply explained: http://groups.google.com/group/comp.lang.python/browse_thread/thread/e84dff684899c3f2/ Confusing the Google Data API, the services it access, and their licenses: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b632eee9dc98b26c/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From peterbe at gmail.com Mon Jun 2 07:27:41 2008 From: peterbe at gmail.com (Peter Bengtsson) Date: Mon, 2 Jun 2008 04:27:41 -0700 (PDT) Subject: mocking a logging object Message-ID: <768fa8be-4bf2-40b2-9a26-6e59ff3b5a07@a70g2000hsh.googlegroups.com> In my unittest I want to override the logger of a working module so that it puts all logging messages in /tmp/test.log instead so that in my unittest I can inspect that it logs things correctly. Hopefully this "pseudo" code will explain my problem:: >>> import logging, os >>> logging.basicConfig(filename='/tmp/real.log', level=logging.INFO) >>> logger = logging.getLogger('Real') >>> logger.info('Real stuff') >>> os.path.isfile('/tmp/real.log') True >>> # do the monkey patching like the unit test does >>> logging.basicConfig(filename='/tmp/test.log', level=logging.INFO) >>> logger = logging.getLogger('Test') >>> logger.info('Test stuff') >>> os.path.isfile('/tmp/test.log') False >>> open('/tmp/real.log').read() 'INFO:Real:Real stuff\nINFO:Test:Test stuff\n' How can I change what file the logger should write to? From fake.mail at noone.be Sun Jun 22 06:24:35 2008 From: fake.mail at noone.be (Josip) Date: Sun, 22 Jun 2008 12:24:35 +0200 Subject: Storing value with limits in object References: Message-ID: > Not with normal vars, because = is a rebinding operator in Python, > rather than assignment. > > You can do (close to) the above with object properties. > > David. Yes, but it's done with built-in types like int and float. I suspect I could subclass from them and implement limits, but I would have to make seperate class for each type. Can I override conversion methods like int() and float() within my class? From larry.bates at websafe.com` Mon Jun 30 08:52:58 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 30 Jun 2008 07:52:58 -0500 Subject: HTML Parsing In-Reply-To: <2760a17a-63f9-4700-b31a-b1b60108a26e@m44g2000hsc.googlegroups.com> References: <2760a17a-63f9-4700-b31a-b1b60108a26e@m44g2000hsc.googlegroups.com> Message-ID: disappearedng at gmail.com wrote: > Hi everyone > I am trying to build my own web crawler for an experiement and I don't > know how to access HTTP protocol with python. > > Also, Are there any Opensource Parsing engine for HTML documents > available in Python too? That would be great. > > Check on Mechanize. It wraps Beautiful Soup inside of methods that aid in website crawling. http://pypi.python.org/pypi/mechanize/0.1.7b -Larry From jurgenex at hotmail.com Sun Jun 1 15:16:28 2008 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sun, 01 Jun 2008 19:16:28 GMT Subject: Python's doc problems: sort References: <929d5ce9-9063-4e6c-98aa-89526f89fba3@y18g2000pre.googlegroups.com> Message-ID: "Andrew Koenig" wrote: > wrote in message [Subject: Python's doc problems: sort] >> I want to emphasize a point here, as i have done quite emphatically in >> the past. The Python documentation, is the world's worst technical And WTF does Python documentation have to do with Perl of Lisp? szr, do you still have any doubts about the nature of xahlee? >Welcome to my killfile. Done a long, long time ago. Follow-up set. jue From desothier at yahoo.com Wed Jun 25 11:47:40 2008 From: desothier at yahoo.com (antar2) Date: Wed, 25 Jun 2008 08:47:40 -0700 (PDT) Subject: reading from list with paths Message-ID: Hello, Suppose this is a stupid question, but as a python beginner I encounter a lot of obstacles... so I would be very grateful with some help for following question: I would like to read files, of which the complete filepaths are mentioned in another textfile. In this textfile (list.txt) are for example the following paths: /data/chorec/chorec-nieuw/s01/S01C001M1/S01C001M1_1LG_f01.TextGrid /data/chorec/chorec-nieuw/s01/S01C001M1/ S01C001M1_1LGPseudo_f01.TextGrid /data/chorec/chorec-nieuw/s01/S01C001M1/S01C001M1_AVI1_f01.TextGrid I know how to open and read one file in my current directory, but after trying to find this out my self, I give up... So could someone help me and write some code so that I know how to open and read the content of the mentioned files. Thanks a lot Antar2 From vronskij at gmail.com Tue Jun 3 17:26:04 2008 From: vronskij at gmail.com (vronskij at gmail.com) Date: Tue, 3 Jun 2008 14:26:04 -0700 (PDT) Subject: Q about object identity References: Message-ID: <8f46276a-fbf8-4a5b-a446-645894de3465@k13g2000hse.googlegroups.com> On 3. J?n, 23:08 h., Christian Heimes wrote: > vrons... at gmail.com schrieb: > > > Hello, > > > I am testing object identity. > > > If I do it from the interpreter, I get strange results. > > >>>> print [] is [] > > False > > >>>> print id([]), id([]) > > 3083942700 3083942700 > > > Why is that? Isn't this an error? > > No, it's not an error. You are getting this result because the list > implementation keeps a bunch of unused list objects in a free list. It's > an optimization trick. Python has to create two different list objects > for "[] is []" while it can reuse the same list object for id([]) == id([]). > > Christian Aha. Thanks. jan bodnar From basti.wiesner at gmx.net Tue Jun 10 07:46:02 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Tue, 10 Jun 2008 13:46:02 +0200 Subject: Separators inside a var name References: <3be4a686-16fc-4b20-8c51-df1addc5cefc@m3g2000hsc.googlegroups.com> Message-ID: bruno.desthuilliers at gmail.com at Montag 09 Juni 2008 23:39: > On 9 juin, 20:05, "Sebastian \"lunar\" Wiesner" > wrote: >> Rainy at Montag 09 Juni 2008 19:29: >> > (snip) >> > From what I understand, scheme can have variables like var-name. I'm >> > curious about reasons that python chose to disallow this. >> >> "-" is an operator in Python. How should the parser know, >> whether "var-name" means "the object bound to var_dash_name" or "subtract >> the object bound to name from the object bound to var"? >> >> Scheme can allows such names, because its a functional programming >> language. > > Nope. Scheme and most lisps AFAICT allow such names because of lisp's > syntax, period. Scheme being (more or less) a functional language is > mostly unrelated. FWIW, there are pure functional languages that use > an infix operator syntax just like Python (and FWIW, Python itselfs > uses functions to implement operators) and don't accept dashes in > identifiers for the same reasons as Python : parsing ambiguity. Of course, you're right. My words were badly chosen, I just wanted to point out, that scheme can allow such names, because it doesn't use operators but functions for things like subtraction. My bad, sorry -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From john.gerald.mason at gmail.com Sun Jun 1 17:58:43 2008 From: john.gerald.mason at gmail.com (Mason) Date: Sun, 1 Jun 2008 14:58:43 -0700 (PDT) Subject: convert binary to float References: <0c15e8e1-948b-4bd6-a312-b1e055da859e@t54g2000hsg.googlegroups.com> Message-ID: <55c862a4-f798-443d-8b79-c4336ef8892c@t54g2000hsg.googlegroups.com> On Jun 1, 6:41 pm, Dennis Lee Bieber wrote: > On Sun, 1 Jun 2008 12:55:45 -0700 (PDT), Mason > declaimed the following in > comp.lang.python: > > > I have tried and tried... > > > I'd like to read in a binary file, convert it's 4 byte values into > > floats, and then save as a .txt file. > > > This works from the command line (import struct); > > > In [1]: f = open("test2.pc0", "rb") > > In [2]: tagData = f.read(4) > > In [3]: tagData > > Interpreter display of raw object name uses repr() > > > Out[3]: '\x00\x00\xc0@' > > > I can then do the following in order to convert it to a float: > > > In [4]: struct.unpack("f", "\x00\x00\xc0@") > > Out[4]: (6.0,) > > > But when I run the same code from my .py file: > > > f = open("test2.pc0", "rb") > > tagData = f.read(4) > > print tagData > > Display from a print statement uses str() > > > I get this (ASCII??): > > ?@ > > Probably not ASCII -- ASCII doesn't have that spanish (?) bottom row > quote... And a pair of null bytes don't take up screen space. > > > I only know how to work with '\x00\x00\xc0@'. > > > I don't understand why the output isn't the same. I need a solution > > that will allow me to convert my binary file into floats. Am I close? > > Can anyone point me in the right direction? > > Why do you have to /see/ the byte representation in the first > place... just feed the four bytes to the struct module directly. > > import struct > fin = open("test2.pc0", "rb") > tagFloat = struct.unpack("f", fin.read(4))[0] > print tagFloat > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ Thanks Dennis, I'm OK now. I just sort of dropped the ball for a bit :). Mason From keiths at apache-da.com Fri Jun 6 11:52:17 2008 From: keiths at apache-da.com (Keith Sabine) Date: Fri, 06 Jun 2008 16:52:17 +0100 Subject: SWIG -- Passing python proxy class instance to python callback Message-ID: <48495D31.7010400@apache-da.com> Hi Did you ever find a solution to this? I am having the exact same problem... - Keith I'm trying to pass a proxy class instance (SWIG generated) of CClass, to a python callback function from C++. The proxy class instance of CClass is created from a pointer to the C++ class CClass. Using the code below, I receive the error message: "AttributeError: 'PySwigObject' object has no attribute 'GetName'" The python callback function is being passed in through the clientdata pointer, and the CClass *class pointer is what's being converted to an instance of the SWIG proxy class and passed to the python callback function as an argument. static void PythonCallBack(CClass *class,void *clientdata) { PyObject *func, *arglist,*obj; PyObject *result; func = (PyObject *) clientdata; // Get Python function obj = SWIG_NewPointerObj((void*) cmd, SWIGTYPE_p_CSCSICommand, 1); //create instance of python proxy class from c++ pointer arglist=Py_BuildValue("(O)",*obj); //convert to tuple result = PyEval_CallObject(func,arglist); // Call Python Py_XDECREF(result); return; } Any input would greatly appreciated. Thanks, Jeff From jr9445 at ATT.COM Tue Jun 3 09:51:44 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Tue, 3 Jun 2008 08:51:44 -0500 Subject: regex help In-Reply-To: <0ac601c8c57e$3c9d6bc0$a501a8c0@office.ipglobal.net> References: <0ac601c8c57e$3c9d6bc0$a501a8c0@office.ipglobal.net> Message-ID: > From: python-list-bounces+jr9445=att.com at python.org > [mailto:python-list-bounces+jr9445=att.com at python.org] > On Behalf Of Support Desk > Sent: Tuesday, June 03, 2008 9:32 AM > To: python-list at python.org > Subject: regex help > > I am trying to put together a regular expression that will > rename users address books on our server due to a recent > change we made.? Users with address books user.abook need > to be changed to user at domain.com.abook I'm having trouble > with the regex. Any help would be appreciated. import re emails = ('foo.abook', 'abook.foo', 'bob.abook.com', 'john.doe.abook') for email in emails: print email, '-->', print re.sub(r'\.abook$', '@domain.com.abook', email) ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA623 From pandasagar at gmail.com Tue Jun 3 00:59:04 2008 From: pandasagar at gmail.com (sagar panda) Date: Tue, 3 Jun 2008 10:29:04 +0530 Subject: Please solve me the problem Message-ID: <905b76210806022159l1bcb0165r1096c491f665e914@mail.gmail.com> Hi I am sagar. I want to write a python script that will run the python scripts automatically from a directory. Please help me out to sovle this problem? -- with regards Mr. Sagar Panda Mob:9986142755 -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.wyburn at googlemail.com Wed Jun 18 06:19:19 2008 From: marc.wyburn at googlemail.com (marc wyburn) Date: Wed, 18 Jun 2008 03:19:19 -0700 (PDT) Subject: CSV variable seems to reset Message-ID: <192bf81f-46cb-4a47-bbae-384a2d17a2be@y38g2000hsy.googlegroups.com> Hi, I'm using the CSV module to parse a file using whitelistCSV_file = open("\\pathtoCSV\\whitelist.csv",'rb') whitelistCSV = csv.reader(whitelistCSV_file) for uname, dname, nname in whitelistCSV: print uname, dname, nname The first time I run the for loop the contents of the file is displayed. Subsequent attempts to run the for loop I don't get any data back and no exception. The only way I can get the data is to run whitelistCSV_file = open("\ \pathtoCSV\\whitelist.csv",'rb') again. I'm stumped as to how I can get around this or work out what the problem is, I'm assuming that the 'open' command buffers the data somewhere and that data is being wiped out by the CSV module but surely this shouldn't happen. thanks, Marc. From grante at visi.com Sat Jun 28 20:53:24 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 28 Jun 2008 19:53:24 -0500 Subject: pxssh submit su commands = very very slow References: <39f89067-8ee6-470a-92ce-77b46a344f37@34g2000hsf.googlegroups.com> Message-ID: On 2008-06-28, Neil Hodgson wrote: > gert: >> This works but after the su command you have to wait like 2 minutes >> before each command gets executed ? >> s.sendline ('su') >> s.expect('Password:') > > A common idiom seems to be to omit the start of the > expected reply since it may not be grabbed quickly enough. > Then the prompt has to time out. Try s.expect('assword:') I don't see why the first letter of the password prompt would be dropped. Tty drivers have buffered data for as long as I've been using Unix (25+ years). After writing the username you can wait for an hour before calling read(), and you'll still see the entire password prompt. I always assumed it was done that way so the script would work for either "password:" or "Password:". -- Grant Edwards grante Yow! Edwin Meese made me at wear CORDOVANS!! visi.com From Lie.1296 at gmail.com Sun Jun 29 05:47:36 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 29 Jun 2008 02:47:36 -0700 (PDT) Subject: help debugging noob code - converting binary data to images... References: <56955a42-155c-4c37-9bf6-5a99cadb5c79@l42g2000hsc.googlegroups.com> Message-ID: On Jun 29, 11:18?am, la... at portcommodore.com wrote: > Ok I'm a Python noob, been doing OK so far, working on a data > conversion program and want to create some character image files from > an 8-bit ROM file. > > Creating the image I've got down, I open the file and use TK to draw > the images... but > > 1) ?It does not seem to end (running in IDLE), I have to kill the > process to retry it seems tkinter does not close(?) > > 2) Once I added the Image module open won't open my binary file > (complains its not an image file, which is isnt.) ?I am sure I need to > prefix open with something but I can't seem to find an example of how > to word it, > > Below is the code (if it is lousy its because I've mainly been > borrowing by examples as I go...) Any suggestions are gretly > appreciated. > > #!/usr/local/bin/python > > from Tkinter import * > from string import * > from Image import * DON'T DO THAT... You're importing everything to the current namespace and this corrupts the current namespace, specifically the 'open' function inside Image.open would shadow the built-in 'open' function. use: import Tkinter import string import Image There are use cases where doing 'from blah import *' is useful, such as importing constants, but in general try to avoid importing everything to current namespace. > root = Tk() > root.title('Canvas') If you used 'import Tkinter', you'd have to change that code to: root = Tkinter.Tk() > #open commodore Cset rom > cset ?= open("chargen","r") Because you shadowed the built-in 'open' with the 'from Image import *', this would call Image.open instead of the built-in open. > canvas = Canvas(width=16, height=16, bg='white') If you used 'import Tkinter', you'd have to change that code to: canvas = Tkinter.Canvas(...) > canvas.pack(expand=YES, fill=BOTH) > > # character size factor > size = 2 > > # read all 512 characters from ROM > for cchar in range(0, 511, 1): You can use this instead: for cchar in range(511): but beware, this creates range with length 511 (so do the original range), which means you're lacking on space for the last char. You probably wanted this instead: for cchar in range(512): But again, python can loop directly over string/list/file, etc, so this might be best: for char in cset.read(): > ? ? #draw line > ? ? while charline < 8: > ? ? ? ? position = 0 > ? ? ? ? x = cset.read(1) > ? ? ? ? ch = ord(x) > ? ? ? ? # draw pixels > ? ? ? ? while position < 8: > ? ? ? ? ? ? if ch & ( 2 ** position ): > ? ? ? ? ? ? ? ? xp = 1+(7-position)*size > ? ? ? ? ? ? ? ? yp = 1+charline*size > ? ? ? ? ? ? ? ? canvas.create_rectangle(xp,yp,xp+size,yp+size, > fill='black', width=0) > ? ? ? ? ? ? position += 1 Since you're planning to use Image module (from PIL/Python Imaging Library) why not use functions from Image instead to create the image. The format of the file you're using seems to be RAW format (i.e. simple uncompressed bitmap, without any kinds of header). That means Image.fromstring() should work. > ? ? ? ? charline += 1 > ? ? #save character image > ? ? outfile = "/home/mydir/work/char"+zfill(cchar,3)+".png" > ? ? canvas.save(outfile,"png") > ? ? #clear canvas for next char... > ? ? canvas.create_rectangle(1,1,size*8,size*8, fill='white', width=0) > root.mainloop() From sturlamolden at yahoo.no Sat Jun 14 11:05:38 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 14 Jun 2008 08:05:38 -0700 (PDT) Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> Message-ID: <0213909a-7888-4474-bd88-fc5f148f0abe@y38g2000hsy.googlegroups.com> On Jun 12, 3:48 pm, Mark wrote: > Is this possible? def foobar(user,score): sums = {} for u,s in zip(user,score): try: sums[u] += s except KeyError: sums[u] = s return [(u, sums[u]) for u in sums].sort() usersum = foobar(user,score) for u,s in usersum: print "%d %d" % (u,s) From workitharder at gmail.com Sat Jun 14 13:26:54 2008 From: workitharder at gmail.com (bukzor) Date: Sat, 14 Jun 2008 10:26:54 -0700 (PDT) Subject: Python + RDBM framework? Message-ID: It seems that whenever I have an application that uses a database (MySQL) I end up writing a database framework from scratch. Is there some accepted pre-existing project that has done this? I see Django, but that seems to have a lot of web-framework that I don't (necessarily) need. I just want to have my objects go in and out of the database in a consistent manner without writing a ton of code. Can you just use the database part without making a full-blow web app? I see Zope, but that doesn't use MySQL (as far as I can tell), which I've invested a lot of time learning to use and optimize. Also, my manager wants to be able to log into a MySQL prompt and be able to look at the data. --Buck From george.sakkis at gmail.com Wed Jun 11 08:00:13 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 11 Jun 2008 05:00:13 -0700 (PDT) Subject: Producer-consumer threading problem References: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> <9482cbb7-297e-4429-b7a1-6d7c1dcc9070@t12g2000prg.googlegroups.com> Message-ID: <3d0a1204-526b-4447-a2cf-7f40860bb299@d1g2000hsg.googlegroups.com> On Jun 11, 1:59?am, Rhamphoryncus wrote: > Why not use a normal Queue, put a dummy value (such as None) in when > you're producer has finished, and have the main thread use the normal > Thread.join() method on all your child threads? I just gave two reasons: - Concurrency / interactivity. The main thread shouldn't wait for all one million items to be produced to get to see even one of them. - Limiting resources. Just like iterating over the lines of a file is more memory efficient than reading the whole file in memory, getting each consumed item as it becomes available is more memory efficient than waiting for all of them to finish. George From rhamph at gmail.com Wed Jun 11 01:40:33 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Tue, 10 Jun 2008 22:40:33 -0700 (PDT) Subject: Confusion with weakref, __del__ and threading References: Message-ID: On Jun 10, 8:15 pm, George Sakkis wrote: > I'm baffled with a situation that involves: > 1) an instance of some class that defines __del__, > 2) a thread which is created, started and referenced by that instance, > and > 3) a weakref proxy to the instance that is passed to the thread > instead of 'self', to prevent a cyclic reference. > > This probably sounds like gibberish so here's a simplified example: > > ========================================== > > import time > import weakref > import threading > > num_main = num_other = 0 > main_thread = threading.currentThread() > > class Mystery(object): > > def __init__(self): > proxy = weakref.proxy(self) > self._thread = threading.Thread(target=target, args=(proxy,)) > self._thread.start() > > def __del__(self): > global num_main, num_other > if threading.currentThread() is main_thread: > num_main += 1 > else: > num_other += 1 > > def sleep(self, t): > time.sleep(t) > > def target(proxy): > try: proxy.sleep(0.01) > except weakref.ReferenceError: pass > > if __name__ == '__main__': > for i in xrange(1000): > Mystery() > time.sleep(0.1) > print '%d __del__ from main thread' % num_main > print '%d __del__ from other threads' % num_other > > ========================================== > > When I run it, I get around 950 __del__ from the main thread and the > rest from non-main threads. I discovered this accidentally when I > noticed some ignored AssertionErrors caused by a __del__ that was > doing "self._thread.join()", assuming that the current thread is not > self._thread, but as it turns out that's not always the case. > > So what is happening here for these ~50 minority cases ? Is __del__ > invoked through the proxy ? The trick here is that calling proxy.sleep(0.01) first gets a strong reference to the Mystery instance, then holds that strong reference until it returns. If the child thread gets the GIL before __init__ returns it will enter Mystery.sleep, then the main thread will return from Mystery.__init__ and release its strong reference, followed by the child thread returning from Mystery.sleep, releasing its strong reference, and (as it just released the last strong reference) calling Mystery.__del__. If the main thread returns from __init__ before the child thread gets the GIL, it will release the only strong reference to the Mystery instance, causing it to clear the weakref proxy and call __del__ before the child thread ever gets a chance. If you added counters to the target function you should see them match the counters of the __del__ function. Incidentally, += 1 isn't atomic in Python. It is possible for updates to be missed. From straton at lampsacos.demon.co.uk Thu Jun 5 04:42:06 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Thu, 05 Jun 2008 09:42:06 +0100 Subject: Interesting Math Problem In-Reply-To: References: Message-ID: BEES INC wrote: > I've been awfully busy programming lately. My Django-based side > project is coming along well and I hope to have it ready for use in a > few weeks. Please don't ask more about it, that's really all I can say > for now. Anyways, I came across an interesting little math problem > today and was hoping some skilled programmers out there could come up > with a more elegant solution than mine. > Problem: Star Ratings > > People can rate cheeseburgers on my website with a star rating of 0-5 > stars (whole stars only), 5 being mighty tasty and 0 being disgusting. > I would like to show the average of everyone's ratings of a particular > cheeseburger to the nearest half star. I have already calculated the > average rating as a float (star_sum) and the total number of people > that rated the particular cheeseburger (num_raters). The result should > be stored as a float in a variable named "stars." > My Solution (in Python): > > # round to one decimal place and > # separate into whole and fractional parts > parts = str(round(star_sum/num_raters, 1)).split('.') > whole = int(parts[0]) > frac = int(parts[1]) > if frac < 3: > ___frac = 0 > elif frac > 7: > ___frac = 0 > ___whole += 1 > else: > ___frac = 5 > # recombine for a star rating rounded to the half > stars = float(str(whole)+'.'+str(frac)) > > Mmmm? In-N-Out Burgers? Please reply if you've got a better solution. for raw in [0.05 * n for n in range (41)]: rounded = round(2.0*raw)/2.0 print "%0.2f --> %0.2f" % (raw,rounded) From noagbodjivictor at gmail.com Sat Jun 28 11:39:32 2008 From: noagbodjivictor at gmail.com (Victor Noagbodji) Date: Sat, 28 Jun 2008 11:39:32 -0400 Subject: C++ or Python Message-ID: Kurda Yon wrote: > I would like to know what are advantages of Python in comparison with C > ++? In which cases and why Python can be a better tool than C++? I have used both in small projects and I think Python wins by far. First of all, you don't have the hassle of compiling each time you make a change to your code. This compiling step can be a nightmare when developing a web application (CGI, but you will see only few C++ frameworks for web development anyway) or a GUI. Second: Python is easy to read and write. This is very important when working in a team. Python doesn't give you much choice on the code layout, and that's a good thing. And it also increases the speed of your coding. I strongly suggest you learn Python, then C (not C++) in order to extend Python when you feel like something is slow. -- NOAGBODJI Paul Victor From Lie.1296 at gmail.com Mon Jun 16 14:22:50 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 16 Jun 2008 11:22:50 -0700 (PDT) Subject: sqlite3 and Python 2.5.1 References: <612ed26a-c6cf-4133-af6c-f256484e3928@x41g2000hsb.googlegroups.com> Message-ID: On Jun 17, 12:59?am, milan_sanremo wrote: > I have sqlite installed, but when I try to import sqlite3 I receive: > > Python 2.5.1 (r251:54863, Nov ?3 2007, 02:54:36) [C] on sunos5 > Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 > > Traceback (most recent call last): > ? File "", line 1, in > ImportError: No module named sqlite3 > > > > Yet: > > # find /usr/local/python -name "sqlite*" -print > /usr/local/python/lib/python2.5/sqlite3 > > # /opt/csw/bin/sqlite3 > SQLite version 3.2.2 > Enter ".help" for instructions > sqlite> > > What is missing? Did you, by chance, happened to compile your Python yourself? From what I see here: http://www.megasolutions.net/python/python-unix-install,-sqlite3-78710.aspx Python's source doesn't include the sqlite3 source, it only contains pysqlite interface, so when compiling python you need to get sqlite3 too. From tjreedy at udel.edu Sat Jun 21 18:34:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 21 Jun 2008 18:34:34 -0400 Subject: Way to unblock sys.stdin.readline() call In-Reply-To: <56b21108-45b4-4b9e-bda5-171c9ddc21ce@i76g2000hsf.googlegroups.com> References: <56b21108-45b4-4b9e-bda5-171c9ddc21ce@i76g2000hsf.googlegroups.com> Message-ID: joamag wrote: > Is there any possible way to unblock the sys.stdin.readline() call > from a different thread. If you want the thread to do something 'else' when no input is available, would this work? Put readline in a thread that puts lines in a q=queue.Quese(). Then try: l=q.ge_nowait except queue.Empty From ed at leafe.com Tue Jun 24 14:58:02 2008 From: ed at leafe.com (Ed Leafe) Date: Tue, 24 Jun 2008 13:58:02 -0500 Subject: Using Python and MS-SQL Server In-Reply-To: <734a9927-a18b-4af6-a717-eaf2631b4836@c58g2000hsc.googlegroups.com> References: <734a9927-a18b-4af6-a717-eaf2631b4836@c58g2000hsc.googlegroups.com> Message-ID: On Jun 23, 2008, at 11:10 AM, hwcowan at hotmail.com wrote: > The current script that I am working on requires pulling in some > information from a Microsoft SQL Server. > > I was wondering if anyone could suggest the best way of doing this? I > have looked at the different modules that are specific to SQL server, > but none of them seem to be active or up to date. Dabo may be what you need. It is a 3-tier framework for developing desktop applications, so even if you are doing web apps, the data access layer is fully usable by itself. We support MS SQL Server, as well as several other database backends. -- Ed Leafe -- http://dabodev.com From bruno.42.desthuilliers at websiteburo.invalid Fri Jun 6 11:32:37 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 06 Jun 2008 17:32:37 +0200 Subject: Newb question: underscore In-Reply-To: <601115a1-c788-4be7-b6b4-92cf159559bd@f36g2000hsa.googlegroups.com> References: <873anrl8p5.fsf@benfinney.id.au> <87y75jjeqo.fsf@benfinney.id.au> <601115a1-c788-4be7-b6b4-92cf159559bd@f36g2000hsa.googlegroups.com> Message-ID: <48495857$0$26543$426a74cc@news.free.fr> cokofreedom at gmail.com a ?crit : >>> My question is: Why would anyone decide to obfuscate something as easy >>> to read as Python??? >> They didn't decide to obfuscate; they decided to follow a >> strongly-expected convention for the name of that function by existing >> users of the 'gettext' functionality, in contexts that predate the >> appearance of that functionality in Python. >> > > Well _ can also mean the previous output statement that wasn't null, In the shell only IIRC. From jimmy at retzlaff.com Sun Jun 15 14:42:51 2008 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Sun, 15 Jun 2008 11:42:51 -0700 Subject: py2exe 0.6.8 released Message-ID: py2exe 0.6.8 released ===================== py2exe is a Python distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation. Console and Windows (GUI) applications, Windows NT services, exe and dll COM servers are supported. Changes in 0.6.8: * Support for relative imports. * Fix MemoryLoadLibrary to handle loading function addresses by ordinal numbers. Patch and test by Matthias Miller. * Using the options compressed=1, bundle_files=3, and zipfile=None at the same time now works; patch from Alexey Borzenkov. * Allow renaming of single-executable files; patch from Alexey Borzenkov. * Embedding icon resources into the image now works correctly even for ico files containing multiple images. * pyd files from different packages with the same filename no longer conflict. Patch from Grant Edwards. * There are new samples for the 'typelibs' support, including the new option of pre-generating a typelib and specifying the file as an input to py2exe. * The test suite is now included in the source distribution. Changes in 0.6.6: * Better support for Python 2.5. * Experimental support for 64-bit builds of Python on win64. * Better ISAPI support. * New samples for ISAPI and COM servers. * Support for new "command-line styles" when building Windows services. Changes in 0.6.5: * Fixed modulefinder / mf related bugs introduced in 0.6.4. This will be most evident when working with things like win32com.shell and xml.xpath. * Files no longer keep read-only attributes when they are copied as this was causing problems with the copying of some MS DLLs. Changes in 0.6.4: * New skip-archive option which copies the Python bytecode files directly into the dist directory and subdirectories - no archive is used. * An experimental new custom-boot-script option which allows a boot script to be specified (e.g., --custom-boot-script=cbs.py) which can do things like installing a customized stdout blackhole. See py2exe's boot_common.py for examples of what can be done. The custom boot script is executed during startup of the executable immediately after boot_common.py is executed. * Thomas Heller's performance improvements for finding needed modules. * Mark Hammond's fix for thread-state errors when a py2exe created executable tries to use a py2exe created COM DLL. Changes in 0.6.3: * First release assembled by py2exe's new maintainer, Jimmy Retzlaff. Code changes in this release are from Thomas Heller and Gordon Scott. * The dll-excludes option is now available on the command line. It was only possible to specify that in the options argument to the setup function before. The dll-excludes option can now be used to filter out dlls like msvcr71.dll or even w9xpopen.exe. * Fix from Gordon Scott: py2exe crashed copying extension modules in packages. Changes in 0.6.2: * Several important bugfixes: - bundled extensions in packages did not work correctly, this made the wxPython single-file sample fail with newer wxPython versions. - occasionally dlls/pyds were loaded twice, with very strange effects. - the source distribution was not complete. - it is now possible to build a debug version of py2exe. Changes in 0.6.1: * py2exe can now bundle binary extensions and dlls into the library-archive or the executable itself. This allows to finally build real single-file executables. The bundled dlls and pyds are loaded at runtime by some special code that emulates the Windows LoadLibrary function - they are never unpacked to the file system. This part of the code is distributed under the MPL 1.1, so this license is now pulled in by py2exe. * By default py2exe now includes the codecs module and the encodings package. * Several other fixes. Homepage: Download from the usual location: Enjoy, Jimmy From mdw at distorted.org.uk Sun Jun 8 08:52:10 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Sun, 8 Jun 2008 12:52:10 +0000 (UTC) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> Message-ID: Fuzzyman wrote: > So, you are stating that no API programmer using Python *ever* has a > valid or genuine reason for wanting (even if he can't have it) genuine > 'hiding' of internal state or members from consumers of his (or > her...) API? I don't want to speak for whoever you were responding to, but from my point of view... Yes. I understand the difference between the documented interface of a system and the details of its implementation. But sometimes it can be useful to take advantage of implementation details, particularly if the published interface is inadequate in some way. Whether or not I choose to make use of implementation details is a trade-off between immediate convenience and maintainability, but that's something I can make a rational decision about. By enforcing your `data hiding', you're effectively telling me that I'm too stupid to make rational decisions of this sort. And that's actually extremely insulting. -- [mdw] From usfreeads69 at gmail.com Sat Jun 14 06:43:32 2008 From: usfreeads69 at gmail.com (USFREEADS) Date: Sat, 14 Jun 2008 03:43:32 -0700 (PDT) Subject: Get Google Ads Free! Message-ID: <9b33e6b6-f403-46a9-a694-3f450b12a470@h1g2000prh.googlegroups.com> Internet Multimillionaire is deliberately out to show up Google, Yahoo, MSN and every other big search engine by giving away this monster of a secret! (But he doesn?t even care!)... "Internet Marketer Gets $87 Million in Google Pay-Per-Click Ads FREE! ... And Makes Over $314 Million as a Result! ... And Now He's Going to Give You This Same Secret for Next to Nothing!? ?Everyday Google sells several $10 million?s in pay-per-clicks. But I get all mine absolutely FREE ? and now I am going to show you how to get yours FREE also!? That?s right ? Start Sharing in the *Incredible* Secret So Few Others Know About that Allow Them to Actually Get All Their Pay-Per-Click Advertising Absolutely FREE! Fast facts about this amazing NEW SECRET!... This is an incredible system developed by none other than Dr Jon Cohen, MD (retired) who found a little-known ?twist? in how to use the pay-per-click (PPC) and paid-for targeted advertising programs at Google? and the other search engines. Dr Jon has personally used this to: Eliminate over $87 million in otherwise paid-for and PPC ads at Google? and other search engines over the course of about 9 years now! Generate over $314 million in product sales as a result of this incredible savings! Acquire a personal wealth of more than $68 million! (Net) Start and develop 16 online ventures of his own. Has coached ?live? where he taught others this same amazing formula - including 198 executives from major Fortune 500 and FortuneSM 1000 companies, 14 representatives of publicly-traded companies on the New York Stock ExchangeSM (NYSE), 82 more on the NASDAQ?, 5 members of investment houses on the American Stock ExchangeSM (AMEX), as well as at least one former US Congressman (now retired also) who now stays at home and runs a home-based online family business, among countless others. Please click here for further details:- http://tubeurl.com/7l7u0b From ptmcg at austin.rr.com Mon Jun 30 03:10:38 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 30 Jun 2008 00:10:38 -0700 (PDT) Subject: best option for python lex/yacc? References: Message-ID: On Jun 30, 1:47?am, m... at pixar.com wrote: > I'm porting a C lex/yacc based project, and would like to redo > it in python. > > What's the best option for a python lex/yacc-like? ?I've > googled a few things, but wanted to see the current concensus. > > Many TIA! > Mark > > -- > Mark Harrison > Pixar Animation Studios For a full list, see http://nedbatchelder.com/text/python-parsers.html For lex/yacc-like's, PLY, Spark, simpleparse, or ANTLR are probably the leaders. If you consider using pyparsing, then *don't* just try to do a straight transliteration from your existing lex/yacc implementation - you will end up fighting some of pyparsing's basic concepts. But if you already have this implemented and working in C, and given that parsing usually is such a performance-sucking operation, why not package the existing parser into a lib, and call it from python using ctypes, or some similar technology for embedding C code in Python? -- Paul From nick at craig-wood.com Wed Jun 11 22:01:49 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 11 Jun 2008 21:01:49 -0500 Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: Frank Millman wrote: > Thanks to all for the various replies. They have all helped me to > refine my ideas on the subject. These are my latest thoughts. > > Firstly, the Decimal type exists, it clearly works well, it is written > by people much cleverer than me, so I would need a good reason not to > use it. Speed could be a good reason, provided I am sure that any > alternative is 100% accurate for my purposes. > > My approach is based on expressing a decimal number as a combination > of an integer and a scale, where scale means the number of digits to > the right of the decimal point. > > Therefore 0.04 is integer 4 with scale 2, 1.1 is integer 11 with scale > 1, -123.456 is integer -123456 with scale 3. I am pretty sure that any > decimal number can be accurately represented in this form. > > All arithmetic is carried out using integer arithmetic, so although > there may be rounding differences, there will not be the spurious > differences thrown up by trying to use floats for decimal > arithmetic. I used an identical scheme in a product some time ago (written in C not python). It was useful because it modelled the problem domain exactly. You might want to investigate the rational class in gmpy which might satisfy your requirement for exact arithmetic :- >>> import gmpy >>> gmpy.mpq(123,1000) mpq(123,1000) >>> a = gmpy.mpq(123,1000) >>> b = gmpy.mpq(12,100) >>> a+b mpq(243,1000) >>> a*b mpq(369,25000) >>> a/b mpq(41,40) >>> It is also *very* fast being written in C. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bignose+hates-spam at benfinney.id.au Sun Jun 15 18:35:02 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 16 Jun 2008 08:35:02 +1000 Subject: Making wxPython a standard module? References: <48512f69$0$11262$c3e8da3@news.astraweb.com> <0bb2d727-4bd8-4baf-be34-716daec1ddff@d1g2000hsg.googlegroups.com> <87y756ahn2.fsf@benfinney.id.au> <0e2b604c-769b-4191-87ea-948566412094@34g2000hsh.googlegroups.com> Message-ID: <87skve9vjd.fsf@benfinney.id.au> s0suk3 at gmail.com writes: > On Jun 15, 9:37 am, Ben Finney > wrote: > > The Zen of Python, by Tim Peters > > ? > > There should be one-- and preferably only one --obvious way to do it. > > I agree with that concept. But there already is more than one way to > do it, only that the other ways are being made less accessible (by > not being on the standard library), don't you think? With the result that there is only one *obvious* way to do it. That's a property worth some effort to preserve. For some reason, people always overlook that qualification when reading that part of the Zen. -- \ ?A hundred times every day I remind myself that [...] I must | `\ exert myself in order to give in the same measure as I have | _o__) received and am still receiving? ?Albert Einstein | Ben Finney From alexnbryan at gmail.com Sun Jun 29 14:52:25 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sun, 29 Jun 2008 11:52:25 -0700 (PDT) Subject: using urllib2 In-Reply-To: <27fbd1c7-6735-4fb0-9758-726b2fd8b86e@m3g2000hsc.googlegroups.com> References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> <25d97d35-6d28-43ef-9e54-d8ae7a03bc8f@b1g2000hsg.googlegroups.com> <27fbd1c7-6735-4fb0-9758-726b2fd8b86e@m3g2000hsc.googlegroups.com> Message-ID: <18184087.post@talk.nabble.com> Okay, so i've hit a new snag and can't seem to figure out what is wrong. What is happening is the first 4 definitions of the word "simple" don't show up. The html is basicly the same, with the exception of noun turning into adj. Ill paste the html of the word cheese, and then the one for simple, and the code I am using to do the work. line of html for the 2nd def of cheese:
1.the curd of milk separated from the whey and >>> prepared >>> >> in >>> >> >> many ways as a food.
2.a definite mass of this substance, often in the shape of a wheel or cylinder.
line of html for the 2nd def of simple:
2.not elaborate or artificial; plain: a simple style.
code: import urllib from BeautifulSoup import BeautifulSoup def get_defs(term): soup = BeautifulSoup(urllib.urlopen('http://dictionary.reference.com/search?q=%s' % term)) for tabs in soup.findAll('table', {'class': 'luna-Ent'}): yield tabs.findAll('td')[-1].contents[-1].string word = raw_input("What word would you like to define: ") mainList = list(get_defs(word)) n=0 q = 1 for x in mainList: print str(q)+". "+str(mainList[n]) q=q+1 n=n+1 Now, I don't think it is the italics because one of the definitions that worked had them in it in the same format. Any Ideas??! Jeff McNeil-2 wrote: > > On Jun 29, 12:50?pm, Alexnb wrote: >> No I figured it out. I guess I never knew that you aren't supposed to >> split a >> url like "http://www.goo\ >> gle.com" But I did and it gave me all those errors. Anyway, I had a >> question. On the original code you had this for loop: >> >> for tabs in soup.findAll('table', {'class': 'luna-Ent'}): >> ? ? ? ? yield tabs.findAll('td')[-1].contents[-1].string >> >> I hate to be a pain, but I was looking at the BeautifulSoup docs, and >> found >> the findAll thing. But I want to know why you put "for tabs," also why >> you >> need the "'table', {'class': 'luna-Ent'}):" Like why the curly braces and >> whatnot? >> >> Jeff McNeil-2 wrote: >> >> > On Jun 27, 10:26?pm, Alexnb wrote: >> >> Okay, so I copied your code(and just so you know I am on a mac right >> now >> >> and >> >> i am using pydev in eclipse), and I got these errors, any idea what is >> >> up? >> >> >> Traceback (most recent call last): >> >> ? File >> >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", >> >> line 14, in >> >> ? ? print list(get_defs("cheese")) >> >> ? File >> >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", >> >> line 9, in get_defs >> >> ? ? dictionary.reference.com/search?q=%s' % term)) >> >> ? File >> >> >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >> lib.py", >> >> line 82, in urlopen >> >> ? ? return opener.open(url) >> >> ? File >> >> >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >> lib.py", >> >> line 190, in open >> >> ? ? return getattr(self, name)(url) >> >> ? File >> >> >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >> lib.py", >> >> line 325, in open_http >> >> ? ? h.endheaders() >> >> ? File >> >> >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >> plib.py", >> >> line 856, in endheaders >> >> ? ? self._send_output() >> >> ? File >> >> >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >> plib.py", >> >> line 728, in _send_output >> >> ? ? self.send(msg) >> >> ? File >> >> >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >> plib.py", >> >> line 695, in send >> >> ? ? self.connect() >> >> ? File >> >> >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >> plib.py", >> >> line 663, in connect >> >> ? ? socket.SOCK_STREAM): >> >> IOError: [Errno socket error] (8, 'nodename nor servname provided, or >> not >> >> known') >> >> >> Sorry if it is hard to read. >> >> >> Jeff McNeil-2 wrote: >> >> >> > Well, what about pulling that data out using Beautiful soup? If you >> >> > know the table name and whatnot, try something like this: >> >> >> > #!/usr/bin/python >> >> >> > import urllib >> >> > from BeautifulSoup import BeautifulSoup >> >> >> > def get_defs(term): >> >> > ? ? soup = BeautifulSoup(urllib.urlopen('http:// >> >> > dictionary.reference.com/search?q=%s' % term)) >> >> >> > ? ? for tabs in soup.findAll('table', {'class': 'luna-Ent'}): >> >> > ? ? ? ? yield tabs.findAll('td')[-1].contents[-1].string >> >> >> > print list(get_defs("frog")) >> >> >> > jeff at martian:~$ python test.py >> >> > [u'any tailless, stout-bodied amphibian of the order Anura, >> including >> >> > the smooth, moist-skinned frog species that live in a damp or >> >> > semiaquatic habitat and the warty, drier-skinned toad species that >> are >> >> > mostly terrestrial as adults. ', u' ', u' ', u'a French person or a >> >> > person of French descent. ', u'a small holder made of heavy >> material, >> >> > placed in a bowl or vase to hold flower stems in position. ', u'a >> >> > recessed panel on one of the larger faces of a brick or the like. ', >> >> > u' ', u'to hunt and catch frogs. ', u'French or Frenchlike. ', u'an >> >> > ornamental fastening for the front of a coat, consisting of a button >> >> > and a loop through which it passes. ', u'a sheath suspended from a >> >> > belt and supporting a scabbard. ', u'a device at the intersection of >> >> > two tracks to permit the wheels and flanges on one track to cross or >> >> > branch from the other. ', u'a triangular mass of elastic, horny >> >> > substance in the middle of the sole of the foot of a horse or >> related >> >> > animal. '] >> >> >> > HTH, >> >> >> > Jeff >> >> >> > On Jun 27, 7:28?pm, Alexnb wrote: >> >> >> I have read that multiple times. It is hard to understand but it >> did >> >> help >> >> >> a >> >> >> little. But I found a bit of a work-around for now which is not >> what I >> >> >> ultimately want. However, even when I can get to the page I want >> lets >> >> >> say, >> >> >> "Http://dictionary.reference.com/browse/cheese", I look on firebug, >> >> and >> >> >> extension and see the definition in javascript, >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> Jeff McNeil-2 wrote: >> >> >> >> > the problem being that if I use code like this to get the html of >> >> that >> >> >> >> > page in python: >> >> >> >> > response = urllib2.urlopen("the webiste....") >> >> >> > html = response.read() >> >> >> > print html >> >> >> >> > then, I get a bunch of stuff, but it doesn't show me the code >> with >> >> the >> >> >> > table that the definition is in. So I am asking how do I access >> this >> >> >> > javascript. Also, if someone could point me to a better reference >> >> than >> >> >> the >> >> >> > last one, because that really doesn't tell me much, whether it be >> a >> >> >> book >> >> >> > or anything. >> >> >> >> > I stumbled across this a while back: >> >> >> >http://www.voidspace.org.uk/python/articles/urllib2.shtml. >> >> >> > It covers quite a bit. The urllib2 module is pretty >> straightforward >> >> >> > once you've used it a few times. ?Some of the class naming and >> >> whatnot >> >> >> > takes a bit of getting used to (I found that to be the most >> >> confusing >> >> >> > bit). >> >> >> >> > On Jun 27, 1:41 pm, Alexnb wrote: >> >> >> >> Okay, I tried to follow that, and it is kinda hard. But since >> you >> >> >> >> obviously >> >> >> >> know what you are doing, where did you learn this? Or where can >> I >> >> >> learn >> >> >> >> this? >> >> >> >> >> Maric Michaud wrote: >> >> >> >> >> > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit : >> >> >> >> >> I have never used the urllib or the urllib2. I really have >> >> looked >> >> >> >> online >> >> >> >> >> for help on this issue, and mailing lists, but I can't figure >> >> out >> >> >> my >> >> >> >> >> problem because people haven't been helping me, which is why >> I >> >> am >> >> >> >> here! >> >> >> >> >> :]. >> >> >> >> >> Okay, so basically I want to be able to submit a word to >> >> >> >> dictionary.com >> >> >> >> >> and >> >> >> >> >> then get the definitions. However, to start off learning >> >> urllib2, I >> >> >> >> just >> >> >> >> >> want to do a simple google search. Before you get mad, what I >> >> have >> >> >> >> found >> >> >> >> >> on >> >> >> >> >> urllib2 hasn't helped me. Anyway, How would you go about >> doing >> >> >> this. >> >> >> >> No, >> >> >> >> >> I >> >> >> >> >> did not post the html, but I mean if you want, right click on >> >> your >> >> >> >> >> browser >> >> >> >> >> and hit view source of the google homepage. Basically what I >> >> want >> >> >> to >> >> >> >> know >> >> >> >> >> is how to submit the values(the search term) and then search >> for >> >> >> that >> >> >> >> >> value. Heres what I know: >> >> >> >> >> >> import urllib2 >> >> >> >> >> response = urllib2.urlopen("http://www.google.com/") >> >> >> >> >> html = response.read() >> >> >> >> >> print html >> >> >> >> >> >> Now I know that all this does is print the source, but thats >> >> about >> >> >> all >> >> >> >> I >> >> >> >> >> know. I know it may be a lot to ask to have someone show/help >> >> me, >> >> >> but >> >> >> >> I >> >> >> >> >> really would appreciate it. >> >> >> >> >> > This example is for google, of course using pygoogle is easier >> in >> >> >> this >> >> >> >> > case, >> >> >> >> > but this is a valid example for the general case : >> >> >> >> >> >>>>[207]: import urllib, urllib2 >> >> >> >> >> > You need to trick the server with an imaginary User-Agent. >> >> >> >> >> >>>>[208]: def google_search(terms) : >> >> >> >> > ? ? return >> >> >> >> urllib2.urlopen(urllib2.Request("http://www.google.com/search?" >> >> >> >> > + >> >> >> >> > urllib.urlencode({'hl':'fr', 'q':terms}), >> >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? >> >> >> ?headers={'User-Agent':'MyNav >> >> >> >> > 1.0 >> >> >> >> > (compatible; MSIE 6.0; Linux'}) >> >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ).read() >> >> >> >> > ? ?.....: >> >> >> >> >> >>>>[212]: res = google_search("python & co") >> >> >> >> >> > Now you got the whole html response, you'll have to parse it >> to >> >> >> recover >> >> >> >> > datas, >> >> >> >> > a quick & dirty try on google response page : >> >> >> >> >> >>>>[213]: import re >> >> >> >> >> >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

> >> >> >> class=r>.*?

', >> >> >> >> > res) ] >> >> >> >> > ...[229]: >> >> >> >> > ['Python Gallery', >> >> >> >> > ?'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des >> >> Monty >> >> >> >> ...', >> >> >> >> > ?'Re: os x, panther, python & co: msg#00041', >> >> >> >> > ?'Re: os x, panther, python & co: msg#00040', >> >> >> >> > ?'Cardiff Web Site Design, Professional web site design >> services >> >> >> ...', >> >> >> >> > ?'Python Properties', >> >> >> >> > ?'Frees < Programs < Python < Bin-Co', >> >> >> >> > ?'Torb: an interface between Tcl and CORBA', >> >> >> >> > ?'Royal Python Morphs', >> >> >> >> > ?'Python & Co'] >> >> >> >> >> > -- >> >> >> >> > _____________ >> >> >> >> >> > Maric Michaud >> >> >> >> > -- >> >> >> >> >http://mail.python.org/mailman/listinfo/python-list >> >> >> >> >> -- >> >> >> >> View this message in >> >> >> context:http://www.nabble.com/using-urllib2-tp18150669p18160312.html >> >> >> >> Sent from the Python - python-list mailing list archive at >> >> Nabble.com. >> >> >> >> > -- >> >> >> >http://mail.python.org/mailman/listinfo/python-list >> >> >> >> -- >> >> >> View this message in >> >> >> >> context:http://www.nabble.com/using-urllib2-tp18150669p18165634.html >> >> >> Sent from the Python - python-list mailing list archive at >> Nabble.com. >> >> >> > -- >> >> >http://mail.python.org/mailman/listinfo/python-list >> >> >> -- >> >> View this message in... >> >> read more ? > > The definitions were embedded in tables with a 'luna-Ent' class. I > pulled all of the tables with that class out, and then returned the > string value of td containing the actual definition. The findAll > method takes an optional dictionary, thus the {}. > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/using-urllib2-tp18150669p18184087.html Sent from the Python - python-list mailing list archive at Nabble.com. From n.emami at gmail.com Thu Jun 12 07:48:42 2008 From: n.emami at gmail.com (Nader) Date: Thu, 12 Jun 2008 04:48:42 -0700 (PDT) Subject: get keys with the same values References: Message-ID: <7334507d-24e7-43f9-baa3-4e9e87eb20fa@w7g2000hsa.googlegroups.com> On Jun 12, 1:35 pm, bearophileH... at lycos.com wrote: > Nader: > > > d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} > > I will something as : > > d.keys(where their values are the same) > > That's magic. > > > With this statement I can get two lists for this example: > > l1= ['a','e'] > > l2=['b','d'] > > Would somebody tell me how I can do it? > > You can create a new dict where the keys are the values of the input > dict and the values are a list of the keys of the original dict. So > scanning the keys, values of the input dict, you can fill the second > dict. Then you can scan the second dict, and create a list that > contains only value lists longer than one. > > Bye, > bearophile Is it niet possible with one or two statement, maybe with list comprehension. For exmple: l = [(k,v) for k in d.keys() for v in d.values() | en here we need some extra logic (v = 1)] I don;t konw how we can define a logic statement in a list comprehension. It will be very compact, if it would possible. Nader From ppearson at nowhere.invalid Sat Jun 28 13:36:30 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: Sat, 28 Jun 2008 12:36:30 -0500 Subject: Do I need "self" and "other"? References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> Message-ID: On Fri, 27 Jun 2008 20:19:00 -0400, Nick Dumas wrote: [snip] > > Example: > > class Foo(): > self.x = 5 Have you tried what you're posting? Python 2.4.3 (#2, Oct 6 2006, 07:52:30) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo(): File "", line 1 class Foo(): ^ SyntaxError: invalid syntax >>> class Foo( object ): ... self.x = 5 ... Traceback (most recent call last): File "", line 1, in ? File "", line 2, in Foo NameError: name 'self' is not defined >>> -- To email me, substitute nowhere->spamcop, invalid->net. From apardon at forel.vub.ac.be Mon Jun 2 06:40:07 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 2 Jun 2008 10:40:07 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> Message-ID: On 2008-06-02, Carl Banks wrote: > On Jun 2, 5:38 am, Antoon Pardon wrote: >> If you really need it, you can do data hiding in python. It just >> requires a bit more work. >> >> ----------------------------- Hide.py --------------------------------- >> class Rec(object): >> def __init__(__, **kwargs): >> for key,value in kwargs.items(): >> setattr(__, key, value) >> >> def __getitem__(self, key): >> return getattr(self, key) >> >> def __setitem__ (self, key, val): >> setattr(self, key, val) >> >> class Foo(object): >> >> def __init__(self): >> >> hidden = Rec(x=0, y=0) >> >> def SetX(val): >> hidden.x = val >> >> def SetY(val): >> hidden.y = val >> >> def GetX(): >> return hidden.x >> >> def GetY(): >> return hidden.y >> >> self.SetX = SetX >> self.SetY = SetY >> self.GetX = GetX >> self.GetY = GetY > > Red Herring. > > 1. This doesn't hide the variables; it just changes their spelling. > 2. This also "hides" the variables from its own class. > > In other words, it's a useless no-op. > > In fact, I'd say this is even worse than useless. Creating accessor > functions is a sort of blessing for external use. Knowing that there > are accessor functions is likely to cause a user to show even less > restraint. I think you completed missed the point. This is just a proof of concept thing. In a real example there would of course no Set en Get methods but just methods that in the course of their execution would access or update the hidden attributes -- Antoon Pardon From barisc at bckm.org Sun Jun 8 18:38:23 2008 From: barisc at bckm.org (Baris-C) Date: Sun, 8 Jun 2008 15:38:23 -0700 (PDT) Subject: Python is slow References: Message-ID: <4aa0d411-071e-46dd-a568-4b5f148aab48@z72g2000hsb.googlegroups.com> On May 22, 7:14?pm, cm_gui wrote: > Python is slow. ? ?Almost all of the web applications written in > Python are slow. ? Zope/Plone is slow, sloow, so very slooow. ?Even > Google Apps is not faster. ? Neither is Youtube. > Facebook and Wikipedia (Mediawiki), written in PHP, are so much faster > than Python. > Okay, they probably use caching or some code compilation -- but Google > Apps and those Zope sites probably also use caching. > > I've yet to see a web application written in Python which is really > fast. I do not have much experience on python but, php is %25 more faster than python in a simple iteration. From martin at v.loewis.de Tue Jun 10 17:05:53 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 10 Jun 2008 23:05:53 +0200 Subject: Cannot install python under Win32 In-Reply-To: <0358337a-b147-4e38-b37f-a8119a39b6d7@j22g2000hsf.googlegroups.com> References: <82d86466-0b90-47aa-af40-f52b52eb2526@d77g2000hsb.googlegroups.com> <484e258f$0$13627$9b622d9e@news.freenet.de> <0358337a-b147-4e38-b37f-a8119a39b6d7@j22g2000hsf.googlegroups.com> Message-ID: <484EECB1.6020109@v.loewis.de> > DEBUG: Error 2356: Couldn't locate cabinet in stream: python. That sounds bad indeed. In the original file, that stream is definitely present, so most likely, you experienced a corruption in download. Please check the md5 sum of the MSI file; if it differs, download again (preferably using a different web browser). Another possible source is that the Windows installer (running as local system) does not have access to your Regards, Martin From http Wed Jun 4 01:01:51 2008 From: http (Paul Rubin) Date: 03 Jun 2008 22:01:51 -0700 Subject: Books for programmers References: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> <78ef063d-7219-4ffa-bf8f-88dc24dd90bc@r66g2000hsg.googlegroups.com> Message-ID: <7xzlq1sshs.fsf@ruckus.brouhaha.com> V writes: > I think that I'm interested in a more advance book, ideally one that > talk of the Python gotchas, traps, pitfall, idioms, performance, > stile, and so on. I may have missed it but I haven't seen Python in a Nutshell mentioned in this thread. From jgodoy at gmail.com Wed Jun 25 06:44:03 2008 From: jgodoy at gmail.com (Jorge Godoy) Date: Wed, 25 Jun 2008 07:44:03 -0300 Subject: IDE on the level of Eclipse or DEVc++? References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> <486214ae$0$9742$426a34cc@news.free.fr> <87ej6lq02c.fsf@benfinney.id.au> Message-ID: cokofreedom at gmail.com wrote: > How is emacs on a windows platform? Except for Windows using _emacs instead of .emacs, it was the same I had on Linux, last time I tried it... :-) There are packages for Windows that have a lot of things pre-packaged to make it feel more like a Windows application, including keyboard shortcuts. -- Jorge Godoy From bj_666 at gmx.net Thu Jun 5 07:19:19 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 5 Jun 2008 11:19:19 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> <873antn9il.fsf@benfinney.id.au> <6ammujF38poe2U2@mid.uni-berlin.de> <87y75llp5x.fsf@benfinney.id.au> <6an5a7F38poe2U3@mid.uni-berlin.de> <6aok3pF38pu6cU2@mid.uni-berlin.de> Message-ID: <6aq0dnF3892asU2@mid.uni-berlin.de> On Thu, 05 Jun 2008 08:21:41 +0000, Antoon Pardon wrote: > On 2008-06-04, Marc 'BlackJack' Rintsch wrote: >> On Wed, 04 Jun 2008 09:34:58 +0000, Antoon Pardon wrote: >> >>> On 2008-06-04, Marc 'BlackJack' Rintsch wrote: >>> >>>>>> it makes sense to me to also test if they work as documented. >>>>> >>>>> If they affect the behaviour of some public component, that's where >>>>> the documentation should be. >>>> >>>> As I said they are public themselves for someone. >>> >>> Isn't that contradictory: "Public for someone" I always >>> thought "public" meant accessible to virtually anyone. >>> Not to only someone. >> >> For the programmer who writes or uses the private API it isn't really >> "private", he must document it or know how it works. > > How does that make it not private. Private has never meant "accessible > to noone". And sure he must document it and know how it works. But that > documentation can remain private, limited to the developers of the > product. It doesn't have to be publicly documented. If the audience is the programmer(s) who implement the "private" API it is not private but public. Even the "public" API is somewhat "private" to a user of a program that uses that API. The public is not virtually anyone here. Depends at which level you look in the system. Ciao, Marc 'BlackJack' Rintsch From mail at timgolden.me.uk Tue Jun 10 15:06:52 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 10 Jun 2008 20:06:52 +0100 Subject: Python doesn't understand %userprofile% In-Reply-To: References: Message-ID: <484ED0CC.6050004@timgolden.me.uk> drobinow at gmail.com wrote: > On Jun 10, 2:09 pm, Duncan Booth wrote: >> bsag... at gmail.com wrote: >>> In xp when I try os.path.getmtime("%userprofile/dir/file%") Python >>> bites back with "cannot find the path specified" Since my script has >>> to run on machines where the username is unspecified I need a fix. >>> Thanks in advance. >>>>> os.path.expanduser("~/dir/file") >> 'C:\\Documents and Settings\\Duncan/dir/file' > > "~" appears to look first at the HOME environment variable. > That is not necessarily the same as "USERPROFILE". On my machine it is > not. There was quite a debate over that on python-dev earlier this year. In short, it's not easy to identify exactly what "~" means on a Windows box. The implementer of that patch took the view that HOME comes first and then USERPROFILE, finally HOMEDRIVE/SHARE/PATH. On my machine at work, the latter should take precedence as they are set via my domain logon. Other people's mileage may vary. In addition, the code assumes that the home for any *other* user can always be derived from the *current* user's home. Which will not always be the case. All that is essentially why the user-specific functions exposed in win32profile rely on a logon token to operate. (Bit of a rant, but just to highlight that things are seldom what they seem). TJG From bearophileHUGS at lycos.com Thu Jun 12 13:13:17 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 12 Jun 2008 10:13:17 -0700 (PDT) Subject: Making wxPython a standard module? References: <3EEC30D2-4536-4CCA-9047-8542CFAF52EC@leafe.com> Message-ID: <53f780fb-84ae-46aa-8033-40731f7a5dca@d1g2000hsg.googlegroups.com> Andrea Gavana: > Maybe. But I remember a nice quote made in the past by Roger Binns (4 > years ago): > """ > The other thing I failed to mention is that the wxPython API isn't very > Pythonic. (This doesn't matter to people like me who are used to GUI > programming - the wxPython API is very much in the normal style for GUI > APIs.) > """ There was a WX wrapper project named WAX (http://zephyrfalcon.org/ waxapi/wx._core.Image.html ) that was trying to create a more pythonic API for WX that I have appreciated. But most people was not interested, so once the original developer has lost interest, no one else has improved the code, so the project has died... Bye, bearophile From Lie.1296 at gmail.com Mon Jun 9 12:12:25 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 9 Jun 2008 09:12:25 -0700 (PDT) Subject: Can I find out (dynamically) where a method is defined? References: Message-ID: <8f177e57-75af-4d12-8307-a146eb17736e@w8g2000prd.googlegroups.com> On Jun 9, 10:28?pm, allendow... at gmail.com wrote: > Hi All. > > In a complex inheritance hierarchy, it is sometimes difficult to find > where a > method is defined. ?I thought it might be possible to get this info > from the > method object itself, but it looks like maybe not. ?Here is the test > case I tried: > > class A(object): > ? ? def method(): > ? ? ? ? pass > > class B(A): > ? ? pass > > a = A() > b = B() > > print a.method > print b.method > > Since B inherits method from A, I thought that printing b.method might > tell > me that the definition is in A, but no. ?Here's the output: > > > > > > > This in indistinguishable from the case where B overrides method. > > So, is there any way to inspect a method to see where (in what class) > it > is defined? I don't know if there is other easier methods, but if you have access to the source code, you can always add a print function. class A(object): def method(self): print 'Entering A.method' ... The rest of the codes ... class B(A): def method(self): print 'Entering B.method' ... The rest of the codes ... class C(A): pass If you don't have access to the source code, that means you shouldn't need to worry about it. A rather odd thing I just noticed is this: class A(object): def method(self): pass class B(A): def method(self): pass class C(A): pass print A.method == B.method ## False print A.method == C.method ## True From zapwireDASHgroups at yahoo.com Wed Jun 4 16:20:16 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Wed, 4 Jun 2008 13:20:16 -0700 Subject: php vs python References: <6ak1pjF379qfdU2@mid.uni-berlin.de> Message-ID: <8OC1k.150152$Tj3.133613@en-nntp-02.dc1.easynews.com> "Marc 'BlackJack' Rintsch" wrote in message news:6ak1pjF379qfdU2 at mid.uni-berlin.de... > I think you are talking about something a little different than Arnaud. Ah, OK. > Other old habits from people coming to Python are: using indexes where they > are not needed, trivial getters and setters, putting *everything* into > classes and every class into a module, and so on. Some of that is more political/policy than anything having to do with the language. Python likes to make it blatantly obvious that a lot of it is unnecessary, so it puts the "control freak" type of programmers on the defensive when, e.g., class variables and methods aren't private by default. (Guido's "we're all conesenting adults here" is of course a good response to this!) > Another difference are internal versus external iterators. In Python you > write the loop outside the iterable and pull the items out of it. In > other languages (Ruby, Io, .) iterables do internal iteration and you give > them a function where all item are "pushed" into one at a time. The Python method is -- IMO -- rather more powerful here, even if the whole protocol is somewhat less explciti than the Ruby/Io/etc. approach. > What makes C++ a "first class" language? My somewhat arbitrary definition is something along the lines of a language with most all of the "contemporary" features expected of languages (e.g., "old school" procedural languages like C/Pascal/Fortran 77 don't count) that are targeting at writing everything from small utilities to programs of various sizes to full-blown operating systems. > And did you quote "first class" > for the same reason than I did? ;-) Probably... C++ is kinda like the McMaster-Carr catalog, whereas Python is a well-stocked hardware store with knowledgable salespeople. ---Joel From __peter__ at web.de Mon Jun 30 09:51:24 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 30 Jun 2008 15:51:24 +0200 Subject: List Performance References: <42358e0b-a351-4862-8f6a-1938eedeff6c@s21g2000prm.googlegroups.com> <2eydnaP-saOZQfXVnZ2dnUVZ_qvinZ2d@comcast.com> Message-ID: Larry Bates wrote: > Peter Otten wrote: >> Ampedesign wrote: >> >>> If I happen to have a list that contains over 50,000 items, will the >>> size of the list severely impact the performance of appending to the >>> list? >> >> No. >> >> $ python -m timeit -n20000 -s"items = []" "items.append(42)" >> 20000 loops, best of 3: 0.554 usec per loop >> $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" >> 20000 loops, best of 3: 0.529 usec per loop >> >> http://wiki.python.org/moin/TimeComplexity >> >> Peter > > Peter, > > So its actually faster to append to a long list than an empty one? That > certainly would not have been intuitively obvious now would it? You shouldn't blindly trust the numbers. Here's what happens if I repeat the measurements a few times: $ python -m timeit -n20000 -s"items = []" "items.append(42)" 20000 loops, best of 3: 0.531 usec per loop $ python -m timeit -n20000 -s"items = []" "items.append(42)" 20000 loops, best of 3: 0.511 usec per loop $ python -m timeit -n20000 -s"items = []" "items.append(42)" 20000 loops, best of 3: 0.512 usec per loop $ python -m timeit -n20000 -s"items = []" "items.append(42)" 20000 loops, best of 3: 0.51 usec per loop $ python -m timeit -n20000 -s"items = []" "items.append(42)" 20000 loops, best of 3: 0.514 usec per loop $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" 20000 loops, best of 3: 0.506 usec per loop $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" 20000 loops, best of 3: 0.512 usec per loop $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" 20000 loops, best of 3: 0.543 usec per loop $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" 20000 loops, best of 3: 0.522 usec per loop $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" 20000 loops, best of 3: 0.51 usec per loop The difference is within the error margin. All you can say is that both operations take roughly the same time. In general, if no error margin (e. g. 0.5+-0.1) is given that is always a warning sign, be it opinion polls or timeit output. Peter From raashidbhatt at gmail.com Thu Jun 19 01:41:54 2008 From: raashidbhatt at gmail.com (raashid bhatt) Date: Wed, 18 Jun 2008 22:41:54 -0700 (PDT) Subject: good Message-ID: <0818dbbe-5019-4b0a-8254-4591d77d8084@f24g2000prh.googlegroups.com> I like your programming choice becaz python is safe than c or c++ or any other compiled languages as it protects against buffer overflow which causes potentail security problems i am wanted to know how many requests can it handle is it configurable for that.....
Raashid Bhatt (C) From zapwireDASHgroups at yahoo.com Sun Jun 1 19:42:24 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Sun, 1 Jun 2008 16:42:24 -0700 Subject: php vs python References: Message-ID: "Ethan Furman" wrote in message news:mailman.1782.1212179802.12834.python-list at python.org... > Jerry Stuckle wrote: > > As I've said before - good programmers can write good code in any > > language. > So... an eloquent speaker of English is also an eloquent speaker of > Spanish/French/German? There's potentially a large difference between a "good" speaker of English/German/etc. vs. "eloquent." I'd tend to agree with Jerry that if you can write "good" code in one language, you can in pretty much any other as well... but that doesn't imply you're necessarily "eloquent" in any languages. :-) Eloquence is nice, but eradicating "bad" code in this world is about a million times more important than attempting to move people from "good" code to "eloquent" code. To be Pythonic here, "eloquent" code would perhaps often have clear, clean list comprehensions used when "good" code would use a "for" loop but still be easy to follow as well and perfectly acceptable in the vast majority of cases. From buzzard at urubu.freeserve.co.uk Fri Jun 13 05:43:14 2008 From: buzzard at urubu.freeserve.co.uk (duncan smith) Date: Fri, 13 Jun 2008 10:43:14 +0100 Subject: boolian logic In-Reply-To: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> References: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> Message-ID: marc wyburn wrote: > HI all, I'm a bit stuck with how to work out boolian logic. > > I'd like to say if A is not equal to B, C or D: > do something. > > I've tried > > if not var == A or B or C: > and various permutations but can't seem to get my head around it. I'm > pretty sure I need to know what is calulated first i.e the not or the > 'OR/AND's > > thanks, Marc. There's a number of ways of coding it. How about, if not var in [A, B, C]: #do stuff Duncan From tjreedy at udel.edu Sun Jun 29 14:54:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 29 Jun 2008 14:54:25 -0400 Subject: tkinter, loading image error, TclError: couldn't recognize data in image file "C:/users/me/desktop/images/blob4.jpg" In-Reply-To: <0ae49ec6-2d6a-48bd-9112-dc0237363822@25g2000hsx.googlegroups.com> References: <0ae49ec6-2d6a-48bd-9112-dc0237363822@25g2000hsx.googlegroups.com> Message-ID: defn noob wrote: > from Tkinter import * > import os > > master = Tk() > w = Canvas(master, width=800, height=600) > > print os.path.exists('C:/me/saftarn/desktop/images/blob4.jpg') > > im = PhotoImage(file = 'C:/users/saftarn/desktop/images/blob4.jpg') > #im = file = 'C:/users/me/desktop/images/blob4.jpg' > pic = w.create_image(0, 0, image = im, anchor = NW) > > #image = open('C:/users/saftarn/desktop/images/blob.png') > > colors = [] > for x in range(1, 800): > for y in range(1, 600): > pic = w.find_closest(x, y)[0] > obj = objects[pic] > colors.append(obj.get(int(x), int(y))) > > print colors > > > > True > > Traceback (most recent call last): > File "C:/Python25/Progs/ImageVideoSearch/imId.py", line 9, in > > im = PhotoImage(file = 'C:/users/me/desktop/images/blob4.jpg') > File "C:\Python25\lib\lib-tk\Tkinter.py", line 3270, in __init__ > Image.__init__(self, 'photo', name, cnf, master, **kw) > File "C:\Python25\lib\lib-tk\Tkinter.py", line 3226, in __init__ > self.tk.call(('image', 'create', imgtype, name,) + options) > TclError: couldn't recognize data in image file "C:/users/me/desktop/ > images/blob4.jpg" > > > > it has worked before opening and displaying a file like this, anything > to do with python 2.52, upgraded from 2.5.1 Did it work with that exact file? Have you tried other files that did work with 2.5.1? The error comes from tcl/tk, not Python. I expect that the version of tcl/tk delivered with 2.5.2 is exactly the same as that delivered with 2.5.1, just to avoid such problems. Note that even if one program displays a file it may still be slightly corrupt and properly fail to display with another. If you have an image editor, you might try opening and saving (different name) without changing. tjr From tjreedy at udel.edu Tue Jun 24 01:40:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Jun 2008 01:40:03 -0400 Subject: An idiom for code generation with exec In-Reply-To: <0967da3a-1fea-401e-896d-9c099b3054ce@c58g2000hsc.googlegroups.com> References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485f4f35$0$28417$426a74cc@news.free.fr> <0967da3a-1fea-401e-896d-9c099b3054ce@c58g2000hsc.googlegroups.com> Message-ID: eliben wrote: > And while we're on the topic of what compilation means in Python, It depends on the implementation. I'm > not sure I fully understand the difference between compiled (.pyc) > code and exec-ed code. Is the exec-ed code turned to bytecode too, > i.e. it will be as efficient as compile-d code ? CPython always compiles to bytecode before executing. There is no alternative execution path. From jsloop at austin.rr.com Wed Jun 18 21:02:40 2008 From: jsloop at austin.rr.com (John Sloop) Date: Wed, 18 Jun 2008 20:02:40 -0500 Subject: Python email server Message-ID: <008301c8d1a8$2c74c460$855e4d20$@rr.com> I am starting to build a Python email server. Before assembling the individual pieces I am wondering if there is a prebuilt package anyone would recommend? Thanks in advance for your advice and guidance. John S. -------------- next part -------------- An HTML attachment was scrubbed... URL: From carsten.haese at gmail.com Wed Jun 11 10:14:58 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Wed, 11 Jun 2008 10:14:58 -0400 Subject: problems with opening files due to file's path In-Reply-To: <77acc29a-fffa-44d6-b07b-6bcf8b5bdd74@h1g2000prh.googlegroups.com> References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> <77acc29a-fffa-44d6-b07b-6bcf8b5bdd74@h1g2000prh.googlegroups.com> Message-ID: Lie wrote: > In most GUI toolkits (including Tkinter) and raw_input() function, > when you input a string (using the textbox, a.k.a Entry widget) it > would automatically be escaped for you, so when you input 'path\path > \file.txt', the GUI toolkit would convert it into 'path\\path\ > \file.txt'. That's incorrect. If you enter text into a text box or in raw_input(), *no* conversion of backslashes is happening. A backslash entered in raw_input is just a backslash. A backslash entered in a textbox is just a backslash. A backslash read from a file is just a backslash. A "conversion" happens when you print the repr() of a string that was obtained from raw_input or from a text box, because repr() tries to show the string literal that would result in the contents, and in a string literal, a backslash is not (always) a backslash, so repr() escapes the backslashes: py> text = raw_input("Enter some text: ") Enter some text: This is a backslash: \ py> print text This is a backslash: \ py> print repr(text) 'This is a backslash: \\' As you can see, I entered a single backslash, and the string ends up containing a single backslash. Only when I ask Python for the repr() of the string does the backslash get doubled up. -- Carsten Haese http://informixdb.sourceforge.net From rubrum at pacbell.net Tue Jun 17 20:13:36 2008 From: rubrum at pacbell.net (Michael Press) Date: Tue, 17 Jun 2008 17:13:36 -0700 Subject: Multiprecision arithmetic library question. Message-ID: I already compiled and installed the GNU multiprecision library on Mac OS X, and link to it in C programs. How do I link to the library from Python? I do not want to download and install redundant material. (I am new to Python) -- Michael Press From alexnbryan at gmail.com Fri Jun 27 13:41:13 2008 From: alexnbryan at gmail.com (Alexnb) Date: Fri, 27 Jun 2008 10:41:13 -0700 (PDT) Subject: using urllib2 In-Reply-To: <200806271227.17081.maric@aristote.info> References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> Message-ID: <18160312.post@talk.nabble.com> Okay, I tried to follow that, and it is kinda hard. But since you obviously know what you are doing, where did you learn this? Or where can I learn this? Maric Michaud wrote: > > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit?: >> I have never used the urllib or the urllib2. I really have looked online >> for help on this issue, and mailing lists, but I can't figure out my >> problem because people haven't been helping me, which is why I am here! >> :]. >> Okay, so basically I want to be able to submit a word to dictionary.com >> and >> then get the definitions. However, to start off learning urllib2, I just >> want to do a simple google search. Before you get mad, what I have found >> on >> urllib2 hasn't helped me. Anyway, How would you go about doing this. No, >> I >> did not post the html, but I mean if you want, right click on your >> browser >> and hit view source of the google homepage. Basically what I want to know >> is how to submit the values(the search term) and then search for that >> value. Heres what I know: >> >> import urllib2 >> response = urllib2.urlopen("http://www.google.com/") >> html = response.read() >> print html >> >> Now I know that all this does is print the source, but thats about all I >> know. I know it may be a lot to ask to have someone show/help me, but I >> really would appreciate it. > > This example is for google, of course using pygoogle is easier in this > case, > but this is a valid example for the general case : > >>>>[207]: import urllib, urllib2 > > You need to trick the server with an imaginary User-Agent. > >>>>[208]: def google_search(terms) : > return urllib2.urlopen(urllib2.Request("http://www.google.com/search?" > + > urllib.urlencode({'hl':'fr', 'q':terms}), > headers={'User-Agent':'MyNav > 1.0 > (compatible; MSIE 6.0; Linux'}) > ).read() > .....: > >>>>[212]: res = google_search("python & co") > > Now you got the whole html response, you'll have to parse it to recover > datas, > a quick & dirty try on google response page : > >>>>[213]: import re > >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

.*?

', > res) ] > ...[229]: > ['Python Gallery', > 'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des Monty ...', > 'Re: os x, panther, python & co: msg#00041', > 'Re: os x, panther, python & co: msg#00040', > 'Cardiff Web Site Design, Professional web site design services ...', > 'Python Properties', > 'Frees < Programs < Python < Bin-Co', > 'Torb: an interface between Tcl and CORBA', > 'Royal Python Morphs', > 'Python & Co'] > > > -- > _____________ > > Maric Michaud > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/using-urllib2-tp18150669p18160312.html Sent from the Python - python-list mailing list archive at Nabble.com. From bearophileHUGS at lycos.com Thu Jun 19 08:53:18 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 19 Jun 2008 05:53:18 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <1ea1731d-9de9-4e73-9c08-e9f5572b9fd6@t54g2000hsg.googlegroups.com> <1a8797c6-a165-49b1-82de-94a6054cf856@z16g2000prn.googlegroups.com> Message-ID: dbpoko...: > Which should be 12 bytes on a 32-bit machine. I thought the space for > growth factor for dicts was about 12% but it is really 100%. (Please ignore the trailing ".2" in my number in my last post, such precision is silly). My memory value comes from experiments, I have created a little program like this: from memory import memory def main(N): m1 = memory() print m1 d = {} for i in xrange(N): d[i] = None m2 = memory() print m2 print float((m2 - m1) * 1024) / N main(20000000) Where memory is a small module of mine that calls a little known program that tells how much memory is used by the current Python process. The results for that run n=20000000 are (first two numbers are kilobytes, the third number is byte/pair): 1876 633932 32.3612672 It means to store 20_000_000 pairs it requires about 647_000_000 bytes, Python 2.5.2, on Win. Bye, bearophile From nick at craig-wood.com Sun Jun 8 15:30:46 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sun, 08 Jun 2008 14:30:46 -0500 Subject: time.clock() or Windows bug? References: Message-ID: Theo v. Werkhoven wrote: > In this code I read out an instrument during a user determined period, > and save the relative time of the sample (since the start of the test) > and the readback value in a csv file. > > from datetime import * > from time import * > from visa import * > from random import * > [..] > for Reading in range(Readings): > RelTimeOfSample = "%.1f" % clock() > #PwrMtr.write("READ?") > #Sample = "%.3f" % float(PwrMtr.read()) > Sample = "%.3f" % (uniform(8.9,9.3)) # Simulation of reading. > print "Sample %s, at %s seconds from start; Output power is: %s dBm" > % (Reading+1, RelTimeOfSample, Sample) > writer.writerow([RelTimeOfSample, Sample]) > ResultFile.flush() > sleep(6.6) > > Output: > Sample 1, at 0.0 seconds from start; Output power is: 8.967 dBm [snip] > Sample 17, at 105.7 seconds from start; Output power is: 9.147 dBm > Sample 18, at 112.4 seconds from start; Output power is: 9.284 dBm > Sample 19, at 119.0 seconds from start; Output power is: 9.013 dBm > Sample 20, at 125.6 seconds from start; Output power is: 8.952 dBm > Sample 21, at 91852.8 seconds from start; Output power is: 9.102 dBm > Sample 22, at 91862.7 seconds from start; Output power is: 9.289 dBm > Sample 23, at 145.4 seconds from start; Output power is: 9.245 dBm > Sample 24, at 152.0 seconds from start; Output power is: 8.936 dBm [snip] > But look at the timestamps of samples 21, 22 and 43. > What is causing this? > I've replaced the time.clock() with time.time(), and that seems to > solve the problem, but I would like to know if it's something I > misunderstand or if it's a problem with the platform (Windows Server > 2003) or the time.clock() function. time.clock() uses QueryPerformanceCounter under windows. There are some known problems with that (eg with Dual core AMD processors). See http://msdn.microsoft.com/en-us/library/ms644904.aspx And in particular On a multiprocessor computer, it should not matter which processor is called. However, you can get different results on different processors due to bugs in the basic input/output system (BIOS) or the hardware abstraction layer (HAL). To specify processor affinity for a thread, use the SetThreadAffinityMask function. I would have said time.time is what you want to use anyway though because under unix time.clock() returns the elapsed CPU time which is not what you want at all! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From karsten.heymann at blue-cable.net Fri Jun 13 08:12:40 2008 From: karsten.heymann at blue-cable.net (Karsten Heymann) Date: Fri, 13 Jun 2008 14:12:40 +0200 Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> Message-ID: <878wx9leiv.fsf@ara.blue-cable.net> Hi Mark, Mark writes: > I have a scenario where I have a list like this: > > User Score > 1 0 > 1 1 > 1 5 > 2 3 > 2 1 > 3 2 > 4 3 > 4 3 > 4 2 > > And I need to add up the score for each user to get something like > this: > > User Score > 1 6 > 2 4 > 3 2 > 4 8 > > Is this possible? If so, how can I do it? I've tried looping through > the arrays and not had much luck so far. Although your problem has already been solved, I'd like to present a different approach which can be quite a bit faster. The most common approach seems to be using a dictionary: summed_up={} for user,vote in pairs: if summed_up.has_key(user): summed_up[user]+=vote else: summed_up[user]=vote But if the list of users is compact and the maximum value is known before, the using a list and coding the user into the list position is much more elegant: summed_up=list( (0,) * max_user ) for user,vote in pairs: summed_up[user] += vote I've run a quick and dirty test on these approaches and found that the latter takes only half the time than the first. More precisely, with about 2 million pairs, i got: * dict approach: 2s (4s with "try: ... except KeyError:" instead of the "if") * list approach: 0.9s BTW this was inspired by the book "Programming Pearls" I read some years ago where a similar approach saved some magnitudes of time (using a bit field instead of a list to store reserved/free phone numbers IIRC). Yours, Karsten From bruno.42.desthuilliers at websiteburo.invalid Fri Jun 27 11:44:28 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 27 Jun 2008 17:44:28 +0200 Subject: what is meaning of "@" in pyhon program. In-Reply-To: <4bfb891d-7a7b-45bc-b126-1d485c9206ee@m44g2000hsc.googlegroups.com> References: <88990b3d-1916-413f-83b9-796aabf43623@l28g2000prd.googlegroups.com> <19aa4978-242b-4732-b072-aa5ff16975b0@27g2000hsf.googlegroups.com> <486502bf$0$6426$426a74cc@news.free.fr> <4bfb891d-7a7b-45bc-b126-1d485c9206ee@m44g2000hsc.googlegroups.com> Message-ID: <48650adb$0$7975$426a74cc@news.free.fr> Damon Getsman a ?crit : > Okay, maybe I just didn't understand the websites that were given as > examples as to 'decoration'. I first came across the unusual '@' when > I was browsing through some extreme beginner's information on os.x > method descriptions. I asked some other people about it and they had > no idea what it meant. I don't _THINK_ that the decoration definition > fits, though, because the examples that I saw it in had it prefixing > an if conditional & a for loop. > > ie: > @if os.exists(foo): > etc > etc > > and > > @for blah: > etc > etc This is not valid Python. period. From exarkun at divmod.com Fri Jun 20 13:17:57 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 20 Jun 2008 13:17:57 -0400 Subject: Python "is" behavior In-Reply-To: <537daeff-e283-47bf-b539-3e6c99aabe5a@m45g2000hsb.googlegroups.com> Message-ID: <20080620171757.4714.198154922.divmod.quotient.11254@ohm> On Fri, 20 Jun 2008 10:07:56 -0700 (PDT), George Sakkis wrote: >On Jun 20, 12:45 pm, michalis.avr... at gmail.com wrote: >> On Jun 20, 9:42 am, George Sakkis wrote: >> >> >> >> > On Jun 20, 12:31 pm, michalis.avr... at gmail.com wrote: >> >> > > I am not certain why this is the case, but... >> >> > > >>> a = 256 >> > > >>> b = 256 >> > > >>> a is b >> >> > > True >> >> > > >>> a = 257 >> > > >>> b = 257 >> > > >>> a is b >> >> > > False >> >> > > Can anyone explain this further? Why does it happen? 8-bit integer >> > > differences? >> >> > No, implementation-dependent optimization (caching). For all we know, >> > the next python version may cache up to 1024 or it may turn off >> > caching completely; do not rely on it. More generally, do not use 'is' >> > when you really mean '=='. >> >> > George >> >> Thank you George. I am very curious about some of these internal >> Python things that I keep stumbling upon through friends. And thank >> you for all the help! > >As far it's plain curiosity it's ok, but it's a small implementation >detail you shouldn't rely on. There's nothing magic about 256, just >the size decided for 2.5. If you tried it on 2.4 you'd get: > >Python 2.4.2 (#1, Mar 8 2006, 13:24:00) >[GCC 3.4.4 20050721 (Red Hat 3.4.4-2)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> a=99 >>>> b=99 >>>> a is b >True >>>> a=100 >>>> b=100 >>>> a is b >False > >I was more surprised by the following: > >Python 2.5.1 (r251:54863, May 8 2007, 14:46:30) >[GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> a= 123456; b=123456; a is b >True > >For some reason, stacking multiple statements reuses the same object. > This is because using the ";" puts the statements into the same compilation unit as each other. So secretly an integer object is created for 123456 and then a and b are both given a reference to it. This is a different mechanism than the other case, where the builtin integer cache causes the literal 100 to refer to the same object each time it is evaluated. Jean-Paul From dwahli at gmail.com Fri Jun 6 02:56:40 2008 From: dwahli at gmail.com (dwahli at gmail.com) Date: Thu, 5 Jun 2008 23:56:40 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> Message-ID: <769c54bf-8664-4179-bd17-c18705320606@27g2000hsf.googlegroups.com> On Jun 6, 8:44?am, "Terry Reedy" wrote: > > Of course, enumerate(iterable) is just a facade over zip(itertools.count(), > iterable) So you could write: gen = (x for x in itertools.izip(itertools.count(8), [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3])) print list(gen) Using zip like you own example is the best option. If you have a huge amount of data and only want to iterate over the result, using a generator is probably better: gen = (x for x in itertools.izip(itertools.count(8), [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3])) for i, j in gen: ... your code here ... From mark.hachey at gmail.com Sat Jun 14 17:33:24 2008 From: mark.hachey at gmail.com (Hachey) Date: Sat, 14 Jun 2008 14:33:24 -0700 (PDT) Subject: sorting a file References: Message-ID: <90f51884-5d70-40c9-b05c-0f3b3f7cc8d1@e39g2000hsf.googlegroups.com> On Jun 14, 12:00 pm, jim-on-linux wrote: > On Saturday 14 June 2008 03:15, Beema > > shafreen wrote: > > Hi all, > > > I have a file with three columns i need > > to sort the file with respect to the third > > column. How do I do it uisng python. I > > used Linux command to do this. Sort but i > > not able to do it ? can any body ssuggest > > me > > I have used this method to solve similar > problems. > > This is a consept of how to do what you want, > but you will have to work a little to get it > right. > > You might try something like this; > > Dict = {} ##create a dictionary > > make a list of all column3 values > > for loop colum3 values > > Make these values the key in a dictionary > If the values are long, you can use the first > 7 to 15 characters if you want. > > use this key to equal all the values in the > other columns on the same row. > > Dict[column3] = column1, column2, column3 > > once the dictionary is made > > get the dictionary key > x = Dict.keys() ## get the keys from Dict > > x.sort() # produce a sorted list of keys of > column3 > > Loop these sorted keys to extract from the > dictionary the values related to each > > jim-on-linux > http://:inqvista.com Here's another way to attack it. Make a class that takes your columns as arguments. define an operator on that class to get the comparison you want. make a list that is your rows, and call sort. here's an example using only two columns class twoColumns : def __init__(self, c1 = 0, c2 = 0) : self.c1 = c1 self.c2 = c2 #just use this for debugging if you want to see everything def getVals(self): print self.c1, self.c2 #order members of this class by the second column def __lt__(c,d): if (c.c2 < d.c2) : return 1 else : return 0 #end class definition Here's what happened when I used this class. >>> r1 = twoColumns(3,4) >>> r2 = twoColumns(1,5) >>> test = [r1,r2] #this is already sorted >>> test[0].getVals() 3 4 >>> test[1].getVals() 1 5 >>> test.sort() #and the sort looks the same >>> test[0].getVals() 3 4 >>> test[1].getVals() 1 5 >>> test = [r2,r1] #I reversed the rows >>> test[0].getVals() 1 5 >>> test[1].getVals() 3 4 >>> test.sort() #and we get what we want >>> test[0].getVals() 3 4 >>> test[1].getVals() 1 5 I think that does what you're asking. From ptmcg at austin.rr.com Tue Jun 17 02:20:51 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 16 Jun 2008 23:20:51 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <4856e80c$0$30401$9b622d9e@news.freenet.de> <97b828d8-e64c-47db-8b8e-d403e8076756@x35g2000hsb.googlegroups.com> <48574B8D.6010102@v.loewis.de> Message-ID: On Jun 17, 12:28?am, "Martin v. L?wis" wrote: > > My guess is that the two main memory allocate/deallocate cases are 1) > > appending a new item to the end, and 2) GC'ing the entire data > > structure. ?I would optimize these 2 at the expense of all others. > > Does that include dictionary lookups? > > Regards, > Martin Well, I did (try to) qualify my guess as pertaining specifically to memory allocate/deallocate cases, the other topics in the nearby posts were talking about updates to the odict, so I hope I can be forgiven this oversight. But you're right, the keyed access is one of the main reasons this is being done with an odict instead of just a list of tuples. The point I was trying to make was that sometimes, the GC case occurs far more frequently than other update methods, yet is overlooked because it happens invisibly to most Python users. I worked on a project a while ago where there was a huge performance penalty in releasing a list structure, because each node was freed individually, causing surrounding freelist entries to be updated for every node. In typical worst-case scenario fashion, a second list was built at the same time as the first, and the default system memory allocator interleaved the list nodes. The truly frustrating part was that at this point in the program, we were trying to free *all* the nodes in *both* lists, and would have preferred to just release the whole chunk of memory, if it had just been allocated in a large chunk instead of a node at a time. I implemented a zone-based memory allocator, so that nodes were allocated within a memory zone, but when we were done, we just released the entire zone, with tremendous improvement in system performance. But what kind of keyed access is likely to be used on an odict? For those cases where all of the items are desired, then I would recommend that the odict iterator be preferred, for this type of retrieval: for k,v in odictvar.iteritems(): # do something with key k and value v and discourage this usage: for k in odictvar.keys(): # or iterkeys() # do something with key k and value odictvar[k] How about this as a simple first approach? Let's assume that the nominal usage pattern for an odict is 1) create all entries in the odict, probably using append, 2) access some or all of the entries, either by iterating over the keys or values, or by keyed access to specific values, and 3) delete the odict. Have the odict keep an internal dict representing the keyed lookups, and have this internal dict set to null whenever the odict is updated. When the odict is accessed by specific key, the internal dict is used - if it null, it is built using dict(odict.iteritems()). In the nominal usage, this dict will only be built once, since the keyed accesses wont begin until after all of the key-value pairs have been added to the odict. Or as a first-first approach (to avoid premature optimization), just implement the odict as a list of tuples, and do linear search for matching key if accessed by key. I would bias any performance choices about keyed access toward cases where the queried key exists in the odict - I think that in those cases where odicts are used, such as ORMs and XML, the keys for a particular odict are known and expected to exist. Those applications where the keys are not known are likely to be meta-type apps, like debuggers and introspection GUIs. I contend that the meat-and- potatoes production apps will be those like database queries - when I get an odict back after querying an EMPLOYEES table, I really should reasonably expect odictvar["EMPNO"] to exist. And what would be the conditions of an abusive form of odict? How about an application log kept in an odict, keyed by timestamp? This could have many 1000's of entries, and yet, I would guess that an odict would be the wrong data structure for this, and that a list of tuples or LogMessage objects would be more appropriate. But someone is likely to do it - if they do, what will happen? Perhaps trying to anticipate "abusive" or degenerate uses of an odict might shed some light on ways to avoid, discourage, or maybe even accommodate these uses in odict. Well, this has become something of a rant, and a speculative one at that, but I think the "delete the entire data structure" memory case should be given reasonably high design attention. (And maybe this is already the norm in Python development - I'm really quite ignorant of this process, not being in the Python development circle.) Always nice to hear from you Martin - cheers! -- Paul From sjmachin at lexicon.net Thu Jun 12 07:47:43 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 12 Jun 2008 04:47:43 -0700 (PDT) Subject: using re module to find " but not " alone ... is this a BUG in re? References: Message-ID: <5aeb32bd-923f-4b98-952b-06097ac8479d@v1g2000pra.googlegroups.com> On Jun 12, 7:11 pm, anton wrote: > Hi, > > I want to replace all occourences of " by \" in a string. > > But I want to leave all occourences of \" as they are. > > The following should happen: > > this I want " while I dont want this \" > > should be transformed to: > > this I want \" while I dont want this \" > > and NOT: > > this I want \" while I dont want this \\" > > I tried even the (?<=...) construction but here I get an unbalanced paranthesis > error. Sounds like a deficit of backslashes causing re to regard \) as plain text and not the magic closing parenthesis in (?<=...) -- and don't you want (? > It seems tha re is not able to do the job due to parsing/compiling problems > for this sort of strings. Nothing is ever as it seems. > > Have you any idea?? For a start, *ALWAYS* use a raw string for an re pattern -- halves the backslash pollution! > > > re.findall("[^\\]\"","this I want \" while I dont want this \\\" ") and if you have " in the pattern, use '...' to enclose the pattern so that you don't have to use \" > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\re.py", line 175, in findall > return _compile(pattern, flags).findall(string) > File "C:\Python25\lib\re.py", line 241, in _compile > raise error, v # invalid expression > error: unexpected end of regular expression As expected. What you want is: >> import re >> text = r'frob this " avoid this \", OK?' >>> text 'frob this " avoid this \\", OK?' >> re.sub(r'(?> HTH, John From tjreedy at udel.edu Tue Jun 24 20:46:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Jun 2008 20:46:03 -0400 Subject: Sequence iterators with __index__ In-Reply-To: <119bb268-2064-4128-8006-f5564f0c62f8@q27g2000prf.googlegroups.com> References: <433c6aca-745e-4c9f-b182-d76291449829@m73g2000hsh.googlegroups.com> <119bb268-2064-4128-8006-f5564f0c62f8@q27g2000prf.googlegroups.com> Message-ID: schickb wrote: > On Jun 24, 3:45 pm, Matimus wrote: >>> I think it would be useful if iterators on sequences had the __index__ >>> method so that they could be used to slice sequences. I was writing a >>> class and wanted to return a list iterator to callers. I then wanted >>> to let callers slice from an iterator's position, but that isn't >>> supported without creating a custom iterator class. Creating custom classes is what the class statement is for. See below. >> Could you post an example of what you are talking about? I'm not >> getting it. > > Interactive mock-up: > >>>> a = ['x','y','z'] >>>> it = iter(a) >>>> a[it:] > ['x', 'y', 'z'] >>>> it.next() > 'x' >>>> a[it:] > ['y', 'z'] >>>> a[:it] > ['x'] >>>> it.next() > 'y' >>>> a[it:] > ['z'] > > This lets you use sequence iterators more general position indicators. > Currently if you want to track a position and slice from a tracked > position you must do it manually with an integer index. It's not > difficult, but given that sequence iterators already do that already > it seems redundant (and of course more error prone). Python's iterator protocol is intentionally simple and general. Wanting to slice while iterating is a *very* specialized usage. In any case: A. If the iterator uses in incrementing index to iterate, you want access. B. Using an iterator as an integer will strike most people as conceptually bizarre; it will never be accepted. C. Doing so is unnecessary since the internal index can just as easily be exposed as an integer attribute called 'index' or, more generally, 'count'. a[it.count:] looks *much* better. D. You can easily add .index or .count to any iterator you write. The iterator protocol is a minimum rather than maximum specification. E. You can easily wrap any iterable/iterator in an iterator class that provides .count for *any* iteration process. Slicing is not the only possible use of such an attribute. class indexerator(): def __inti__(self, iterable): self.it = iter(iterable) self.count = 0 def __iter__(self): return self def __next__(self): # 3.0 tem = self.it.next() self.count += 1 return tem .count is always the number of items returned. It is also the index of the next item to be returned if (but only if() the base iterable exists and is an indexable sequence. F. Even this should be unnecessary for most usages. Built-in function enumerate(iterable) generates count,item pairs in much the same manner: >> In any case, the first step is writing a PEP.http://www.python.org/dev/peps/ Discussion usually comes first. > Ok thanks, but I do want some idea of interest level before spending a > bunch of time on this. Even the developers sometimes take this precaution. Many ideas never make it to the PEP stage. I see no need for a change in Python here. Terry Jan Reedy From goldwamh at slu.edu Wed Jun 4 23:09:45 2008 From: goldwamh at slu.edu (Michael H. Goldwasser) Date: 04 Jun 2008 22:09:45 -0500 Subject: Books for programmers References: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> <32791EDC-1033-4B65-BFB5-DF1CF71EF20D@comhem.se> Message-ID: Dick Moores writes: > Do not neglect the 2008 book, "Object-Oriented Programming in Python", > by Goldwasser and Letscher. > > > > Dick Moores I'll note that our book is designed as a "CS1" text, and thus intended primarly for beginners. So its probably not a match for the original poster who wants a more advanced Python book. That said, I think its a great book for those with less experience. +----------------------------------------------- | Michael Goldwasser | Associate Professor | Dept. Mathematics and Computer Science | Saint Louis University | 220 North Grand Blvd. | St. Louis, MO 63103-2007 From ladasky at my-deja.com Wed Jun 4 12:03:26 2008 From: ladasky at my-deja.com (John Ladasky) Date: Wed, 4 Jun 2008 09:03:26 -0700 (PDT) Subject: Import, site packages, my modules, Windows vs. Linux References: <4993bd3d-22aa-4e0d-a593-38c0f5e2d69a@m44g2000hsc.googlegroups.com> <878wxmm0fa.fsf@benfinney.id.au> Message-ID: On Jun 3, 6:52 pm, Ben Finney wrote: > John Ladasky writes: > > I want to know what is the *recommended* way to integrate my own > > personal modules with Python. Thanks! > > You want the 'distutils' documentation > and the documents > that it references, which will lead you to write a 'setup.py' module > for your package. Many thanks, Ben, distutils was exactly what I needed. It was a little strange to grasp the concept that I would be "distributing" my module to myself -- but once I got over that mental hurdle, it worked perfectly. From hall.jeff at gmail.com Mon Jun 23 15:50:58 2008 From: hall.jeff at gmail.com (hall.jeff at gmail.com) Date: Mon, 23 Jun 2008 12:50:58 -0700 (PDT) Subject: tuple.index() and tuple.count() Message-ID: <0411a4b3-7b99-41f9-980e-dd81845101bd@y21g2000hsf.googlegroups.com> Before the inevitable response comes, let me assure you I've read through the posts from Guido about this. 7 years ago Guido clearly expressed a displeasure with allowing these methods for tuple. Let me lay out (in a fresh way) why I think we should reconsider. 1) It's counterintuitive to exclude them: It makes very little sense why an indexable data structure wouldn't have .index() as a method. It makes even less sense to not allow .count() 2) There's no technical reason (that I'm aware of) why these can't be added 3) It does not (contrary to one of Guido's assertions) require any relearning of anything. It's a new method that could be added without breaking any code whatsoever (there isn't even a UserTuple.py to break) 4) The additional documentation is relatively minute (especially since it could be copied and pasted virtually verbatim from the list methods 5) It's MORE Pythonic to do it this way (more intuitive, less boilerplate) 6) It jives with the help file better. One of Guido's many stated reasons was that tuples are for heterogeneous sequences and lists are for homogeneous sequences. While this may be hypothetically true, the help file does not come close to pointing you in this direction nor does the implementation of the language. example: "Tuples have many uses. For example: (x, y) coordinate pairs, employee records from a database, etc. Tuples, like strings, are immutable: it is not possible to assign to the individual items of a tuple (you can simulate much of the same effect with slicing and concatenation, though). It is also possible to create tuples which contain mutable objects, such as lists." is a quote from the help file. Not only does it never mention homogeneous vs. heterogeneous but mentions both immutable and mutable which draws your mind and attention to that aspect. While tuples and lists may have different uses based on convention, there's really only two reasons to ever use a tuple: Efficiency or dictionary keys (or some similar immutability requirement). The implementation contains absolutely NOTHING to reinforce the idea that lists are for homogeneous data. The implementation of the language contains EVERY indication that tuples are second class citizens only to be used for those limited functions above (in fact, efficiency isn't even talked about in the documentation... I pieced that together from other threads). Tuples could have been implemented as frozenlist just as easily. The lack of .index() and .count() appears to be primarily motivated by a subtle and silent (at least in the documentation) desire to push towards coding "best practice" rather than for any technical reason. While I'm certainly not a "change for change sake" kind of guy and I understand the "bang for your buck" thinking, I'm just not seeing the rational for stopping this so forcibly. I get the impression that if a perfect working patch was submitted, Guido might still reject it which just seems odd to me. Again, I'm not trying to raise a stink or open old wounds, I just ran across it in an app, started doing some research and was thoroughly confused (for the record, I'm using the tuples as dictionary keys and had a desire to do k.count() for some edit checks and realized I had to convert the thing to a list first to run count() ) From pfreixes at milnou.net Tue Jun 3 15:58:12 2008 From: pfreixes at milnou.net (Pau Freixes) Date: Tue, 3 Jun 2008 21:58:12 +0200 Subject: Different execution time in python code between embedded or standalone Message-ID: <207312b70806031258n68b9dfl942e098e5119c1dc@mail.gmail.com> Hi list, First Hello to all, this is my and hope not end message to the list :P This last months I have been writting a program in c like to mod_python for embedding python language, it's a middleware for dispatch and execute python batch programs into several nodes. Now I'm writing some python program for test how scale this into several nodes and comparing with "standalone" performance. I found a very strange problem with one application named md5challenge, this aplication try to calculate the max number md5 digest in several seconds, md5challenge use a simple signal alarm for stop program when time has passed. This is the code of python script def handler_alrm(signum, frame): global _signal global _nrdigest global _f _signal = True def try_me(): global _nrdigest global _f global _signal _f = open("/dev/urandom","r") while _signal is not True: buff = _f.read(_const_b) md5.md5(buff).hexdigest() _nrdigest = _nrdigest + 1 if _f is not None : _f.close() def main( req ): global _nrdigest signal.signal(signal.SIGALRM, handler_alrm) signal.alarm(req.input['time']) try_me() req.output['count'] = _nrdigest return req.OK if __name__ == "__main__": # test code class test_req: pass req = test_req() req.input = { 'time' : 10 } req.output = { 'ret' : 0, 'count' : 0 } req.OK = 1 main(req) print "Reached %d digests" % req.output['count'] When I try to run this program in standalone into my Pentium Dual Core md4challenge reached 1.000.000 milion keys in 10 seconds but when i try to run this in embedded mode md5challenge reached about 200.000 more keys !!! I repeat this test many times and always wins embedded mode !!! What's happen ? Also I tested to erase read dependencies from /dev/random, and calculate all keys from same buffer. In this case embedded mode win always also, and the difference are more bigger !!! Thks to all, can anybody help to me ? -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From pythonblogs at gmail.com Mon Jun 2 21:33:16 2008 From: pythonblogs at gmail.com (pythonblogs at gmail.com) Date: Mon, 2 Jun 2008 18:33:16 -0700 (PDT) Subject: python blogs References: <19d5037f-837d-4f6b-9e56-d4e6d84b277d@y22g2000prd.googlegroups.com> Message-ID: <61119f97-9d1c-4ea9-af05-34ae70fb3bcf@p39g2000prm.googlegroups.com> On Jun 2, 2:14 pm, miller.pau... at gmail.com wrote: > On Jun 2, 2:49 pm, pythonbl... at gmail.com wrote: > > http://www.pythonblogs.com > > It seems like Python blogs are gaining popularity. It seems to me that > > they play a crucial role in promoting Python as a language. > > Neat! Do blogs on your site have to be about Python programming, or > can people blog about anything? Sure, feel free to blog about anything. However, it is assumed that Python will also be one of your topics :) ~pyblog From vasudevram at gmail.com Tue Jun 3 17:05:25 2008 From: vasudevram at gmail.com (vasudevram) Date: Tue, 3 Jun 2008 14:05:25 -0700 (PDT) Subject: Books for programmers References: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> <78ef063d-7219-4ffa-bf8f-88dc24dd90bc@r66g2000hsg.googlegroups.com> Message-ID: <6f709bc8-a527-420a-92c9-6e829fd0315d@w34g2000prm.googlegroups.com> On Jun 3, 6:42 pm, Mike Driscoll wrote: > On Jun 3, 5:45 am, V wrote: > > > Hi Matt, > > > and thank you very much for your answer. > > > > Hm, depends of course, how good your programming skills are in the > > > languages you knwo already, but I rely on the book "Beginning Python - > > > From Novice to Professional" by Magnus Lie Hetland, published by Apress. > > > I think that I'm interested in a more advance book, ideally one that > > talk of the Python gotchas, traps, pitfall, idioms, performance, > > stile, and so on. I really like the style used from Scott Meyers in > > his Effective C++ series, or from Herb Sutter's Exceptional C++, but > > after a quick look I did not find anything similar for Python... > > > Best regards. > > I agree with Rick. "Core Python Programming" by Chun is pretty good. > However, Lutz's "Programming Python" is also very good and has a few > big example programs to walk through. You might also find the Python > Cookbooks handy. > > There's also "Python Power!" by Matt Telles, which is more of a > reference book although not quite as dry as "Python Essential > Reference" was. > > Mike The Python Cookbook - printed version - I've read it - is a very good book on the lines of what you're looking for, IMO. If you go by its title, it might not sound like a book in the Effective Series (I've read Effective C++ too and agree that its excellent), but it actually is something quite like Effective C++, since its contributors include many very good Python developers, including Alex Martelli, David Ascher, Tim Peters, Raymond Hettinger, to name just a few. Though the explicit goal of the book is not to be a book about idiomatic Python, the point is that it ends up being a lot like that, since most of the contributors write idiomatic Python. For example, one idiom that's mentioned a lot in the book, is about one of Python's greatest strengths - "smooth signature-based polymorphism" - with good examples to substantiate it. Though not a book, you may also find the Python articles by David Mertz on IBM developerWorks very useful. Go to http://www.ibm.com/developerworks and search for either "Charming Python" - the name of his Python column there - or his name - to get the articles. HTH Vasudev ------- Vasudev Ram Biz site: http://www.dancingbison.com Quick PDF creation toolkit (in Python, open source): http://www.dancingbison.com/products.html From bruno.42.desthuilliers at websiteburo.invalid Wed Jun 4 07:50:42 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 04 Jun 2008 13:50:42 +0200 Subject: new to python, looking for streams clues In-Reply-To: <58bb3360-daa5-4cf8-a3bf-93044ed189b1@x41g2000hsb.googlegroups.com> References: <58bb3360-daa5-4cf8-a3bf-93044ed189b1@x41g2000hsb.googlegroups.com> Message-ID: <48468161$0$26543$426a34cc@news.free.fr> Thierry a ?crit : > Hello peoples, > > As I said, I'm new to python, and particularly to XML generation in > python. > Using the 4suite XML package, I have been able to produce XML, but > only directly to STDOUT. > > Refering to the 4suite markupWriter refrence, the class needs a stream > to output the generated XML, and if none is specified, it's the STDOUT > stream that is used. > > What I would like, would be to store the generated XML into a python > object which implement the stream interface to be able to transform it > via XSLT if needed (it's in a web based project). > > But, I've read the python doc for the last 12 hours without finding > anything about an existing object that implements that interface. > Am I missing something, or should I really create that object myself ? > > I mean, I just need something that I can write into and read > thereafter. > It should already exists, no ? It does, it's named StringIO (or cStringIO for the faster C implementation), and it's part of the standard lib. AFAICT, it should fit your needs. From hackame at gmail.com Sun Jun 22 16:42:48 2008 From: hackame at gmail.com (AngelinaCarmen) Date: Sun, 22 Jun 2008 13:42:48 -0700 (PDT) Subject: Learning Python in a group References: Message-ID: <8cc4de66-0139-4052-95dc-1b9c7d9ad97a@a1g2000hsb.googlegroups.com> I would like to be a part of this if enough people are able to join up, I nabbed python less than two days ago, and have been trying to absorb as much as I can out of websites and practice projects. Learning this together would speed up the process slightly because we could share tips and such, all in all, I'm up for it. From __peter__ at web.de Fri Jun 13 13:05:57 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Jun 2008 19:05:57 +0200 Subject: struct unpack issue References: Message-ID: Ping Zhao wrote: > I am writing a small program to decode MS bitmap image. When I use > statements as follow, it works fine: > > header['sig'] = str(struct.unpack('2s', self.__read(src, 2))[0]) > header['len'] = int(struct.unpack('1i', self.__read(src, 4))[0]) > > However, when I tried to rewrite them in short: > > header = struct.unpack('2s1i', self.__read(src, 6)) > > The Python interpreter in my Linux box came up with an error: > > ... > header = struct.unpack('2s1i', self.__read(src, 6)) > File "/usr/lib/python2.5/struct.py", line 87, in unpack > return o.unpack(s) > struct.error: unpack requires a string argument of length 8 > > It was weired that the required argument length increased to 8. Any idea > on this? I am using a 32bit pentium-m and the picture file was stored in > little-edian format. Try specifying byte order and alignment: >>> struct.unpack("2s1i", "123456") Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/struct.py", line 87, in unpack return o.unpack(s) struct.error: unpack requires a string argument of length 8 >>> struct.unpack("=2s1i", "123456") ('12', 909456435) See the second table on http://docs.python.org/lib/module-struct.html for the options you have. Peter From ram.rachum at gmail.com Wed Jun 18 15:00:23 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Wed, 18 Jun 2008 12:00:23 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> <4857AA74.2080205@electrooptical.net> Message-ID: <612892c1-0703-48bb-9351-dc855bd3c1de@2g2000hsn.googlegroups.com> On Jun 18, 7:12?pm, Peter Pearson wrote: > On Tue, 17 Jun 2008 08:13:40 -0400, Phil Hobbs wrote: > > ram.rac... at gmail.com wrote: > [snip] > >> I have a physical system set up in which a body is supposed to > >> accelerate and to get very close to lightspeed, while never really > >> attaining it. After approx. 680 seconds, Python gets stuck and tells > >> me the object has passed lightspeed. I put the same equations in > >> Mathematica, again I get the same mistake around 680 seconds. So I > >> think, I have a problem with my model! Then I pump up the > >> WorkingPrecision in Mathematica to about 10. I run the same equations > >> again, and it works! At least for the first 10,000 seconds, the object > >> does not pass lightspeed. > >> I concluded that I need Python to work at a higher precision. > [snip] > > You need to change your representation. ?Try redoing the algebra using > > (c-v) as the independent variable, and calculate that. > > Or represent the velocity as c*tanh(b), where b is the independent > variable. ?If memory serves, this is the representation in which > constant acceleration corresponds to db/dt = constant. > > -- > To email me, substitute nowhere->spamcop, invalid->net. See my comment to Brodie. From johnjsal at gmailNOSPAM.com Sun Jun 15 22:53:19 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sun, 15 Jun 2008 22:53:19 -0400 Subject: Combining music or video files? Message-ID: <4855d5a5$0$11609$607ed4bc@cv.net> Before I try this and destroy my computer :) I just wanted to see if this would even work at all. Is it possible to read a binary file such as an mp3 or an avi, put its contents into a new file, then read another such file and append its contents to this same new file as well, thereby making, for example, a single long video instead of two smaller ones? Thanks. From alexnbryan at gmail.com Fri Jun 27 19:36:57 2008 From: alexnbryan at gmail.com (Alexnb) Date: Fri, 27 Jun 2008 16:36:57 -0700 (PDT) Subject: using urllib2 In-Reply-To: References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> Message-ID: <18165692.post@talk.nabble.com> I have read that multiple times. It is hard to understand but it did help a little. But I found a bit of a work-around for now which is not what I ultimately want. However, even when I can get to the page I want lets say, "Http://dictionary.reference.com/browse/cheese", I look on firebug, and extension and see the definition in javascript,
1.the curd of milk separated from the whey and >> prepared >> >> in >> >> >> many ways as a food.
the problem being that if I use code like this to get the html of that page in python: response = urllib2.urlopen("the webiste....") html = response.read() print html then, I get a bunch of stuff, but it doesn't show me the code with the table that the definition is in. So I am asking how do I access this javascript. Also, if someone could point me to a better reference than the last one, because that really doesn't tell me much, whether it be a book or anything. Jeff McNeil-2 wrote: > > I stumbled across this a while back: > http://www.voidspace.org.uk/python/articles/urllib2.shtml. > It covers quite a bit. The urllib2 module is pretty straightforward > once you've used it a few times. Some of the class naming and whatnot > takes a bit of getting used to (I found that to be the most confusing > bit). > > On Jun 27, 1:41 pm, Alexnb wrote: >> Okay, I tried to follow that, and it is kinda hard. But since you >> obviously >> know what you are doing, where did you learn this? Or where can I learn >> this? >> >> >> >> >> >> Maric Michaud wrote: >> >> > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit : >> >> I have never used the urllib or the urllib2. I really have looked >> online >> >> for help on this issue, and mailing lists, but I can't figure out my >> >> problem because people haven't been helping me, which is why I am >> here! >> >> :]. >> >> Okay, so basically I want to be able to submit a word to >> dictionary.com >> >> and >> >> then get the definitions. However, to start off learning urllib2, I >> just >> >> want to do a simple google search. Before you get mad, what I have >> found >> >> on >> >> urllib2 hasn't helped me. Anyway, How would you go about doing this. >> No, >> >> I >> >> did not post the html, but I mean if you want, right click on your >> >> browser >> >> and hit view source of the google homepage. Basically what I want to >> know >> >> is how to submit the values(the search term) and then search for that >> >> value. Heres what I know: >> >> >> import urllib2 >> >> response = urllib2.urlopen("http://www.google.com/") >> >> html = response.read() >> >> print html >> >> >> Now I know that all this does is print the source, but thats about all >> I >> >> know. I know it may be a lot to ask to have someone show/help me, but >> I >> >> really would appreciate it. >> >> > This example is for google, of course using pygoogle is easier in this >> > case, >> > but this is a valid example for the general case : >> >> >>>>[207]: import urllib, urllib2 >> >> > You need to trick the server with an imaginary User-Agent. >> >> >>>>[208]: def google_search(terms) : >> > return >> urllib2.urlopen(urllib2.Request("http://www.google.com/search?" >> > + >> > urllib.urlencode({'hl':'fr', 'q':terms}), >> > headers={'User-Agent':'MyNav >> > 1.0 >> > (compatible; MSIE 6.0; Linux'}) >> > ).read() >> > .....: >> >> >>>>[212]: res = google_search("python & co") >> >> > Now you got the whole html response, you'll have to parse it to recover >> > datas, >> > a quick & dirty try on google response page : >> >> >>>>[213]: import re >> >> >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

> class=r>.*?

', >> > res) ] >> > ...[229]: >> > ['Python Gallery', >> > 'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des Monty >> ...', >> > 'Re: os x, panther, python & co: msg#00041', >> > 'Re: os x, panther, python & co: msg#00040', >> > 'Cardiff Web Site Design, Professional web site design services ...', >> > 'Python Properties', >> > 'Frees < Programs < Python < Bin-Co', >> > 'Torb: an interface between Tcl and CORBA', >> > 'Royal Python Morphs', >> > 'Python & Co'] >> >> > -- >> > _____________ >> >> > Maric Michaud >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> -- >> View this message in >> context:http://www.nabble.com/using-urllib2-tp18150669p18160312.html >> Sent from the Python - python-list mailing list archive at Nabble.com. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/using-urllib2-tp18150669p18165692.html Sent from the Python - python-list mailing list archive at Nabble.com. From tjreedy at udel.edu Sat Jun 28 20:06:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 28 Jun 2008 20:06:41 -0400 Subject: Testing for Null? In-Reply-To: <268ac2770806281605n663670e9n29620f344ed66e4d@mail.gmail.com> References: <268ac2770806281605n663670e9n29620f344ed66e4d@mail.gmail.com> Message-ID: Alex Bryan wrote: > I am having a problem with a list value that is empty. I have a list of > definitions called mainList. the 5th value in the list doesn't have > anything in it. In this case, the values are definitions; also, in this > case just the word cheese is defined. Here is my output to the console: > > > 5. a sprawling,weedy plant having small lavender or white flowers and > round, flat, segmented fruits thought to resemble little wheels of cheese. > 6. > 7. an ingot or billet made into a convex, circular form by blows at the > ends. > > > I've made it so where the numbers, the period, and two spaces follow > that, then the definition. However, as you can see in 6, there is > nothing. Here is the code to print all this: > > n=0 > > for x in mainList: > if mainList[n] == "": > print "Error on this definition" > else: > print str(n+1)+". "+str(mainList[n]) > n=n+1 > > Now the two "" is where I need to figure out if it is empty. What is up > right now doesn't work; or at least doesn't give the desired result. So > I need to know how to write the if statement to make it work. This > should be simple, but I just don't know how to do it, never had this > problem before. My guess is that your 'empty' value is something like ' ', which is not equal to ''. Change str to repr and see better what item 6 is. From patelgopal at gmail.com Sun Jun 29 04:39:11 2008 From: patelgopal at gmail.com (gops) Date: Sun, 29 Jun 2008 01:39:11 -0700 (PDT) Subject: What is "@" used for ? Message-ID: Hi. I am noob in python. while reading some source code I came across , this funny thing called @ in some function , def administrator(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): user = users.get_current_user() if not user: if self.request.method == "GET": self.redirect(users.create_login_url(self.request.uri)) return raise web.HTTPError(403) elif not users.is_current_user_admin(): raise web.HTTPError(403) else: return method(self, *args, **kwargs) return wrapper now what is that "@" used for ? I tried to google , but it just omits the "@" and not at all useful for me(funny!! :D) It will be enough if you can just tell me some link where i can look for it.. Thank you in advance. :D From saptarshi.guha at gmail.com Mon Jun 9 15:44:47 2008 From: saptarshi.guha at gmail.com (sapsi) Date: Mon, 9 Jun 2008 12:44:47 -0700 (PDT) Subject: Numpy, adding a row to a matrix Message-ID: <359ea846-786a-4267-9068-d61ff4c58974@x35g2000hsb.googlegroups.com> Hello, I have a numpy array (2 rows 3 colums) import numpy a=numpy.array( [ [1,2,3] , [3,3,1] ]) I wish to add a row, this is how i do it s=a.shape numpy.resize(a,s[0]+1,s[1]) a[s[0]]=new row vector. Q: Is this a costly operation? What happens if i have to it several (and unknown) number of times? is there a simpler way to add a row? Thank you in advance Saptarshi From d3vvnull at gmail.com Thu Jun 19 10:24:53 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Thu, 19 Jun 2008 09:24:53 -0500 Subject: python/ruby question.. In-Reply-To: <485A3173.3080908@mattnordhoff.com> References: <3b017f08-2d42-4c65-9003-19ffc606234d@l64g2000hse.googlegroups.com> <485A3173.3080908@mattnordhoff.com> Message-ID: <170543c70806190724m4cbd67f0t7cd01956f36212d0@mail.gmail.com> The commands module might help you out as well. import commands as c output = c.getoutput('testruby.rb') On Thu, Jun 19, 2008 at 5:14 AM, Matt Nordhoff wrote: > Mensanator wrote: > > On Jun 18, 10:33?pm, "bruce" wrote: > >> hi... > >> > >> can someone point me to where/how i would go about calling a ruby app > from a > >> python app, and having the python app being able to get a returned value > >> from the ruby script. > >> > >> something like > >> > >> test.py > >> ?a = os.exec(testruby.rb) > >> > >> testruby.py > >> ?foo = 9 > >> ?return foo > >> > >> i know this doesn't work... but i've been searching for hours on this > with > >> no luck.... (and yeah, i'm relatively new to both ruby/python!!) > >> > >> thanks > > > > Well, I don't know anything about Ruby, but here's > > how I do it for C programs (compiled to .exe that > > write to stdout). > > > > > > import os > > factor_program = 'factor! -d200 ' # factor!.exe from MIRACL > > > > n = > > > '50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749' > > > > # call external program and capture stdout > > the_output = os.popen(factor_program+n).readlines() > > > > print 'n: %s' % n > > for i in the_output: > > print i, > > > > You're supposed to use the subprocess module. > > In this case, something like: > > import subprocess > factor_program = ['factor!', '-d200'] > > ... > > p = subprocess.Popen(factor_program + [n], stdout=subprocess.PIPE) > p.wait() # wait for it to finish; not sure how necessary it is > the_output = p.stdout.readlines() > > See subprocess's documentation [1], which includes guides on replacing > os.popen* and other functions with it. > > [1] > -- > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From omer at no-log.org Tue Jun 24 06:45:35 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Tue, 24 Jun 2008 12:45:35 +0200 Subject: sending executable data over network.. In-Reply-To: <19ac19520806232359r31f74c7bk9f5d47eb3540e457@mail.gmail.com> References: <19ac19520806232359r31f74c7bk9f5d47eb3540e457@mail.gmail.com> Message-ID: <200806241245.35047.omer@no-log.org> Le Tuesday 24 June 2008 08:59:40 Piyush Anonymous, vous avez ?crit?: > hi, > i wish to change the way the function definition at run time in a running > server. new function code which is to be executed is provided by a client > at different location. > i am getting it by reading a file and sending it using makefile() with > server/client connected using sockets. > > how can make the lines received in a string array as new function > definition? or should i receive it in a different way? > > is there any better way to do the entire thing? One way is to transmit the code as a string and compile it on server-side with the 'compile' builtin function. Another is to compile it on client-side and transmit the resulting code object with the marshal module but there are many restrictions on it (specially the fact that the client and server will have to run the same python version) so carefully read the docs first. I'd choose the first solution, eventually using the pickle module to avoid encoding problems. -- C?dric Lucantis From nick at craig-wood.com Mon Jun 9 16:30:49 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 09 Jun 2008 15:30:49 -0500 Subject: _POSIX_C_SOURCE References: Message-ID: Madhur wrote: > I would like to know the difference between using the > C_INCLUDE_PATH and using the -I option with compilers. How are they > different? No idea on that - I always just use -I > The problem which I am facing is that I am having a > source base which uses python. I am currently enabling compile time > option _POSIX_C_SOURCE in my Makefile. The compilaiton fails if i > include -I option to /usr/include/python2.4 > > /usr/include/python2.4/pyconfig-32.h:838:1: error: "_POSIX_C_SOURCE" > redefined > > but if i do > > export C_INCLUDE_PATH=/usr/include/python2.4 > > I do not face any compilation issues. > > I would like to know if there is anything i am missing on this. Do it in your code with #define _POSIX_C_SOURCE instead of the Makefile, and do it after the #include "Python.h" -- Nick Craig-Wood -- http://www.craig-wood.com/nick From ggpolo at gmail.com Fri Jun 20 18:20:39 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Fri, 20 Jun 2008 19:20:39 -0300 Subject: inheritance question... In-Reply-To: <587C2C9324493D4B96BD6BBCDEAC321AA95911@exchange3.valvesoftware.com> References: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> <09ec833f-7751-4991-8d09-45c200fb4c18@z72g2000hsb.googlegroups.com> <587C2C9324493D4B96BD6BBCDEAC321AA95911@exchange3.valvesoftware.com> Message-ID: On Fri, Jun 20, 2008 at 6:19 PM, Hamish McKenzie wrote: > > I have this class: > > class Vector(object): > TOL = 1e-5 > def __eq__( self, other, tolerance=TOL ): > print tolerance > > > shortened for clarity obviously. so I want to subclass this class like > so: > > class BigVector(Vector) > TOL = 100 > > > for example if I was working with large vectors which I knew would never > be very close hence the large tolerance. this doesn't work however - > the TOL class variable, while overridden in BigVector, is still using > the Vector.TOL variable in the __eq__ method. > > > which kinda makes sense to a certain degree, but how do I get the > behaviour where doing: > > BigVector().__eq__( otherVec ) No, don't do this. Just do "avector == othervector" > > > prints 100 instead of 1e-5? > > does this question make sense? not sure how clearly I'm phrasing my > question... any of you guys python experts? > > > I *could* do this, but its ugly: > > class Vector(object): > TOL = 1e-5 > def __eq__( self, other, tolerance=None ): > if tolerance is None: tolerance = self.TOL > print tolerance > class Vector(object): TOL = 1e-5 def __eq__(self, other): print self.TOL > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From garyrob at mac.com Mon Jun 23 22:12:18 2008 From: garyrob at mac.com (Gary Robinson) Date: Mon, 23 Jun 2008 22:12:18 -0400 Subject: 32-bit python memory limits? Message-ID: <20080623221218152774.85cdf772@mac.com> I'm running a Python job on OS X 10.5.3 and the Python 2.5.2 that's available as a binary download at python.org for OS X. I ran a python program tonight that ended up using much more memory than anticipated. It just kept on using more and more memory. Instead of killing it, I just watched it, using Activity Monitor. I assumed that when it had 2GB allocated it would blow up, because I thought 32-bit python could only address 2GB. But Activity Monitor reported that it had allocated 3.99GB of virtual memory before it finally blew up with malloc errors. Was my understanding of a 2GB limit wrong? I guess so! But I'm pretty sure I saw it max out at 2GB on linux... Anybody have an explanation, or is it just that my understanding of a 2GB limit was wrong? Or was it perhaps right for earlier versions, or on linux...?? Thanks for any thoughts, Gary -- Gary Robinson CTO Emergent Music, LLC personal email: garyrob at mac.com work email: grobinson at emergentmusic.com Company: http://www.emergentmusic.com Blog: http://www.garyrobinson.net From gongchangzhaojie at gmail.com Thu Jun 5 13:52:54 2008 From: gongchangzhaojie at gmail.com (Zhaojie Boulder) Date: Thu, 5 Jun 2008 11:52:54 -0600 Subject: gcc error in Mac OS X In-Reply-To: References: <12956470806041550k7e2815b4ga6823ee7967a8718@mail.gmail.com> Message-ID: <12956470806051052g2d4a53as7b644c1f26dddcfa@mail.gmail.com> Hi Tommy, When I typed which gcc,nothing happened,I checked the /usr/bin path myself and gcc was not there. In fact, the Xcode folder is at the same level with the usr folder. Is there a way you can install Xcode in the right place? I did not find such a option during the installation process of Xcode. Thanks Jie 2008/6/4 Tommy Grav : > What happens when you run > > which gcc > > Cheers > Tommy > > > On Jun 4, 2008, at 6:50 PM, Zhaojie Boulder wrote: > > Hello, >> >> I am new to Mac and used python in linux before. What I am trying to do is >> to install "Ipython" and "PyCogent" in Mac OS X. >> >> For PyCogent, after entering the package path, I typed "python setup.py >> install". The results are as follows: >> >> Didn't find Pyrex - will compile from .c files >> running install >> running build >> running build_py >> running build_ext >> building 'cogent.align._compare' extension >> gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd >> -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DMACOSX >> -I/usr/include/ffi -DENABLE_DTRACE -arch i386 -arch ppc -pipe >> -I/Users/zhaojie/Downloads/PyCogent-1.0.1/include >> -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 >> -c cogent/align/_compare.c -o >> build/temp.macosx-10.5-i386-2.5/cogent/align/_compare.o -w >> unable to execute gcc: No such file or directory >> error: command 'gcc' failed with exit status 1 >> >> After google, I installed Xcode,but it did not help. Also, the Xcode >> folder is not within "applications" folder, but a separate one parallel with >> "applications". Dragging Xcode folder into the applications folder did not >> make a difference, either. >> >> Hope someone familiar with Mac can help me out. >> >> Thank you, >> >> Jie >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From brian_vanderburg2 at yahoo.com Thu Jun 26 19:23:11 2008 From: brian_vanderburg2 at yahoo.com (Allen) Date: Thu, 26 Jun 2008 19:23:11 -0400 Subject: Adding functions to an existing instance In-Reply-To: References: <27adnS2SrIrOLv7VnZ2dnUVZ_rjinZ2d@earthlink.com> Message-ID: bruno.desthuilliers at gmail.com wrote: > On 26 juin, 17:18, Allen wrote: >> I need a way to add a method to an existing instance, but be as close as >> possible to normal instance methods. > > def set_method(obj, func, name=None): > if not name: > name = func.__name__ > setattr(obj, name, func.__get__(obj, type(obj))) > > class Toto(object): > pass > > toto = Toto() > > def titi(self): > print self > > set_method(toto, titi) > I tried that. func.__get__(obj, type(obj)) creates a bound method and then sets an attribute to that, creating a cyclic reference. toto contains a reference to the bound method, the bound method contains a reference to the instance toto. However it does eliminate the need for FunctionCaller. Instead of: return InstanceFunctionHelper.FunctionCaller(self, funcs[name]) __getattr__(...) can just do: return funcs[name].__get__(self, type(self)) to get the same behavior. All of the extra __setattr__ and __delattr__ exist so that if the attribute is set after a function is set, it will delete the function so that later deleting the attribute will not make the function visible again. Brian Vanderburg II From inhahe at gmail.com Tue Jun 24 05:55:50 2008 From: inhahe at gmail.com (inhahe) Date: Tue, 24 Jun 2008 05:55:50 -0400 Subject: How to import filenames with special characters? Message-ID: How would I import a python file whose name contains characters like .'s or !'s? Is there really _no_ way to do that? I have to use plain jane letters and numbers for everything? From vtians at gmail.com Mon Jun 9 21:14:22 2008 From: vtians at gmail.com (TT) Date: Mon, 9 Jun 2008 18:14:22 -0700 (PDT) Subject: 65K length limitation in MySQLdb? Message-ID: <4e79050f-ee50-42f0-9b84-4571faa30ee5@a32g2000prf.googlegroups.com> I'm trying to using the following code insert a long string into a MySQL table, the data type is of that column is TEXT. When the length of the content is longer than 65K, it get truncated in the database. Any idea about this? Thanks import MySQLdb import MySQLdb.cursors class MyDb: def __init__(self): self.conn = None self.cursor = None def connect(self): self.conn = MySQLdb.Connect( host='localhost', user='user', passwd='password', db='testdb',compress=1, cursorclass=MySQLdb.cursors.DictCursor) self.cursor = self.conn.cursor() def insert(self, id, content): try: self.cursor.execute("INSERT INTO `my_table`(`id`, `content`) VALUES (%s, %s);", (id, content)); except: print "Failed to insert new record" pass From pavlovevidence at gmail.com Fri Jun 20 20:25:54 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 20 Jun 2008 17:25:54 -0700 (PDT) Subject: sublassing as a verb References: Message-ID: On Jun 20, 4:34?pm, davidj411 wrote: > docs on urllib module say this about the FancyUrlOpener: > "class FancyURLopener( ...) > > FancyURLopener subclasses URLopener providing default handling > for ..." > > does that mean the FancyURLopener is a subclass of URLopener? Yes. Anthimeria is very common in English. Carl Banks From Lie.1296 at gmail.com Tue Jun 10 11:55:42 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 10 Jun 2008 08:55:42 -0700 (PDT) Subject: proposal: give delattr ability to ignore missing attribute References: <4e9122bb-eb81-460f-85cd-11e344195175@p25g2000hsf.googlegroups.com> Message-ID: On Jun 10, 10:06?pm, Gary Wilson wrote: > I would like to propose that functionality be added to delattr to > handle the case when the attribute does not exist. > > First off, getattr handles this nicely with the default parameter: > > value = getattr(obj, 'foo', False) > > instead of: > > try: > ? ? value = getattr(obj, 'foo') > except AttributeError: > ? ? value = False > > or: > > if hasattr(obj, 'foo'): > ? ? value = getattr(obj, 'foo') > else: > ? ? value = False > > And I think it makes sense to have something similar for delattr (name > the argument as you wish): > > delattr(obj, 'foo', allow_missing=True) > > instead of: > > try: > ? ? delattr(obj, 'foo') > except AttributeError: > ? ? pass > > or: > > try: > ? ? del obj.foo > except AttributeError: > ? ? pass > > or: > > if hasattr(obj, 'foo') > ? ? delattr(obj, 'foo') > > For backwards compatibility, allow_missing would default to False. > > Gary That doesn't need to be implemented internally, you could do it yourself in python. def my_delattr(obj, attr): try: delattr(obj, attr) except AttributeError: pass def my_getattr(obj, attr, default): try: return getattr(obj, attr) except AttributeError: return default From weheh at yahoo.com Sun Jun 22 16:31:20 2008 From: weheh at yahoo.com (weheh) Date: Sun, 22 Jun 2008 20:31:20 GMT Subject: binary number format ? format character %b or similar. References: Message-ID: I don't know if you found this example: http://www.daniweb.com/code/snippet285.html -- > I'm was wanting to format a positive integer in binary, > and not finding it--to my surprise--I rolled my own version. > > Is this already in python, or have I missed it somewhere? > > I have Googled around a bit, and found a few threads on > the subject, but they all seem to fizzle out. > > (e.g. : INPUT 35, OUTPUT "100011" ) From s0suk3 at gmail.com Thu Jun 5 09:06:35 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Thu, 5 Jun 2008 06:06:35 -0700 (PDT) Subject: Books for learning how to write "big" programs References: <219c77ef-dd0c-464b-bb6a-e4f3bee89eae@x41g2000hsb.googlegroups.com> Message-ID: <304580c2-bdfb-4564-8507-d742d9eaf5a8@79g2000hsk.googlegroups.com> On May 22, 12:49?pm, "Kurt Smith" wrote: > On Thu, May 22, 2008 at 10:55 AM, duli wrote: > > Hi: > > I would like recommendations forbooks(in any language, not > > necessarily C++, C, python) which have walkthroughs for developing > > a big software project ? So starting from inception, problem > > definition, design, coding and final delivery on a single theme > > or application. > > The bigger the project, the more likely it is that you'll have > documentation on how to use it (for a language or library, how to use > the features in your program) but to take the time to write up a > dead-tree book on the project's "inception, problem definition, > design, coding and final delivery" is not likely well spent. ?Anyone > who has the expertise to write such a book would probably be spending > his time working on the next phase of the project itself. > > Someone will probably respond with an amazon link to a book that does > exactly what you're asking, in which case, I will stand corrected. > But I'll be surprised. > > > > > Most of the code I have written andbooksthat I have read deal with > > toy programs and I am looking for something a bit more > > comprehensive. ?For example, maybe a complete compiler written in C++ > > for some language, or a complete web server or implementing > > .net libraries in some language (just a few examples of the scale of > > things I am interested in learning). > > It seems to me the reason toy programs are so prevalent is because > they illustrate a (few) well defined ideas in a short amount of code. > A big project, necessarily, brings together all kinds of stuff, much > of which may not interest the author at all, and so doesn't motivate > him to write a book about it. > > Compilers, web servers & .NET libraries are *widely* varying areas. > You may have interest in them all, but to significantly contribute to > any requires a fair amount of expertise and specialization. > > The best route I've found to learn how to organize & program large > scale applications is this: find a cutting edge program that interests > you and that is open source. ?Download its source, and read the code. > Diagram it. ?Map it out. ?Read the comments. ?Join the mailing list > (probably the developer's list), lurk for a while, and ask questions > about why they organized things the way they did. ?Get the overall big > picture and learn from it. ?Better yet, find out what pitfalls they > found and avoided (or fell into). ?Compare their approach & > organization with another competing project. ?This is the wonder of > open source software -- you have access to everything, and can learn > from all the expertise the developers put into their opus. > > You can learn the basics frombooks, but nothing beats analyzing a > species in the wild. I think I have lately understood what you mean, thanks to Programming Python 3rd Ed by Lutz. It doesn't teach Python itself -- the book aims to teach Python programming at an application level, but I'm starting to wonder whether that knowledge can be obtained from any book. The book goes through over 1500 pages (!) giving small- and medium-sized example programs and describing their details. Roughly after a couple of hundred pages I started to feel like all that was trivial (isn't looking at code and figuring their details what we do in our every-day programmer lifes?), and then started to feel like it was really useless. Maybe large-scale programming can only be self-thought in every day life, am I right?. From laurent.ploix at gmail.com Mon Jun 16 17:56:22 2008 From: laurent.ploix at gmail.com (=?ISO-8859-1?Q?m=E9choui?=) Date: Mon, 16 Jun 2008 14:56:22 -0700 (PDT) Subject: How to request data from a lazily-created tree structure ? References: <6bo3ifF3dj7dmU1@mid.uni-berlin.de> Message-ID: <896f8600-4183-4147-96c9-64ab5a9ad753@x41g2000hsb.googlegroups.com> On Jun 16, 11:16 pm, "Diez B. Roggisch" wrote: > m?choui schrieb: > > > > > Problem: > > > - You have tree structure (XML-like) that you don't want to create > > 100% in memory, because it just takes too long (for instance, you need > > a http request to request the information from a slow distant site). > > - But you want to be able to request data from it, such has "give me > > all nodes that are under a "//foo/bar" tree, and have a child with an > > "baz" attribute of value "zzz". > > > Question : > > > Do you have any other idea to request data from a lazily-created tree > > structure ? > > > And does it make sense to create a DOM-like structure and to use a > > generic XPath engine to request the tree ? (and does this generic > > XPath engine exist ?) > > > The idea is to have the tree structure created on the fly (we are in > > python), only when the XPath engine requests the data. Hopefully the > > XPath engine will not request all the data from the tree (if the > > request is smart enough and does not contain **, for instance). > > Generic XPath works only with a DOM(like) structure. How else would you > e.g. evaluate an expression like foo[last()]? > > So if you really need lazy evaluation, you will need to specifically > analyze the query of interest and see if it can be coded in a way that > allows to forget as much of the tree as possible, or even better not > query it. > > Diez Yes, I need to make sure my requests are properly written so that the generic XPath engine does not need all the structure in memory. There are quite a few cases where you really don't need to load everything at all. /a/b/*/c/d is an example. But even with an example like /x/z[last()]/t, you don't need to load everything under the every /x/z nodes. You just need to check for the latest one, and make sure there is a t node under it. Anyway, if I need to make requests that need all the data... that means that the need for lazy instantiation of nodes disappears, right ? From lists at cheimes.de Tue Jun 3 05:03:24 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 03 Jun 2008 11:03:24 +0200 Subject: Writing Empty folders into ZipFile In-Reply-To: References: Message-ID: otaeris at o2.pl schrieb: > Hello. > > I'm having situation writing folders structure into > a zip file. Folders contain no files. > > Is it possible to do in python ? As far as I remember the zip format it's not possible at all. Folders are created implicitly. The zip format doesn't support empty directories. Christian From shore.cloud at gmail.com Mon Jun 16 15:30:15 2008 From: shore.cloud at gmail.com (Mr Shore) Date: Mon, 16 Jun 2008 12:30:15 -0700 (PDT) Subject: vmware job vacancy! Message-ID: <3239dff8-d5b2-42d3-9b98-e5947eb65f4f@v26g2000prm.googlegroups.com> A veteran engineer from VMWare Inc., Jeffrey, is being featured on jobirn.com on Monday Jun 16, from 9am to 5pm (PST.) He will chat with applicants who are interested in job openings in VMWare. He will identify qualified candidates and directly submit qualified candidates' resumes to hiring managers. Logon to http://jobirn.com and chat with Jeff. Jobirn.com is a job-referral company. It connects job applicants with insider employees in companies. Jobirn.com believes it gives qualified candidates higher opportunities to catch the attention of the right managers. Referrers, once featured, will usually make significant amount of bonus (Employee Referral Bonus) from his own company,if the recommended candidates are hired. From Robert.Bossy at jouy.inra.fr Wed Jun 18 08:10:38 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 18 Jun 2008 14:10:38 +0200 Subject: dict order In-Reply-To: <1a7a2dc6-4acf-473d-a51c-4715ca9c7068@c19g2000prf.googlegroups.com> References: <4804032a-adef-4973-ae21-acc4ad2dce37@z72g2000hsb.googlegroups.com> <411fc353-dd54-4bbc-a72e-ddee66408313@c58g2000hsc.googlegroups.com> <1a7a2dc6-4acf-473d-a51c-4715ca9c7068@c19g2000prf.googlegroups.com> Message-ID: <4858FB3E.1060907@jouy.inra.fr> Lie wrote: >> Whoops, I think I misunderstood the question. If what you're asking >> whether two dictionary is equal (equality comparison, rather than >> sorting comparison). You could do something like this: >> Testing for equality and finding differences are trivial tasks indeed. It is the sort order I'm interested in. The meaning of the order is not really an issue, I'm rather looking for a consistent comparison function (in the __cmp__ sense) such as: if d1 > d2 and d2 > d3, then d1 > d3 I'm not sure the hashing method suggested by Albert guarantees that. Cheers From wizzardx at gmail.com Wed Jun 18 04:22:20 2008 From: wizzardx at gmail.com (David) Date: Wed, 18 Jun 2008 10:22:20 +0200 Subject: Database design questions In-Reply-To: <18c1e6480806180041s5ffaca54r39a7554734cd513c@mail.gmail.com> References: <18c1e6480806180041s5ffaca54r39a7554734cd513c@mail.gmail.com> Message-ID: <18c1e6480806180122o5fe113e3m9a1c8e0761391fbf@mail.gmail.com> > I have a few database-related questions. These aren't Python-specific > questions, but some of my apps which use (or will use) these tables > are in Python :-) Let me know if I should ask this on a different > list. Hi list. I've thought about this some more, and it is off-topic for the python list. I'm going to ask this on the postgresql users list instead. David. From dgetsman at amirehab.net Wed Jun 4 14:53:50 2008 From: dgetsman at amirehab.net (Damon Getsman) Date: Wed, 4 Jun 2008 11:53:50 -0700 (PDT) Subject: python library for passwd suitable blowfish hash generation Message-ID: I'm working on a utility that needs to be able to generate /etc/shadow suitable hashes on an OpenSuSE 10.3 system. All of the shadowed hashes are blowfish, I believe, from seeing the 'magic' $2a$10$ at the start of each of the entries. Ideally I would like to find a library that will take my string and spit out the hash in a compatible ascii form so that I could just drop it in place or prepend the $2a$10$ and drop it in, but I'm not afraid of taking the binary and trying to convert it to compatible ascii. Does anybody know of any python libraries like this? I've seen a few of the libraries so far and I'm not sure if I want to use them or not; documentation was rather lacking. I'd appreciate any input you all might be able to give on this. Thanks for your time. -Damon Getsman From phillip.oldham at gmail.com Thu Jun 12 10:27:36 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Thu, 12 Jun 2008 07:27:36 -0700 (PDT) Subject: Comments on my first script? Message-ID: <7e3a7c92-6204-46dd-8df8-90218f2fb314@26g2000hsk.googlegroups.com> I'm keen on learning python, with a heavy lean on doing things the "pythonic" way, so threw the following script together in a few hours as a first-attempt in programming python. I'd like the community's thoughts/comments on what I've done; improvements I can make, "don'ts" I should be avoiding, etc. I'm not so much bothered about the resulting data - for the moment it meets my needs. But any comment is welcome! #!/usr/bin/env python ## Open a file containing a list of domains (1 per line), ## request and parse it's whois record and push to a csv ## file. import subprocess import re src = open('./domains.txt') dest = open('./whois.csv', 'w'); sep = "|" headers = ["Domain","Registrant","Registrant's Address","Registrar","Registrant Type","Date Registered","Renewal Date","Last Updated","Name Servers"] dest.write(sep.join(headers)+"\n") def trim( txt ): x = [] for line in txt.split("\n"): if line.strip() == "": continue if line.strip().startswith('WHOIS'): continue if line.strip().startswith('>>>'): continue if line.strip().startswith('%'): continue if line.startswith("--"): return ''.join(x) x.append(" "+line) return "\n".join(x) def clean( txt ): x = [] isok = re.compile("^\s?([^:]+): ").match for line in txt.split("\n"): match = isok(line) if not match: continue x.append(line) return "\n".join(x); def clean_co_uk( rec ): rec = rec.replace('Company number:', 'Company number -') rec = rec.replace("\n\n", "\n") rec = rec.replace("\n", "") rec = rec.replace(": ", ":\n") rec = re.sub("([^(][a-zA-Z']+\s?[a-zA-Z]*:\n)", "\n\g<0>", rec) rec = rec.replace(":\n", ": ") rec = re.sub("^[ ]+\n", "", rec) return rec def clean_net( rec ): rec = rec.replace("\n\n", "\n") rec = rec.replace("\n", "") rec = rec.replace(": ", ":\n") rec = re.sub("([a-zA-Z']+\s?[a-zA-Z]*:\n)", "\n\g<0>", rec) rec = rec.replace(":\n", ": ") return rec def clean_info( rec ): x = [] for line in rec.split("\n"): x.append(re.sub("^([^:]+):", "\g<0> ", line)) return "\n".join(x) def record(domain, record): details = ['','','','','','','','',''] for k, v in record.items(): try: details[0] = domain.lower() result = { "registrant": lambda: 1, "registrant name": lambda: 1, "registrant type": lambda: 4, "registrant's address": lambda: 2, "registrant address1": lambda: 2, "registrar": lambda: 3, "sponsoring registrar": lambda: 3, "registered on": lambda: 5, "registered": lambda: 5, "domain registeration date": lambda: 5, "renewal date": lambda: 6, "last updated": lambda: 7, "domain last updated date": lambda: 7, "name servers": lambda: 8, "name server": lambda: 8, "nameservers": lambda: 8, "updated date": lambda: 7, "creation date": lambda: 5, "expiration date": lambda: 6, "domain expiration date": lambda: 6, "administrative contact": lambda: 2 }[k.lower()]() if v != '': details[result] = v except: continue dest.write(sep.join(details)+"\n") ## Loop through domains for domain in src: domain = domain.strip() if domain == '': continue rec = subprocess.Popen(["whois",domain], stdout=subprocess.PIPE).communicate()[0] if rec.startswith("No whois server") == True: continue if rec.startswith("This TLD has no whois server") == True: continue rec = trim(rec) if domain.endswith(".net"): rec = clean_net(rec) if domain.endswith(".com"): rec = clean_net(rec) if domain.endswith(".tv"): rec = clean_net(rec) if domain.endswith(".co.uk"): rec = clean_co_uk(rec) if domain.endswith(".info"): rec = clean_info(rec) rec = clean(rec) details = {} try: for line in rec.split("\n"): bits = line.split(': ') a = bits.pop(0) b = bits.pop(0) details[a.strip()] = b.strip().replace("\t", ", ") except: continue record(domain, details) ## Cleanup src.close() dest.close() From lawtonpaul at gmail.com Sun Jun 15 21:23:44 2008 From: lawtonpaul at gmail.com (takayuki) Date: Sun, 15 Jun 2008 18:23:44 -0700 (PDT) Subject: newbie question: for loop within for loop confusion Message-ID: Hi, I'm studying python via the exellent book "How to think like a python programmer" by Allen Downey. Noob question follows... animals.txt is a list of animals, each on a separate line: "aardvard, bat, cat, dog, elephant, fish, giraffe, horse, insect, jackelope" I want to loop through the list of words and print words that don't have any "avoid" letter in them. def hasnolet(avoid): fin = open('animals.txt') for line in fin: word = line.strip() for letter in avoid: if letter in word: break else: print word hasnolet('abcd') Why doesn't the function above work? It returns: dog dog dog fish fish fish fish horse horse horse horse inchworm inchworm thanks for any help. takayuki From giltay at gmail.com Wed Jun 11 09:48:03 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Wed, 11 Jun 2008 06:48:03 -0700 (PDT) Subject: Producer-consumer threading problem References: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> <5d41116a-a75f-4421-a397-cde28403d73b@a70g2000hsh.googlegroups.com> Message-ID: <3f7e7640-87bf-4c2e-a7d5-1dda7d6989f3@f63g2000hsf.googlegroups.com> > Sounds like a sentinel would work for this. The producer puts a > specific object (say, None) in the queue and the consumer checks for > this object and stops consuming when it sees it. But that seems so > obvious I suspect there's something else up. There's a decent implementation of this in the Python Cookbook, Second Edition (9.4: Working with a Thread Pool), available from Safari as a preview: http://my.safaribooksonline.com/0596007973/pythoncook2-CHP-9-SECT-4 Basically, there's a request_work function that adds (command, data) pairs to the input Queue. The command 'stop' is used to terminate each worker thread (there's the sentinel). stop_and_free_thread_pool() just puts N ('stop', None) pairs and join()s each thread. The threadpool put()s the consumed items in an output Queue; they can be retrieved concurrently using get(). You don't call join() until you want to stop producing; you can get() at any time. Geoff Gilmour-Taylor (I ended up using this recipe in my own code, but with a completely different stopping mechanism---I'm using the worker threads to control subprocesses; I want to terminate the subprocesses but keep the worker threads running---and a callback rather than an output queue.) From bsagert at gmail.com Wed Jun 18 13:37:13 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Wed, 18 Jun 2008 10:37:13 -0700 (PDT) Subject: Importing module PIL vs beautifulSoup. References: Message-ID: On Jun 18, 10:18 am, Duncan Booth wrote: > bsag... at gmail.com wrote: > > I downloaded BeautifulSoup.py from > >http://www.crummy.com/software/BeautifulSoup/and being a n00bie, I > > just placed it in my Windows c:\python25\lib\ file. When I type > > "import beautifulsoup" from the interactive prompt it works like a > > charm. This seemed too easy in retrospect. > > It might be better if you put the file in \python25\lib\site-packages\ > The same import will still work, but you probably want to avoid putting > non-core files directly in \python25\lib. > > Also, it sounds like you renamed the file: "import beautifulsoup" should > fail (the file is supposed to be called BeautifulSoup.py). If you want to > be able to install other software which has been written to use > BeautifulSoup you'll need to make sure the case of the filename is correct. > > > > > Then I downloaded the PIL (Python Imaging Library) module from > >http://www.pythonware.com/products/pil/. Instead of a simple file that > > BeautifulSoup sent me, PIL is an .exe that installed itself in c: > > \python25\lib\site-packages\PIL\. However it won't load by typing > > "import pil". > > > I know I am supposed to RTFM, but a Google search has not led to the > > holy grail that Monty Python found. I realize that PIL is a package as > > opposed to a simple script (and it does not include a readme file). > > Thanks in advance for any help. > > Did you try "import PIL"? All module and package names in Python are case > sensitive. YIKES, Python is case sensitive! I knew that, says he blushing. Now it works. Thanks Duncan. Ciao, Bill From n.emami at gmail.com Fri Jun 13 06:01:55 2008 From: n.emami at gmail.com (Nader) Date: Fri, 13 Jun 2008 03:01:55 -0700 (PDT) Subject: Checking list by using of exception References: <3bdcc52d-2432-4b28-8188-bf7c811859d1@d45g2000hsc.googlegroups.com> Message-ID: <93f7f082-627b-4da2-8a1c-4e6e9400a428@34g2000hsf.googlegroups.com> On Jun 13, 11:34 am, "Gabriel Genellina" wrote: > En Fri, 13 Jun 2008 04:37:44 -0300, Nader escribi?: > > > Hello, > > > I read some files name from a directory and then I put these name in a > > list. I will check whether it is empty or not, and I would do it with > > an exception. With if statement it is very simple: > > > If list_of_files != "" : # this can be if list_of_files != > > []: > > get the files > > elas: > > there is no file > > If it is simple, just do it! Why do you want to make things more > complicated? This would be enough: > > if list_of_files: > get_the_files(list_of_files) > else: > print "there is no file" > > (a list has a false boolean value when it is empty) > > > But with exception, I can write something as: > > > try: > > list_of_files != [] > > get the files > > except ValueError: > > Print " there is no file" > > > What can the first statement be inside 'try' if I don't want to use if > > statement? > > If you insist on using an exception (and assuming list_of_files is > actually a list, not a string or other kind of sequence): > > try: > list_of_files[0] > except IndexError: > ...no files... > > This way you're checking that list_of_files contains at least one element. > But I would not reccomend it. > > -- > Gabriel Genellina I would accept your suggestion in raltion of checking a list whether it is empty or not with "if" statement. It is more expressive and clear. But In this case I would learn more about the "try .... except" exception. Nader From cmpython at gmail.com Mon Jun 9 21:23:15 2008 From: cmpython at gmail.com (CM) Date: Mon, 9 Jun 2008 18:23:15 -0700 (PDT) Subject: Write to file and see content on screen References: <5b2e915f-9fc5-4acc-b49e-d1b90d00bda0@59g2000hsb.googlegroups.com> Message-ID: On Jun 9, 9:01 pm, lama... at verizon.net wrote: > Hello all, > > New user to python. I can write to a file, however, I would like to > do both...whatever I do on the screen, I'd like to write it to a file. > > any pointers on where I can find this info. > > thanks, There is probably some smart way to do this that I don't know, but in wxPython you could have your textbox and bind it to an EVT_TEXT event, and then in the event handler for that write the contents of the textbox to your file. This way on any change in the textbox, there would be a write to the file. But I don't know if that is practical or if the writes would keep up well. You could also have a counter and when the counter reaches x characters then do a write. Or you could set a timer and do the write every x seconds. From ethan at stoneleaf.us Wed Jun 11 13:37:44 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 11 Jun 2008 09:37:44 -0800 Subject: can't assign to literal In-Reply-To: <484feda6_2@news.tm.net.my> References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> <1a244dc4-4d10-491d-8ec7-224f3a1f0df5@m73g2000hsh.googlegroups.com> <484feda6_2@news.tm.net.my> Message-ID: <48500D68.6050406@stoneleaf.us> TheSaint wrote: > On 00:15, gioved? 12 giugno 2008 Ethan Furman wrote: > > >>I like Vim (Vi Improved) > > What about justifying text ? Do you mean indenting, or wrapping? Vim has excellent indenting support, and Python files already included that support proper indenting, syntax coloring, etc. I don't use the line-wrapping feature myself, so I have no experience with it. -- Ethan From mal at egenix.com Fri Jun 27 06:40:34 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 27 Jun 2008 12:40:34 +0200 Subject: Multiprecision arithmetic library question. In-Reply-To: References: Message-ID: <4864C3A2.7050201@egenix.com> duncan smith wrote: > Michael Press wrote: >> In article , >> Mark Wooding wrote: >> >>> Michael Press wrote: >>> >>>> I already compiled and installed the GNU multiprecision library >>>> on Mac OS X, and link to it in C programs. How do I link to the >>>> library from Python? >>> You know that Python already supports multiprecision integer arithmetic, >>> right? If you desperately want GMP, though, there's the gmpy module >>> (q.g.). >> >> No, I do not know that. Define desperate. Does Python support the >> extended Euclidean algorithm >> and other number theory functions? >> How fast does Python multiply? >> Not that the latter is particularly important, >> as C is built for speed. >> >> I've been fooling around. Ran dir(gmpy), and it does not show the full >> complement of GMP >> library functions, such as the various division >> functions. e.g. mpz_tdiv_qr. >> > > There's also > http://www.egenix.com/products/python/mxExperimental/mxNumber/. I'm not > sure how the functionality compares to GMPY. mxNumber is a implementation of number types that use GMP for the internals. It doesn't expose all APIs available in GMP and also doesn't use a 1-1 mapping. Instead, it wraps the basic types available in GMP in Python objects which can be used just like normal Python numbers. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From Lie.1296 at gmail.com Mon Jun 9 12:39:45 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 9 Jun 2008 09:39:45 -0700 (PDT) Subject: money data type References: Message-ID: On Jun 9, 10:22?pm, Stephan Diehl wrote: > Hi lazyweb, > I'm wondering, if there is a usable money data type for python available. > A quick search in pypi and google didn't convey anything, even though the > decimal data type seemed to be planned as a money data type originaly. > Thanks for any pointers > > Stephan What is it that you feel is lacking in the decimal datatype that makes you feel you require a money datatype? Decimal datatype was a general purpose fixed-point number, which is usually the behavior required for money calculation, but it's not named 'money' because this behavior isn't only useful for money calculation, so they don't name it money. From nihao at qinqin.com Sun Jun 22 14:32:36 2008 From: nihao at qinqin.com (Serve Lau) Date: Sun, 22 Jun 2008 20:32:36 +0200 Subject: -1/2 Message-ID: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> What is the expected result of -1/2 in python? From lawtonpaul at gmail.com Mon Jun 16 01:35:03 2008 From: lawtonpaul at gmail.com (takayuki) Date: Sun, 15 Jun 2008 22:35:03 -0700 (PDT) Subject: newbie question: for loop within for loop confusion References: Message-ID: Thanks to everyone for the excellent advice. Roy: I did as you suggested and could see after staring at the output for awhile what was going on. The print statements really helped to put a little light on things. Yes, I agree that "learning to fish" is the best way. John: There were two "inchworms" because "c" is in "inchworm" so it shouldn't print. Thanks for your detailed description of the for loop. The Saint: i'll check out the word = line.split() command. After much flailing about, here's a loop that is working: def hasnolet2(avoid): fin = open('animals.txt') for line in fin: word = line.strip() length = len(avoid) x = 0 noprint = 0 while length -1 >= x: if avoid[x] in word: noprint = noprint + 1 x = x + 1 if noprint == 0: print word hasnolet2('abcd') which should return: fish horse hasnolet2('abcd') From arslanburney at gmail.com Thu Jun 12 07:30:21 2008 From: arslanburney at gmail.com (arslanburney at gmail.com) Date: Thu, 12 Jun 2008 04:30:21 -0700 (PDT) Subject: Plotting Graphs using Gnuplot Message-ID: <17f71342-0cc4-4eea-b99a-668096302b8b@a70g2000hsh.googlegroups.com> Hello. Was trying to create a simple plotting function. Wasnt working however. If i write the same code without putting it inside a function it works. :S. Could some1 tell me the problem? Heres the code: # File name Plotting2 import Gnuplot def plot(original, expected, actual): if type (original) != type([]): return False else: gp = Gnuplot.Gnuplot() gp('set data style lines') # Make the plot items plot1 = Gnuplot.PlotItems.Data(original, title="Original") plot2 = Gnuplot.PlotItems.Data(expected, title="Expected") plot3 = Gnuplot.PlotItems.Data(actual, title="Acutal") return gp.plot(plot1, plot2, plot3) ---- import Plotting2 #The name of my file... Plotting2.plot( [(2,3), (3,4)], [(4,5), (5,6)], [(1,3), (4,8)] ) From sasa.bistrovic at ck.t-com.hr Thu Jun 12 11:38:34 2008 From: sasa.bistrovic at ck.t-com.hr (Saąa Bistrović) Date: Thu, 12 Jun 2008 17:38:34 +0200 Subject: FPC: Exception : Unknown Run-Time error : 210 Message-ID: Sa?a Bistrovi? Antuna Mihanvi?a 13 40000 ?akovec Croatia sasa.bistrovic at ck.t-com.hr FPC: Exception : Unknown Run-Time error : 210 Hi, I'm Sa?a from Croatia. And I have : Windows XP PRO SP3. Pentium II MMX 400MHz. 256 MB of RAM. I tried to compile fp.pas. But I get this error message : 'Running "c:\fpc\fpcbuild-2.2.0\fpcsrc\ide\fp.exe "' 'Starting value of ConsoleMode is $0000001F' 'Compiler Verison f p c b u i l d - 2 . 2 . 0 \ f p c s r c \ i d e \ f p . e x e ' + same unknown exe characters as for GBD Verison 'GBD Verison f p c b u i l d - 2 . 2 . 0 \ f p c s r c \ i d e \ f p . e x e ' + same unknown exe characters as for Compiler Verison 'Cygwin "C:\FPC\222A5D~1.0\BIN\I386-W~1\cygwin1.dll" version 1005.18.0.0' 'An unhandled exception occurred at $004A74E6' 'Exception : Unknown Run-Time error : 210' ' $004A74E6 TSWITCHES__ADDBOOLEANITEM, line 602 of c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/FPSwitch.pas' ' $004A92F4 INITSWITCHES, line 1150 of c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/FPSwitch.pas' ' $004020DF main, line 382 of c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/fp.pas' From mal at egenix.com Wed Jun 4 04:37:39 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 04 Jun 2008 10:37:39 +0200 Subject: a python phpmyadmin like program In-Reply-To: References: Message-ID: <48465453.9080605@egenix.com> On 2008-06-03 20:49, Gandalf wrote: > is their any graphic program for handling sqlite like phpmyadmin or > access in python? If you run Firefox: https://addons.mozilla.org/en-US/firefox/addon/5817 -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jun 04 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania 32 days to go :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From mathewedward at gmail.com Tue Jun 10 22:53:05 2008 From: mathewedward at gmail.com (mathewedward) Date: Tue, 10 Jun 2008 19:53:05 -0700 (PDT) Subject: Earn $5000 + /mo Just by clicking Ads :: all u need is a internet connection Message-ID: <7c0930d3-e51d-411c-87bc-fc975d58a0f8@a9g2000prl.googlegroups.com> Did you know there are sites that are willing to pay you to click Ads? Did you also know that it's FREE to sign up to them? You can earn moneyonline, right now, there are already tens of thousands of people that are paid to work at home, some are making a tidy sum just by clickingon a link. PTC's or Paid to Click Sites offer FREE Memberships so you can make cash at home right away. Some Get Paid to Click Sites evenoffer you cash in your account just for signing up. Many PTC's we havelisted are well paying so earnings are great even if you're clickingalone. Earnings Example ? You click 10 ads per day = $0.10 ? 20 referrals click 10 ads per day = $2.00 ? Your daily earnings = $2.10 ? Your weekly earnings = $14.70 ? Your monthly earnings = $63.00 You Can Check Out The Payment Proofs at my site .. at . http://tinyurl.com/6dwknm Here are some the great resources we have prepared for You..... ? PTC Guide => http://tinyurl.com/55l6ql ? The PTC Directory => http://tinyurl.com/5qe7p7 ? Scam Alert => http://tinyurl.com/5q6vyf ? Top Rated => http://tinyurl.com/5gycuk Some Of the Top PTC Programs 07bux => http://tinyurl.com/5zwrq8 Buxear => http://tinyurl.com/5nsaku Bux.to => http://tinyurl.com/6pzzls Angelbux => http://tinyurl.com/58nlah 10Bux => http://tinyurl.com/6rezpq FoxCash => http://tinyurl.com/3oxu7k World-bux => http://tinyurl.com/3tz97z From ivan.illarionov at gmail.com Thu Jun 5 14:38:01 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 5 Jun 2008 11:38:01 -0700 (PDT) Subject: Tuples part 2 References: <6d3e6d40-63a6-40d1-8ea4-5ddf40238d8d@m44g2000hsc.googlegroups.com> <99bc30fb-532a-4c4f-9f5e-e7a18c28d2a5@z72g2000hsb.googlegroups.com> <0ecaaa47-3ad4-4f67-9d48-94d5d1951bc6@y21g2000hsf.googlegroups.com> Message-ID: On 5 ???, 21:22, George Sakkis wrote: > On Jun 5, 11:48 am, Ivan Illarionov wrote: > > > > > On 5 ???, 19:38, George Sakkis wrote: > > > > On Jun 5, 11:21 am, Ivan Illarionov wrote: > > > > > On 5 ???, 18:56, Ivan Illarionov wrote: > > > > > > On 5 ???, 18:19, "victor.hera... at gmail.com" > > > > > wrote: > > > > > > > On Jun 5, 3:49 pm, Ivan Illarionov wrote: > > > > > > > > On 5 ???, 01:57, "victor.hera... at gmail.com" > > > > > > > wrote: > > > > > > > > > Hi Everyone, > > > > > > > > > i have another question. What if i wanted to make n tuples, each with > > > > > > > > a list of coordinates. For example : > > > > > > > > > coords = list() > > > > > > > > for h in xrange(1,11,1): > > > > > > > > for i in xrange(1, 5, 1) : > > > > > > > > for j in xrange(1, 5, 1) : > > > > > > > > for k in xrange(1,2,1) : > > > > > > > > coords.append((i,j,k)) > > > > > > > > lista+str(h)= tuple coords > > > > > > > > print tuple(coords) > > > > > > > > > so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do > > > > > > > > it the way i show you above but it is not working properly. I wish you > > > > > > > > could help me with that. Thanks again, > > > > > > > >>> from itertools import repeat, izip > > > > > > > >>> coords = tuple((i,j,k) for i in xrange(1,5) for j in xrange(1,5) for k in xrange(1,2)) > > > > > > > >>> locals().update(("tuple%s" % i, coord) for i, coord in izip(xrange(1,11), repeat(coords))) > > > > > > > >>> tuple1 > > > > > > > > ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (2, 1, 1), (2, 2, 1), (2, > > > > > > > 3, 1), (2 > > > > > > > , 4, 1), (3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1), (4, 1, 1), (4, 2, > > > > > > > 1), (4, 3 > > > > > > > , 1), (4, 4, 1)) > > > > > > > > Does this help? > > > > > > > > But I don't understand why you need this? > > > > > > > > Ivan > > > > > > > Hi, > > > > > > > What i need is, for example: > > > > > > > tuple 1=((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)) > > > > > > > tuple 2=((2, 1, 1), (2, 2, 1), (2, 3, 1), (2, 4, 1)) > > > > > > > tuple 3=((3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1)) > > > > > > > and so on. Please help me and sorry for not taking the time to post my > > > > > > questions properly. > > > > > > > Victor > > > > > > Or even so: > > > > > > locals().update(("tuple_%s" % i, tuple((i,j,k) for j in range(1,5) for > > > > > k in range(1,2))) for i in range(1,5)) > > > > > > Ivan > > > > > Tried to make it readable: > > > > > def iter_coords(i): > > > > for j in xrange(1,5): > > > > for k in xrange(1,2): > > > > yield i, j, k > > > > > def iter_vars(): > > > > for i in xrange(1, 5): > > > > yield "tuple_%s" % i, tuple(iter_coords(i)) > > > > > locals().update(dict(iter_vars())) > > > > locals().update() works by accident here because it's in global scope; > > > it doesn't work within a function. > > > > Use a proper data structure, like a dict or a list, and access each > > > tuple list as 'tuples[n]' instead of 'tuple_n'. > > > > George > > > OP wanted variables and I showed him how to do this. I agree that a > > list or a dict would be better. > > > Ivan > > Generating variable names at runtime doesn't work for locals and it is > a bad solution for globals in 99.9% of the cases. It is usually more > helpful to point someone who can't even express his problem clearly to > the right direction, rather than taking his pseudocode literally and > coming up with a semi-working translation. > > George Understanding of how to create variables dynamically can be good for OP's learning curve even though it's a bad solution in this particular case. I agree that it was my mistake to not point him in the right direction. Ivan From jonathan at findmeon.com Wed Jun 11 13:17:40 2008 From: jonathan at findmeon.com (Jonathan Vanasco) Date: Wed, 11 Jun 2008 10:17:40 -0700 (PDT) Subject: question about import Message-ID: <886765d0-2be7-4a66-b838-032aebae0622@d1g2000hsg.googlegroups.com> I'm a little unclear about import / __import__ I'm exploring dynamically importing modules for a project, and ran into this behavior works as expected: app = __import__( myapp ) appModel = __import__( myapp.model ) but... appname= 'myapp' app = __import__( "%s" % appname ) appModel = __import__( "%s.model" % appname ) In the latter example, app and appModel will always seem to be imported as 'myapp' , and I've yet to find a way to address the .model namespace I know 'dynamically importing modules' is cursed upon -- and I'm likely rewriting hundreds of line of codes so I can work around this with a registration system -- however I'd like to understand why this occurs and know if what i'm trying is even possible. From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 9 04:35:16 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 09 Jun 2008 10:35:16 +0200 Subject: Q re documentation Python style In-Reply-To: References: Message-ID: <484ceaf7$0$7877$426a74cc@news.free.fr> kj a ?crit : (snip) > I think that sometimes even simple functions require a lot of > documentation. For example, I want to document a function that > takes a dictionary as argument, and this dictionary is expected to > have 5 keys. (When the number of mandatory arguments gets above > 4, I find that it's too difficult to remember their order, so I > resort to using a dictionary as the single argument.) Python supports keyword (named) arguments, so you don't have to remembed the order, ie: def func(arg1, arg2, arg3, arg4): # code here func(arg2=42, arg4="toto", arg3="truc", arg1="foo") Also, with good enough naming (perhaps one of the most difficult part of programming FWIW), you don't necessarily need an exhaustive documentation of each and every detail. (snip) > Then again, I suppose that Python's relative formal rigidity is > considered by many to be a strength. Which means that, to be > comfortable with Python, one has to learn to like this (relatively) > rigid structure... Or to learn how to hook into the system. If you want to put the doc before or after the function's body, it is not a big problem: # doc after the function's body: def func(args): # code here func.__doc__ = """ doc here ... """ # doc before the function's body: def document(doc): def _document(func): func.__doc__ = doc return func return _document @document(""" doc here and here and here etc... """) def func(): # code here I wouldn't personnaly use any of the above styles, but as far as I'm concerned, I don't write exhaustive docstrings. Good naming (somehow one of the hardest part in programming IMHO) and simplicity (small simple functions doing one thing each) already provide some part of the documentation IMHO, and code always provides the most exhaustive documentation you'll ever find !-) From arnodel at googlemail.com Sun Jun 1 03:18:23 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 01 Jun 2008 08:18:23 +0100 Subject: Bring object 'out of' Class? References: Message-ID: dave writes: > Hello, > > I'm currently on the class section of my self-taught journey and have > a question about classes: is it possible to bring a object created > inside the class definitions outside the class so it can be accessed > in the interpreter? > > For example, right now I'm working (within Allen Downey's Python > Programmer book) with creating a 'hand' of cards. I want to be able > to deal to 'x' amount of cards to 'x' amount of hands and then be able > to manipulate those hands afterwards. I'm not sure if even what I'm > asking is possible or if I'm getting ahead of myself. > > As always, thanks for all your help. My learning is greatly enhanced > with everyone's input on this board. Please feel free to > comment/critique the code... > > Here is the section of code that deals hands (but doesn't do anything > past that): > > def deal_cards(self, num_of_hands, num): > '''deals x amount of cards(num) to each hand''' > for i in range(num_of_hands): > handname = Hand('hand%d' % i) > self.deal(handname, num) > print '::::%s::::' % (handname.label), '\n', handname, '\n' > You need to use a 'return' statement: def deal_cards(self, num_of_hands, num): '''deals x amount of cards(num) to each hand''' hands = [] for i in range(num_of_hands): newhand = Hand('hand%d' % i) self.deal(newhand, num) hands.append(newhand) print '::::%s::::' % (handname.label), '\n', handname, '\n' return Hand Then you can write: >>> hands = deck.deal_cards(4, 5) # On fait une belotte? And I don't see the need of defining 'Hand' inside 'Deck'. HTH -- Arnaud From musiccomposition at gmail.com Wed Jun 25 22:49:02 2008 From: musiccomposition at gmail.com (Benjamin) Date: Wed, 25 Jun 2008 19:49:02 -0700 (PDT) Subject: Threads, GIL and re.match() performance References: Message-ID: <25be11e7-157c-4af0-be3a-fa7a6c9c3acc@m3g2000hsc.googlegroups.com> On Jun 25, 9:05?am, Mirko Dziadzka wrote: > > 1) Is there a reason for this? I think it is because the Python re library uses the Python C-API which is not threadsafe. > 2) Is the regex library not thread-safe? > 3) Is it possible, to release the GIL in re.match() to > ? ?get more performance? From sajmikins at gmail.com Mon Jun 23 00:53:28 2008 From: sajmikins at gmail.com (Simon Forman) Date: Sun, 22 Jun 2008 21:53:28 -0700 (PDT) Subject: Tkinter canvas drag/drop obstacle References: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> Message-ID: On Jun 22, 7:41?pm, Peter Pearson wrote: > On Fri, 20 Jun 2008 13:41:35 -0300, Guilherme Polo wrote: > > On Fri, Jun 20, 2008 at 1:11 PM, Peter Pearson wrote: > >> Tkinter makes it very easy to drag jpeg images around on a > >> canvas, but I would like to have a "target" change color when > >> the cursor dragging an image passes over it. ?I seem to be > >> blocked by the fact that the callbacks that might tell the > >> target that the mouse has entered it (, , > >> even ) aren't called if the mouse's button is down. > >> What am I missing? ?Have I failed to find the right Tkinter > >> document? ?Is Tkinter the wrong tool for this job? ?Thanks. > > > I believe the only way to achieve this is binding to the > > entire canvas, then checking if the x, y coords are inside the > > "target". > > Ugh. ?OK, thanks. > > -- > To email me, substitute nowhere->spamcop, invalid->net. Yep, but it's not so bad: from Tkinter import * c = Canvas() c.pack() i = c.create_oval(1, 1, 100, 100, fill='green') def cb(e): items = c.find_overlapping( e.x, e.y, e.x + 1, e.y + 1 ) if not items: return print items c.bind("", cb) mainloop() The c.find_overlapping() method returns a tuple. I believe the item ids in the tuple (if any) will be in the same order as the items Z order on the canvas, so "items[-1]" should always be the "topmost" graphic item (again, if any.) From mensanator at aol.com Mon Jun 2 15:42:12 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 2 Jun 2008 12:42:12 -0700 (PDT) Subject: Formatting Output References: <6e94b4dc-5920-447e-9971-96ec6a48b9ce@c58g2000hsc.googlegroups.com> Message-ID: <6ea2e85a-d00c-4228-98be-431205fceb7b@34g2000hsf.googlegroups.com> On Jun 2, 3:38?am, Chris wrote: > On Jun 2, 9:34?am, "victor.hera... at gmail.com" > > wrote: > > Hi, > > > i am building a little script and i want to output a series of columns > > more or less like this: > > > 1 ?5 ?6 > > 2 ?2 ?8 > > 2 ?9 ?5 > > > The matter is that i don't know in advance how many columns there will > > be. By the way, each column will be actually FLOATs, not INTs. How can > > i do this ? Any help welcome. Regards, > > > Victor > > import sys > float_list = [1.0, 5.0, 6.0, 2.0, 2.0, 8.0, 2.0, 9.0, 5.0] > num_columns = 3 > for i,item in enumerate(float_list): > ? ? sys.stdout.write('%.4f\t' % item) > ? ? if not (i+1) % num_columns: > ? ? ? ? sys.stdout.write('\n') > > Problem with this approach is it doesn't cater for instances where you > exceed the standard 80 characters for a terminal window. That wouldn't be a problem if being re-directed to a file. A bigger problem would be if his list were actually [1.0,2.0,2.0,5.0,2.0,9.0,6.0,8.0,5.0] but he still wanted it printed 1 5 6 2 2 8 2 9 5 as if he always wants 3 rows, but doesn't know how many columns it will take. In which case, he could do something like this: import sys float_list = [1.0,2.0,2.0,5.0,2.0,9.0,6.0,8.0,5.0] num_rows = 3 num_cols = divmod(len(float_list),num_rows) for r in xrange(num_rows): for c in xrange(num_cols[0]): sys.stdout.write('%.4f\t' % float_list[c*num_rows + r]) if num_cols[1]>0 and r References: Message-ID: <663744510806121546q4a425854o215bf7b473a95420@mail.gmail.com> > Hello , > following scenario > > list_current = [ "welcome", "search", "done", "result"] > list_ldap = [ "welcome", "hello"] > > result: > > list_toadd = [ "hello"] > > by words said , i want to check if list item from list_ldap exists in > list_current if not i want to add it to list_toadd. > > Thanks! > > D. list_toadd = [i for i in list_ldap if i not in list_current] seems to work. I'm sure there's a way to do it with set objects as well. -Steven From catalinfest at gmail.com Sun Jun 29 11:34:57 2008 From: catalinfest at gmail.com (catalinfest at gmail.com) Date: Sun, 29 Jun 2008 08:34:57 -0700 (PDT) Subject: gelato - nvidia and python Message-ID: <65fcd6a4-131e-4d7c-96b3-402296bf2a18@y21g2000hsf.googlegroups.com> Did somebody worked with gelato from nvidia and python? I have some C cod from books nvidia . This is : " GelatoAPI *r = GelatoAPI::CreateRenderer(); r->Camera ("main"); ... API calls through r ... r->Render ("main"); delete r; // Finished with this renderer " the code for python i create is only this : " python Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import gelato >>> from gelato import * >>> r=gelato.CreateRenderer >>> print r >>> dir(r) ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__str__'] " And I blocked here... Thank you . From socyl at 987jk.com.invalid Sat Jun 7 14:25:24 2008 From: socyl at 987jk.com.invalid (kj) Date: Sat, 7 Jun 2008 18:25:24 +0000 (UTC) Subject: How to send a POST request? References: Message-ID: Thanks to Jeff and subeen for the helpful comments and suggestions. Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From jamitwidme at gmail.com Mon Jun 30 12:55:28 2008 From: jamitwidme at gmail.com (jamitwidme at gmail.com) Date: Mon, 30 Jun 2008 09:55:28 -0700 (PDT) Subject: raw_input into Tkinter ? Message-ID: <634e2b50-45ba-4b93-89b4-0afd739adaf3@z66g2000hsc.googlegroups.com> Is there any way to type into a Tkinter frame window? I want to use raw_input() within a Tkinter frame. From kyosohma at gmail.com Tue Jun 17 14:37:09 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 17 Jun 2008 11:37:09 -0700 (PDT) Subject: text alignment References: <39d1c620-9923-46e7-999d-ed86c8b465ff@34g2000hsh.googlegroups.com> <114f3f4c-4004-488b-86c5-4bf6416e15bd@l42g2000hsc.googlegroups.com> <8d563101-53f0-41d3-a544-ee0ba1d58db5@m36g2000hse.googlegroups.com> Message-ID: <66b9d47c-2746-44de-b6cb-6e614519e15a@c65g2000hsa.googlegroups.com> On Jun 17, 12:59?pm, Gandalf wrote: > On Jun 17, 7:49?pm, Mike Driscoll wrote: > > > > > On Jun 17, 11:45?am, Gandalf wrote: > > > > On Jun 17, 6:43?pm, Gandalf wrote: > > > > > Hi every one. What is the similar python WX style property for CSS > > > >text-align? > > > > > I need this item text to start from the right direction: > > > > > aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60)) > > > > ? ? ? ? aaa.LoadPage('../../aa.html') > > > > > Thanks! > > > > *right to the left direction... > > > > And I'm using pythin 2.5 on XP (I forget to mention...) > > > The HtmlWindow widget can only display simple html. So, while you > > cannot use CSS, you should be able to use the simple html alignment > > directives. Check out the following site for pointers: > > >http://www.htmlite.com/lite008.php > > > If you want to be able to use CSS and javascript, you'll want to use > > the ActiveX_IEHtmlWindow (wx.lib.iewin) widget instead as it embeds > > Internet Explorer. > > > Mike > > well thanks it seems useful... > My question is about general items in WX and how to position them > inside an element without using CSS. It's only coincidence My item is > HtmlWindow Positioning the widgets within a container widgets (such as a wx.Window, wx.Panel or wx.Frame) is usually done with sizers. Something like this: mySizer.Add(myWidget, 0, wx.ALIGN_RIGHT) I've written a few tutorials on aligning widgets in various types of sizers. You might find them helpful. There are located here: http://www.blog.pythonlibrary.org You might also find this site useful too: http://www.zetcode.com/wxpython/layout/ Mike From kay.schluehr at gmx.net Sat Jun 7 14:37:53 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 7 Jun 2008 11:37:53 -0700 (PDT) Subject: ABC question: what is the purpose of the register() method? Message-ID: <22c53e8d-1f95-465f-932e-b0b0bbf148ba@x41g2000hsb.googlegroups.com> I was reading PEP 3119 (http://www.python.org/dev/peps/pep-3119/ ) and have done some experiments using Python 3.0a5. Now I'm somewhat puzzled about the purpose of the ABCMeta.register() method. One can use the register() method to register any class as a virtual subclass of any ABC. For example one can register `int` on `Iterable` and therefore it is a subclass which is confirmed in the issubclass check. What is that good for? This registration might even conflict with the implementation of __subclasscheck__. So one might expect that register(C) leads to an acceptance of a class as a subclass but this isnt't true if __subclasscheck__(C) rejects it. Why isn't __subclasscheck__ not sufficient? Example: -------------- class Interface(metaclass = ABCMeta): @classmethod def __subclasscheck__(cls, C): return cls.__abstractmethods__.issubset(C.__dict__) # some contract... class IAppendable(Interface): @abstractmethod def append(self, item): pass >>> issubclass(list, IAppendable) True >>> issubclass(tuple, IAppendable) False >>> IAppendable.register(int) >>> issubclass(int, IAppendable) False >>> import collections.Iterable as Iterable >>> Iterable.register(int) >>> issubclass(int, Iterable) True From hat at se-162.se.wtb.tue.nl Fri Jun 27 09:30:28 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 27 Jun 2008 15:30:28 +0200 Subject: shorten path to files References: Message-ID: On 2008-06-27, cesco wrote: > Hi, > > I need to retrieve the content of some files which are placed on a > network drive so in order to open them I need the full path to the > file. > Unfortunately some times the path is longer than 256 characters and in > Windows such a path is too long with the result that the file is not > found (though it is there). > > Is there any way around this? >From your description, it sounds like a OS problem, and not a Python problem. You may have better luck if you ask in a Win* newsgroup. Albert From rschroev_nospam_ml at fastmail.fm Fri Jun 13 06:20:27 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 13 Jun 2008 12:20:27 +0200 Subject: boolian logic In-Reply-To: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> References: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> Message-ID: marc wyburn schreef: > HI all, I'm a bit stuck with how to work out boolian logic. > > I'd like to say if A is not equal to B, C or D: > do something. > > I've tried > > if not var == A or B or C: > and various permutations but can't seem to get my head around it. I'm > pretty sure I need to know what is calulated first i.e the not or the > 'OR/AND's if var not in (A, B, C): do_something() -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From n.emami at gmail.com Wed Jun 18 05:10:57 2008 From: n.emami at gmail.com (Nader) Date: Wed, 18 Jun 2008 02:10:57 -0700 (PDT) Subject: reading from a gzip file Message-ID: <24f0b04f-1f34-41d4-9015-fe90e95819ba@m45g2000hsb.googlegroups.com> Hello, I have a gzip file and I try to read from this file withe the next statements: gunziped_file = gzip.GzipFile('gzip-file') input_file = open(gunziped_file,'r') But I get the nezt error message: Traceback (most recent call last): File "read_sfloc_files.py", line 131, in ? input_file = open(gunziped_file,'r') TypeError: coercing to Unicode: need string or buffer, instance found I think that I do some mistake. Would some body tell me what is my mistake? Nader From mnordhoff at mattnordhoff.com Thu Jun 19 06:14:11 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 19 Jun 2008 10:14:11 +0000 Subject: python/ruby question.. In-Reply-To: <3b017f08-2d42-4c65-9003-19ffc606234d@l64g2000hse.googlegroups.com> References: <3b017f08-2d42-4c65-9003-19ffc606234d@l64g2000hse.googlegroups.com> Message-ID: <485A3173.3080908@mattnordhoff.com> Mensanator wrote: > On Jun 18, 10:33?pm, "bruce" wrote: >> hi... >> >> can someone point me to where/how i would go about calling a ruby app from a >> python app, and having the python app being able to get a returned value >> from the ruby script. >> >> something like >> >> test.py >> ?a = os.exec(testruby.rb) >> >> testruby.py >> ?foo = 9 >> ?return foo >> >> i know this doesn't work... but i've been searching for hours on this with >> no luck.... (and yeah, i'm relatively new to both ruby/python!!) >> >> thanks > > Well, I don't know anything about Ruby, but here's > how I do it for C programs (compiled to .exe that > write to stdout). > > > import os > factor_program = 'factor! -d200 ' # factor!.exe from MIRACL > > n = > '50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749' > > # call external program and capture stdout > the_output = os.popen(factor_program+n).readlines() > > print 'n: %s' % n > for i in the_output: > print i, You're supposed to use the subprocess module. In this case, something like: import subprocess factor_program = ['factor!', '-d200'] ... p = subprocess.Popen(factor_program + [n], stdout=subprocess.PIPE) p.wait() # wait for it to finish; not sure how necessary it is the_output = p.stdout.readlines() See subprocess's documentation [1], which includes guides on replacing os.popen* and other functions with it. [1] -- From tjreedy at udel.edu Sun Jun 15 16:05:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 15 Jun 2008 16:05:02 -0400 Subject: randrange loops References: <6e424f2a-872d-4dd1-b28d-cf2a985895c9@j22g2000hsf.googlegroups.com> Message-ID: wrote in message news:6e424f2a-872d-4dd1-b28d-cf2a985895c9 at j22g2000hsf.googlegroups.com... | Hi, | | | I've created a method where the script defines twenty variables and | several of them should be random having a maximum and a minimum value. | | What I did was this: | | from random import randrange as rr, random | | self.tr2_vezes = self.rr(self.d_tr2_vezes[0],self.d_tr2_vezes[-1], | 1) # just an example, others are similar Are we to presume that self.rr is rr? | The minimum and maximum limits are never lower than -50 and higher | than 250 and are integer. | | Many times, not always, the problem is that the script just loops | forever and no value is chosen for the variable. | | What's happening here? What am I doing wrong? On what line does it 'loop forever'? Are you saying that the same code with same input sometimes works and sometimes does not? In any case, try to reduce it to the minumum that either always or sometimes fails. And post that. tjr From maric at aristote.info Fri Jun 27 12:36:04 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 27 Jun 2008 18:36:04 +0200 Subject: Use of the "is" statement In-Reply-To: References: Message-ID: <200806271836.05122.maric@aristote.info> Le Friday 27 June 2008 18:26:45 Christian Heimes, vous avez ?crit?: > Ask yourself if you are interested if f.tell() returns exactly the same > 0 object ("is") or a number that is equal to 0 ("=="). That said, "f.tell() == 0" and "f.tell() != 0" should be written "f.tell()" and "not f.tell()" in python. if not f.tell() : print 'at the beginning of the file" -- _____________ Maric Michaud From fc14301589 at icqmail.com Wed Jun 11 11:04:29 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Wed, 11 Jun 2008 23:04:29 +0800 Subject: catastrophic regexp, help! References: Message-ID: <484fe991_2@news.tm.net.my> On 12:20, mercoled? 11 giugno 2008 cirfu wrote: > patzln = re.compile("(\w* *)* zlatan ibrahimovic (\w* *)*") I think that I shouldn't put anything around the phrase you want to find. patzln = re.compile(r'.*(zlatan ibrahimovic){1,1}.*') this should do it for you. Unless searching into a special position. In the other hand, I'd like to understand how I can substitute a variable inside a pattern. if I do: import os, re EOL= os.linesep re_EOL= re.compile(r'[?P\s+2\t]')) for line in open('myfile','r').readlines(): print re_EOL.sub('',line) Will it remove tabs, spaces and end-of-line ? It's doing but no EOL :( -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From boris.smirnov at gmail.com Thu Jun 12 04:28:13 2008 From: boris.smirnov at gmail.com (boriq) Date: Thu, 12 Jun 2008 01:28:13 -0700 (PDT) Subject: suppress opening command window after using os.system command Message-ID: Hi, I'm using in my script command os.system('command') on Windows XP. Each time the os.system command is used, python opens an empty ms-dos command window (the black one) and then closes it. So when in one script the os.system command 50 times is used, I see 50 black windows. Is there a way of how to suppress this unnecessary command windows to be opened? thx. Boris From drobinow at gmail.com Wed Jun 11 12:42:33 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Wed, 11 Jun 2008 09:42:33 -0700 (PDT) Subject: Numpy array to gzip file References: Message-ID: <404de0ba-edd5-47ff-8b25-132aa0b5b570@c58g2000hsc.googlegroups.com> On Jun 11, 9:17 am, Sean Davis wrote: > I have a set of numpy arrays which I would like to save to a gzip > file. Here is an example without gzip: > > b=numpy.ones(1000000,dtype=numpy.uint8) > a=numpy.zeros(1000000,dtype=numpy.uint8) > fd = file('test.dat','wb') > a.tofile(fd) > b.tofile(fd) > fd.close() > > This works fine. However, this does not: > > fd = gzip.open('test.dat','wb') > a.tofile(fd) > > Traceback (most recent call last): > File "", line 1, in > IOError: first argument must be a string or open file > > In the bigger picture, I want to be able to write multiple numpy > arrays with some metadata to a binary file for very fast reading, and > these arrays are pretty compressible (strings of small integers), so I > can probably benefit in speed and file size by gzipping. > > Thanks, > Sean Use fd.write(a) The documentation says that gzip simulates most of the methods of a file object. Apparently that means it does not subclass it. numpy.tofile wants a file object Or something like that. From jgodoy at gmail.com Wed Jun 25 06:34:47 2008 From: jgodoy at gmail.com (Jorge Godoy) Date: Wed, 25 Jun 2008 07:34:47 -0300 Subject: Apache2 + Python WITHOUT mod_pytho References: <4f90e1e5-056e-4f61-866b-015a15030ebf@e39g2000hsf.googlegroups.com> Message-ID: pistacchio wrote: > Hi to all! > How can i configure apache2 so that it processes all .py files with > python _without_ using mod_python? > I'm on Ubuntu 8.4. I have no idea about how to do that in Ubuntu. Use fcgi or wsgi for your Python scripts. There should be recipes around for your distribution. -- Jorge Godoy From basti.wiesner at gmx.net Mon Jun 16 13:53:44 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Mon, 16 Jun 2008 19:53:44 +0200 Subject: bpython - fancy Python shell References: Message-ID: Wolfgang Grafen : > I couldn't get it work on Solaris (modified some lines for Python2.3). If solaris doesn't have a readline library, you might try to compile gnu readline, and recompile python (also a chance to get the current version 2.5) > One reason was that I had to download pyreadline separately > - I did than but now pyreadline requires either ironpython or > a windows installation. pyreadline is a windows-only thing. Since readline is a standard module on most unix systems and linux, there was no need to implement pyreadline for these systems. It would have been difficult anyway, since the windows console is completely different to unix consoles (which are fairly compatible to each other, a outcome of POSIX efforts). -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From steven.p.clark at gmail.com Tue Jun 10 17:46:06 2008 From: steven.p.clark at gmail.com (Steven Clark) Date: Tue, 10 Jun 2008 17:46:06 -0400 Subject: can't assign to literal In-Reply-To: References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> Message-ID: <663744510806101446r60b18458oc8335c36adb5fb79@mail.gmail.com> On Tue, Jun 10, 2008 at 5:30 PM, maehhheeyy wrote: > On Jun 10, 1:21 pm, Matimus wrote: >> On Jun 10, 12:53 pm, maehhheeyy wrote: >> >> > this is stopping my program from running properly. is there something >> > wrong in my code when that happens? >> >> yes >> >> Post your code, or at least the full error message if you want more >> details. >> >> Matt > > for 1 in oids, vals head_oids: > SyntaxError: can't assign to literal > -- > http://mail.python.org/mailman/listinfo/python-list > Wow. http://catb.org/~esr/faqs/smart-questions.html From maric at aristote.info Tue Jun 24 01:44:57 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 24 Jun 2008 07:44:57 +0200 Subject: An idiom for code generation with exec In-Reply-To: <0967da3a-1fea-401e-896d-9c099b3054ce@c58g2000hsc.googlegroups.com> References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <0967da3a-1fea-401e-896d-9c099b3054ce@c58g2000hsc.googlegroups.com> Message-ID: <200806240744.58075.maric@aristote.info> Le Tuesday 24 June 2008 07:18:47 eliben, vous avez ?crit?: > > If code generation is not the best, and I fail to see any performance > > issue that could explain such a choice, except a misunderstanding of > > what "compilation" means in python, just don't use it, use closures or > > callable instances, there are many way to achieve this. > > And while we're on the topic of what compilation means in Python, I'm > not sure I fully understand the difference between compiled (.pyc) > code and exec-ed code. Is the exec-ed code turned to bytecode too, > i.e. it will be as efficient as compile-d code ? Yes, exactly the same, cpython always interprets compiled code, when a script is executed for example, it is parsed/compiled to bytecode by the interpreter before any execution. The .pyc/pyo files are just a cache created at import time to avoid the rather time consuming parsing stage. -- _____________ Maric Michaud From rhamph at gmail.com Wed Jun 11 13:49:08 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Wed, 11 Jun 2008 10:49:08 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <6e6df35e-e641-44d9-9f56-c0732306eec2@q27g2000prf.googlegroups.com> <13db98b5-ed2e-45ef-97ec-ad3caeeed10e@j1g2000prb.googlegroups.com> <074caf4a-de1e-4290-b688-30148786952c@z72g2000hsb.googlegroups.com> <776fd3e3-7c2e-45b1-8196-7cde93e72da3@w1g2000prd.googlegroups.com> Message-ID: <98d541c3-e974-4a8c-961c-2a59f6bf32ea@v26g2000prm.googlegroups.com> On Jun 11, 7:56 am, Fuzzyman wrote: > On Jun 11, 6:56 am, Rhamphoryncus wrote: > > > > > On Jun 10, 3:41 pm, Fuzzyman wrote: > > > > On Jun 10, 2:03 am, Rhamphoryncus wrote: > > > How does that protect code like this? > > > f = open('somefile', 'w') > > # interruption here > > try: > > ... > > finally: > > ... > > How does it *not* protect you if you write this instead: > > f = None > try: > f = open('somefile', 'w') > ... > finally: > if f is not None: > ... Yeah, that should be safe, so long as the open call itself is protected. > > > The calculation is 'coarse grained' (it can call into .NET APIs that > > > can take a relatively long time to return) - so polling for exit > > > wouldn't work anyway. We also run user code and can't expect their > > > code to poll for exit conditions. > > > Do those .NET get interrupted at arbitrary points? Is this > > "untrusted" user code also audited for correctness? (Although I'd bet > > you simply document what you do and blame the user if something > > breaks.) > > We don't audit our user code - of course. We do document and assist > them as necessary. Changing to a more restrictive model still wouldn't > meet our use case and put *more* of a burden on our users. > > Our situation is not the only one. In general there are situations > where you may want to put a long running calulcation on a background > thread and you *know* that it is safe to interrupt - but Python > currently won't let you. > > > I'm not saying it can't be made to work in your specific case - it > > likely does work well for you. I'm saying it can't work *in > > general*. Stretching it out for general use turns those little cracks > > into massive canyons. A language needs a general mechanism that does > > work - such as a polite cancellation API. > > Neither *works in general* - polite cancellation *doesn't* work for > our us. That's my point - you probably want *both* for different use > cases. :-) Yeah, but mine's less icky. ;) I think the ideal for you would be a separate process. I'd also suggest a restricted VM only in a thread, but that probably wouldn't work for those long-running .NET APIs. Now, if those long- running .NET APIs did polite cancellation, then you could combine that with a restricted VM to get what you need. I think what bothers me is, even if those external APIs support polite cancellation properly, your forced interruptions will bleed over and mess them up. There needs to be a way of containing it better. Writing them in another language (as C is used for most of Python's builtins today) isn't a reasonable requirement. From bborcic at gmail.com Mon Jun 23 05:39:44 2008 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 23 Jun 2008 11:39:44 +0200 Subject: listcomprehension, add elements? In-Reply-To: <510c6f38-24f8-431e-9b37-c70ed91b3ee2@z24g2000prf.googlegroups.com> References: <13452c64-ef91-49a2-bb73-7f33c088660e@d45g2000hsc.googlegroups.com> <7dc3d1d6-12d7-4a9e-ac7a-91406610e106@d19g2000prm.googlegroups.com> <510c6f38-24f8-431e-9b37-c70ed91b3ee2@z24g2000prf.googlegroups.com> Message-ID: John Machin wrote: > > Instead of sum(a + b for a, b in zip(foo, bar)) > why not use sum(foo) + sum(bar) > ? or even sum(foo+bar) as may apply. Cheers, BB From ptmcg at austin.rr.com Mon Jun 16 23:23:13 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 16 Jun 2008 20:23:13 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <4856e80c$0$30401$9b622d9e@news.freenet.de> Message-ID: <97b828d8-e64c-47db-8b8e-d403e8076756@x35g2000hsb.googlegroups.com> On Jun 16, 5:24?pm, "Martin v. L?wis" wrote: > > ? ? ``odict.byindex(index)`` > > > ? ? ? ? Index-based lookup is supported by ``byindex()`` which returns > > ? ? ? ? the key/value pair for an index, that is, the "position" of a > > ? ? ? ? key in the ordered dict. ?0 is the first key/value pair, -1 > > ? ? ? ? the last. > > > ? ? ? ? >>> d.byindex(2) > > ? ? ? ? ('foo', 'bar') > > For this API, I think it's important to make some performance > guarantees. It seems fairly difficult to make byindex O(1), and > simultaneously also make insertion/deletion better than O(n). > > IOW, the PEP should somehow specify which operations are efficient, > and which ones aren't. > > Regards, > Martin My guess is that the two main memory allocate/deallocate cases are 1) appending a new item to the end, and 2) GC'ing the entire data structure. I would optimize these 2 at the expense of all others. -- Paul From luislupe at gmail.com Sun Jun 15 17:59:17 2008 From: luislupe at gmail.com (luislupe at gmail.com) Date: Sun, 15 Jun 2008 14:59:17 -0700 (PDT) Subject: randrange loops References: <6e424f2a-872d-4dd1-b28d-cf2a985895c9@j22g2000hsf.googlegroups.com> Message-ID: <2ac304b0-cfac-4571-95b7-66bea1a22794@l42g2000hsc.googlegroups.com> On 15 Jun, 21:05, "Terry Reedy" wrote: > wrote in message > > news:6e424f2a-872d-4dd1-b28d-cf2a985895c9 at j22g2000hsf.googlegroups.com... > | Hi, > | > | > | I've created a method where the script defines twenty variables and > | several of them should be random having a maximum and a minimum value. > | > | What I did was this: > | > | from random import randrange as rr, random > | > | self.tr2_vezes = self.rr(self.d_tr2_vezes[0],self.d_tr2_vezes[-1], > | 1) # just an example, others are similar > > Are we to presume that self.rr is rr? > > | The minimum and maximum limits are never lower than -50 and higher > | than 250 and are integer. > | > | Many times, not always, the problem is that the script just loops > | forever and no value is chosen for the variable. > | > | What's happening here? What am I doing wrong? > > On what line does it 'loop forever'? > Are you saying that the same code with same input sometimes works and > sometimes does not? In any case, try to reduce it to the minumum that > either always or sometimes fails. And post that. > > tjr I tried to reproduce the error in a small script. Python's error message always returned this kind of error: Traceback (most recent call last): File "individuo.py", line 584, in ind.criarAleatorio() File "individuo.py", line 247, in criarAleatorio self.criarTr2_vezes() File "individuo.py", line 185, in criarTr2_vezes self.tr2_vezes = self.rr(self.d_tr2_vezes[0],self.d_tr2_vezes[-1], 1) File "/usr/lib/python2.5/random.py", line 158, in randrange istart = int(start) KeyboardInterrupt I got mislead by this. The loop was about a while statement that compared values from two of the random variables. It was a '>=' and it should be a '>'. Thank you for your messages. Luis From tdahsu at gmail.com Fri Jun 13 12:29:01 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Fri, 13 Jun 2008 09:29:01 -0700 (PDT) Subject: Iterate creating variables? References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> <6bfhj5F3b47fmU1@mid.uni-berlin.de> <6bfj7bF3c3npoU1@mid.uni-berlin.de> Message-ID: <417fa772-1d72-478c-b088-b062f415250c@f36g2000hsa.googlegroups.com> On Jun 13, 12:19?pm, Calvin Spealman wrote: > On Jun 13, 2008, at 11:56 AM, tda... at gmail.com wrote: > > > > > On Jun 13, 11:48 am, "Diez B. Roggisch" wrote: > >> tda... at gmail.com schrieb: > > >>> On Jun 13, 11:21 am, "Diez B. Roggisch" wrote: > >>>> tda... at gmail.com schrieb: > > >>>>> I have twenty-five checkboxes I need to create (don't ask): > >>>>> self.checkbox1 = ... > >>>>> self.checkbox2 = ... > >>>>> . > >>>>> . > >>>>> . > >>>>> self.checkbox25 = ... > >>>>> Right now, my code has 25 lines in it, one for each checkbox, ? > >>>>> since > >>>>> these are all variables. > >>>>> Is there a way to write a loop so that I can have fewer lines ? > >>>>> of code > >>>>> but still keep the variables? > >>>>> I've tried: > >>>>> for o in xrange(25): > >>>>> ? ? self.checkbox[o] = ... > >>>>> which didn't work, and > >>>>> for o in xrange(25): > >>>>> ? ? self.checkbox[''%d'%(o)] = ... > >>>>> which also didn't work. > >>>>> Both give the error message: "Attribute error: Main.App has no > >>>>> attribute "checkbox"", which clearly indicates that I'm not ? > >>>>> keeping > >>>>> the "variability" aspect I want. > >>>>> Is there a way? > >>>> Keep either a list or dictionary around. Like this: > > >>>> checkboxes = [] > > >>>> for o in xrange(25): > >>>> ? ? ?checkboxes.append(....create a checkbox...) > > >>>> self.checkboxes = checkboxes > > >>>> Diez > > >>> I don't understand... how do I then complete the assignment ? > >>> statement? > > >>> If I have: > > >>> self.checkbox1 = xrc.XRCCTRL(self.panel01, 'Checkbox1') > >>> . > >>> . > >>> . > >>> self.checkbox25 = xrc.XRCCTRL(self.panel01, 'Checkbox25') > > >>> using your method, wouldn't I still need to figure out my original > >>> question? > > >>> If I have a list of checkboxes, then I'll have: > > >>> checkboxes = [checkbox1, checkbox2 ... checkbox25] > > >>> in which case I'd still need to figure out how to get the ? > >>> variable at > >>> the end of checkbox to do the rest of the "=" statement. > > >> I don't fully understand that. But if your code is uniform and looks > >> like the above, it appears that > > >> for o in xrange(25): > >> ? ? ?checkboxes.append(xrc.XRCCTRL(self.panel01, 'Checkbox%i' % o)) > > >> is the way to go. > > >> Diez > > > Thank you, this is much closer to where I need to be... > > > The issue is (and this is the part that you don't know, because I > > didn't tell you!) is that I later need to call methods on > > "self.checkbox1", for instance: > > > self.checkbox1.GetValue() > > self.checkbox[1].GetValue() is only two more characters and more ? > readable, because it expresses that you have this list of checkboxes, ? > where as "self.checkbox1" could be an odd name and all on its own, no ? > others at all, etc. > > Variable variable names are a good thing to avoid. Thats why we have ? > containers. > > > > > to determine if the box is checked or not. > > > I should have included that piece in the initial problem description; > > my apologies. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I don't think I'm being clear enough. Thanks to everyone for their help. From robin at alldunn.com Wed Jun 25 16:00:16 2008 From: robin at alldunn.com (Robin Dunn) Date: Wed, 25 Jun 2008 13:00:16 -0700 Subject: [wxpython-users] ANN: wxPython 2.8.8.0 In-Reply-To: <771741b20806251251m2345486ek7121533bdddae778@mail.gmail.com> References: <48629A74.2030109@alldunn.com> <771741b20806251251m2345486ek7121533bdddae778@mail.gmail.com> Message-ID: <4862A3D0.6010600@alldunn.com> Mario Lacunza wrote: > Hello Robin, > > Are available repos for Ubuntu Hardy?? Not yet. I hope to get set up for a Hardy build in the next few days, but you may be able to use the gutsy packages in the meantime. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From dan at catfolks.net Tue Jun 3 14:38:09 2008 From: dan at catfolks.net (Daniel Mahoney) Date: Tue, 03 Jun 2008 13:38:09 -0500 Subject: Handling some isolated iso-8859-1 characters Message-ID: I'm working on an app that's processing Usenet messages. I'm making a connection to my NNTP feed and grabbing the headers for the groups I'm interested in, saving the info to disk, and doing some post-processing. I'm finding a few bizarre characters and I'm not sure how to handle them pythonically. One of the lines I'm finding this problem with contains: 137050 Cleo and I have an anouncement! "Mlle. =?iso-8859-1?Q?Ana=EFs?=" Sun, 21 Nov 2004 16:21:50 -0500 4478 69 Xref: sn-us rec.pets.cats.community:137050 The interesting patch is the string that reads "=?iso-8859-1?Q?Ana=EFs?=". An HTML rendering of what this string should look would be "Anaïs". What I'm doing now is a brute-force substitution from the version in the file to the HTML version. That's ugly. What's a better way to translate that string? Or is my problem that I'm grabbing the headers from the NNTP server incorrectly? From deets at nospam.web.de Thu Jun 12 10:02:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 12 Jun 2008 16:02:19 +0200 Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> Message-ID: <6bcokhF3b2mo7U1@mid.uni-berlin.de> Mark wrote: > Hi all, > > I have a scenario where I have a list like this: > > User Score > 1 0 > 1 1 > 1 5 > 2 3 > 2 1 > 3 2 > 4 3 > 4 3 > 4 2 > > And I need to add up the score for each user to get something like > this: > > User Score > 1 6 > 2 4 > 3 2 > 4 8 > > Is this possible? If so, how can I do it? I've tried looping through > the arrays and not had much luck so far. > > Any help much appreciated, Show us your efforts in code so far. Especially what the actual data looks like. Then we can suggest a solution. Diez From google at mrabarnett.plus.com Wed Jun 11 04:32:52 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 11 Jun 2008 01:32:52 -0700 (PDT) Subject: can't assign to literal References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> Message-ID: <1a244dc4-4d10-491d-8ec7-224f3a1f0df5@m73g2000hsh.googlegroups.com> On Jun 10, 10:57 pm, "Steven Clark" wrote: > > for 1 in oids, vals head_oids: > > SyntaxError: can't assign to literal > > -- > > 1 is a literal, you can't assign it to something. Are you trying to > use it as a variable name? Slightly OT, but is there an editor that can display digits in a different colour to letters? From none at this.time Mon Jun 2 10:48:10 2008 From: none at this.time (The Pythonista) Date: Mon, 02 Jun 2008 10:48:10 -0400 Subject: Greetings, fellow Pythonistas! Message-ID: <13328$4844082a$30292@news.teranews.com> Hello, all! This post is to announce a new Python-oriented blog. See my .sig for the URL. I also have a question: is there any "official" method for getting listed on Planet Python? Thanks! A fellow Pythonista -- code.py: A blog about life, the universe, and Python http://pythonista.wordpress.com ** Posted from http://www.teranews.com ** From spectrumdt at gmail.com Wed Jun 4 12:12:18 2008 From: spectrumdt at gmail.com (spectrumdt at gmail.com) Date: Wed, 4 Jun 2008 09:12:18 -0700 (PDT) Subject: Extending Python with C: Can I specify another C compiler? Message-ID: <625c63a6-8f71-48db-9f6a-e3f43b487472@56g2000hsm.googlegroups.com> Hello. I am trying to extend my Python program with some C code. This thread is sort of a follow-up to another thread of mine, linked below. I don't know what the conventions are in this newsgroup about creating new threads vs. staying in existing ones, but I figured I'd rather make a new one with a title pertaining to my current problem. http://groups.google.com/group/comp.lang.python/browse_thread/thread/d60449f4db19f731# Anyway, my question is this: When compiling my C code to include in Python, using a Python script with the function distutils.core.setup... can I choose which C compiler to use? On my system it defaults to gcc, but I would like to use mpicc instead (C compiler for MPI, Message Passing Interface). Can I do this? My system, in case it matters, is Fedora Linux. Thanks in advance. From martin at v.loewis.de Tue Jun 17 01:33:55 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 17 Jun 2008 07:33:55 +0200 Subject: Python GC does not work as it should be In-Reply-To: References: Message-ID: <48574cc3$0$9714$9b622d9e@news.freenet.de> > Yes I did my job, i had mention it before. but an application would not > consist mine only, it could be incorporate your c extension module(s), and > others, means problem could be from my side, yours, or others. Though > forcing to reset the state would not mean fixing the real problem, but > making sure the GC would always try to do its job is important as python > itself used as an integrator engine no matter whether it succeed or not. Python does not support the Microsoft structured exceptions at all, and there is nothing that can be done about it. There are many many many places in the that would work incorrectly if a structured exception occurred, including many which lead to significant memory leaks or completely block the interpreter (as it won't return the GIL. That it can also happen in GC is just a tiny detail of the problem. If you think you absolutely need to have that work, just change the code and use a modified Python DLL. Regards, Martin From metalkeys404 at gmail.com Thu Jun 26 13:07:36 2008 From: metalkeys404 at gmail.com (Ampedesign) Date: Thu, 26 Jun 2008 10:07:36 -0700 (PDT) Subject: I Need A Placeholder References: Message-ID: <8c4665a8-7f47-4657-8621-38aafc0ea4d7@q24g2000prf.googlegroups.com> On Jun 26, 10:06?am, Daniel Mahoney wrote: > On Thu, 26 Jun 2008 10:03:47 -0700, Ampedesign wrote: > > I'm trying to build a try/except case, and I want to have the except > > function like such: > > > try: > > ? ? ? # Do some code here > > ? ? ? var = 1 ? ? ? ? # For example > > except: > > ? ? ? #Do nothing here > > > The only problem is if I leave a comment only in the except block, I > > get an error back saying that the except block is not properly > > formatted, since it has no content other than a comment. > > > So if anyone could suggest some code to put there as a placeholder > > that would be wonderful. > > "pass" would work fine. > > try: > ? ? ?# Do something that can throw an exception > except: > ? ? ?pass Thanks. That will work perfectly. From lawtonpaul at gmail.com Mon Jun 16 20:55:10 2008 From: lawtonpaul at gmail.com (takayuki) Date: Mon, 16 Jun 2008 17:55:10 -0700 (PDT) Subject: newbie question: for loop within for loop confusion References: <7504caa1-7941-4166-a46c-fd192cbf0d01@i76g2000hsf.googlegroups.com> Message-ID: <2b1a834f-d7d8-4a55-8e3e-65f7add59460@v1g2000pra.googlegroups.com> On Jun 17, 6:34 am, Thomas Hill wrote: > On Jun 15, 6:23 pm, takayuki wrote: > > > def hasnolet(avoid): > > fin = open('animals.txt') > > for line in fin: > > word = line.strip() > > for letter in avoid: > > if letter in word: > > break > > else: > > print word > > You're using the split command correctly, but you're not filtering > correctly. Consider this: > > ---begin--- > fin = open('animals.txt') > "\n".join(["%s" % line for line in fin if len(line.strip('abcd')) == > len(line)]) > ----end---- > > Let's go slow. > > "\n".join([...]) > > 1. Take everything that is in the following list, and print each one > with a carriage return appended to it. > > "\n".join(["%s" % line for line in fin ...]) > > 2. For each line in fin, create a string that only consists of what > currently in the line variable, using string substitution. > > "\n".join(["%s" % line for line in fin if len(line.strip('abcd')) == > len(line)]) > > 3. Only do #2 if the length of the line after stripping out the > unnecessary characters is the same length as the line originally. This > way we filter out the lines we don't want. If we wanted the lines that > have been filtered, we can change "==" to "!=" or "<=". > > Now, I read "Dive Into Python" first, which through these early on in > the book. If your eyes cross looking at this, write it down and read > it again after you get a little farther into the book you're reading Thomas, thanks for the reply. I'm early on in my python adventure so I'm not there yet on the strip command nuances. I'm reading "How to think like a python programmer" first. It's great. Then "Learning python". I've read parts of Dive into Python and will work through it fully when I'm a little farther along. takayuki From pcdhSpamMeSenseless at electrooptical.net Tue Jun 17 08:13:40 2008 From: pcdhSpamMeSenseless at electrooptical.net (Phil Hobbs) Date: Tue, 17 Jun 2008 08:13:40 -0400 Subject: 32 bit or 64 bit? In-Reply-To: <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> Message-ID: <4857AA74.2080205@electrooptical.net> ram.rachum at gmail.com wrote: > On Jun 15, 7:43 pm, Peter Otten <__pete... at web.de> wrote: >> ram.rac... at gmail.com wrote: >>> On Jun 15, 6:58 pm, Christian Meesters wrote: >>>>> I do need speed. Is there an option? >>>> Mind telling us what you *actually* want to achieve? (What do you want to >>>> calculate?) >>>> Christian >>> Physical simulations of objects with near-lightspeed velocity. >> How did you determine that standard python floats are not good enough? > > I have a physical system set up in which a body is supposed to > accelerate and to get very close to lightspeed, while never really > attaining it. After approx. 680 seconds, Python gets stuck and tells > me the object has passed lightspeed. I put the same equations in > Mathematica, again I get the same mistake around 680 seconds. So I > think, I have a problem with my model! Then I pump up the > WorkingPrecision in Mathematica to about 10. I run the same equations > again, and it works! At least for the first 10,000 seconds, the object > does not pass lightspeed. > I concluded that I need Python to work at a higher precision. > >> Everything beyond that is unlikely to be supported by the hardware and will >> therefore introduce a speed penalty. >> > > I have thought of that as well. However I have no choice. I must do > these calculations. If you know of any way that is supported by the > hardware, it will be terrific, but for now the slower things will have > to do. You need to change your representation. Try redoing the algebra using (c-v) as the independent variable, and calculate that. Cheers, Phil Hobbs From gherron at islandtraining.com Thu Jun 26 13:07:46 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 26 Jun 2008 10:07:46 -0700 Subject: I Need A Placeholder In-Reply-To: References: Message-ID: <4863CCE2.10801@islandtraining.com> Ampedesign wrote: > I'm trying to build a try/except case, and I want to have the except > function like such: > > try: > # Do some code here > var = 1 # For example > except: > #Do nothing here > > try: # Do some code here var = 1 # For example except: pass Gary Herron > The only problem is if I leave a comment only in the except block, I > get an error back saying that the except block is not properly > formatted, since it has no content other than a comment. > > So if anyone could suggest some code to put there as a placeholder > that would be wonderful. > -- > http://mail.python.org/mailman/listinfo/python-list > From jason.scheirer at gmail.com Fri Jun 13 15:29:09 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Fri, 13 Jun 2008 12:29:09 -0700 (PDT) Subject: Iterate creating variables? References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> Message-ID: <6b671d56-1060-4fd4-86ca-b36a1e4c936f@m44g2000hsc.googlegroups.com> On Jun 13, 8:11?am, tda... at gmail.com wrote: > I have twenty-five checkboxes I need to create (don't ask): > > self.checkbox1 = ... > self.checkbox2 = ... > . > . > . > self.checkbox25 = ... > > Right now, my code has 25 lines in it, one for each checkbox, since > these are all variables. > > Is there a way to write a loop so that I can have fewer lines of code > but still keep the variables? > > I've tried: > > for o in xrange(25): > ? ? self.checkbox[o] = ... > > which didn't work, and > > for o in xrange(25): > ? ? self.checkbox[''%d'%(o)] = ... > > which also didn't work. > > Both give the error message: "Attribute error: Main.App has no > attribute "checkbox"", which clearly indicates that I'm not keeping > the "variability" aspect I want. > > Is there a way? > > I appreciate any and all answers! > > Thanks! for x in xrange(1, 26): setattr(self, 'checkbox_%i' % x, ...) From python at rcn.com Fri Jun 20 09:36:48 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 20 Jun 2008 06:36:48 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> Message-ID: On Jun 20, 5:03?am, eliben wrote: > I've rewritten it using a dynamically generated procedure > for each field, that does hard coded access to its data. For example: > > def get_counter(packet): > ? data = packet[2:6] > ? data.reverse() > ? return data > > This gave me a huge speedup, because each field now had its specific > function sitting in a dict that quickly extracted the field's data > from a given packet. > > Now I'm rewriting this program in Python and am wondering about the > idiomatic way to use exec (in Perl, eval() replaces both eval and exec > of Python). FWIW, when I had a similar challenge for dynamic coding, I just generated a py file and then imported it. This technique was nice because can also work with Pyrex or Psyco. Also, the code above can be simplified to: get_counter = lambda packet: packet[5:1:-1] Since function calls are expensive in python, you can also gain speed by parsing multiple fields at a time: header, timetag, counter = parse(packet) Raymond From kamhung.soh at gmail.com Tue Jun 10 00:34:01 2008 From: kamhung.soh at gmail.com (Kam-Hung Soh) Date: Tue, 10 Jun 2008 14:34:01 +1000 Subject: Separators inside a var name In-Reply-To: References: Message-ID: Rainy wrote: > I have a stylistic question. In most languages words in var. name are > separated by underscores or cap letters, resulting in var names like > var_name, VarName and varName. I don't like that very much because all > 3 ways of naming look bad and/or hard to type. From what I understand, > scheme can have variables like var-name. I'm curious about reasons > that python chose to disallow this. Another question I have is what > other languages allow this naming scheme? Were there any languages > that allowed space as a separator? What would be a practical way to > separate variables from keywords in that case? "some long variable > name", 'just a string', or maybe using 2 spaces: one var + other > var + third var ? I think being able to easy have very long names > for vars that are easy to type would be a fairly significant > advantage. I know I'm probably being too obsessive about this, but > that didn't stop me from posting. Comments? > -- > http://mail.python.org/mailman/listinfo/python-list > Groovy allows spaces in method names. See following request and thread: http://jira.codehaus.org/browse/GROOVY-2857 -- Kam-Hung Soh Software Salariman From jarausch at igpm.rwth-aachen.de Mon Jun 23 04:50:44 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Mon, 23 Jun 2008 10:50:44 +0200 Subject: [2to3] Bug converting import Message-ID: <6c96f5F3eb8hnU1@mid.dfncis.de> Hi Given the following two files in the same directory Master.py: ---------- #!/usr/bin/python import Slave Slave.main() and Slave.py: --------- def main() : print "Hello World" Invoking Master.py under python-2.5.2 works just fine. 2to3 converts these to Master.py: ---------- from . import Slave Slave.main() I have added the first line #!/usr/local/bin/python3.0 manually Slave.py: --------- def main() : print("Hello World") Now, when I invoke Master.py I get Traceback (most recent call last): File "Master.py", line 2, in from . import Slave ValueError: Attempted relative import in non-package thanks for looking into it, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From bruno.42.desthuilliers at websiteburo.invalid Wed Jun 25 11:11:47 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 25 Jun 2008 17:11:47 +0200 Subject: IDE on the level of Eclipse or DEVc++? In-Reply-To: References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> <486214ae$0$9742$426a34cc@news.free.fr> <87ej6lq02c.fsf@benfinney.id.au> Message-ID: <48626033$0$1295$426a74cc@news.free.fr> cokofreedom at gmail.com a ?crit : > On Jun 25, 12:38 pm, Jorge Godoy wrote: >> Ben Finney wrote: >>> Bruno Desthuilliers writes: >>>> If you're into clickodroms, you may want to have a look at Eric too. >>>> As far as i'm concerned, I still wait for something that would be >>>> worth dropping emacs + python-mode + ecb. >>> I'm having the most success with this combination, yes. Though ecb is >>> rather non-Emacs-like in its configuration, and seems to strongly >>> expect to be run in graphical mode, it is still very powerful. >> Heh... I'm another one that keeps trying new things but comes back to Emacs all the time. >> >> Eclipse is too heavy, NetBeans has a poor support, Eric is too "mousy"... >> >> -- >> Jorge Godoy > > How is emacs on a windows platform? err... alien ?-) From johnjsal at NOSPAMgmail.com Wed Jun 18 09:56:29 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 18 Jun 2008 09:56:29 -0400 Subject: Buffer size when receiving data through a socket? References: <20080616202135.41c407de.johnjsal@NOSPAMgmail.com> <03985958$0$8452$c3e8da3@news.astraweb.com> Message-ID: <485913ac$0$28627$c3e8da3@news.astraweb.com> "Dennis Lee Bieber" wrote in message news:vrudnYYHF6EnLcXVnZ2dnUVZ_oPinZ2d at earthlink.com... > The first if is checking for lack of interactive input -- and, as > coded, will never break out as ANY response to the > prompt will have a > newline attached. > > Try with raw_input("> ").strip() instead Well, I know the first if block works properly. Pressing just ENTER will exit the loop and close the client socket. > The second if is checking for empty receive block... And since > .recv() blocks until it has something to return (as I recall) it may not > be of use... Interesting point. I'm not sure if it works that way though. I *think* I tried sending an empty string from the server back to the client, and as expected it exited the loop and closed the client, which doesn't make sense to me, since an empty string could be perfectly valid return data. I opted to remove the second if statement and see where that takes me. :) From robert.kern at gmail.com Thu Jun 12 16:48:37 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 12 Jun 2008 15:48:37 -0500 Subject: Mapping None. Why? In-Reply-To: References: Message-ID: Paddy wrote: > On looking up map on Wikipedia there is no mention of this special > behaviour, > So my question is why? My question is why you are looking up the semantics of Python functions on Wikipedia instead of the Python documentation. I don't see any particular discussion of map() there at all. Am I missing something? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mishok13 at gmail.com Tue Jun 3 17:35:46 2008 From: mishok13 at gmail.com (Andrii V. Mishkovskyi) Date: Wed, 4 Jun 2008 00:35:46 +0300 Subject: Ideas for master's thesis In-Reply-To: References: Message-ID: <192840a00806031435r2a682079s6d83dc8e835d90a8@mail.gmail.com> 2008/6/4 Larry Bugbee : >> I would like to do something with this language, yet >> I don't know if there are any needs/science fields, that could be used >> as a basis for a thesis. > > Personally, I'd like to see *optional* data typing added to Python > perhaps along the lines of what was done in Pyrex. You declare the > data type when you know it, or when it matters, and skip it > otherwise. Your paper could analyze its pros and cons, analyze any > potential performance gains, and recommend how to implement it. Your > professor will suggest some additional questions. > > I suspect, if the type be known and declared, the interpreter could be > streamlined and quicker, you might get asserts for free, and perhaps, > Python becomes even more self-documenting. Perhaps I've missed it, > but I haven't seen a strong analytical case made for or against > optional data typing. Your paper? I think what you are talking about is already implemented in Python 3.0 as annotations. Forgive me if I missed your point. > > Larry > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Wbr, Andrii Mishkovskyi. He's got a heart of a little child, and he keeps it in a jar on his desk. From tjreedy at udel.edu Fri Jun 13 18:03:26 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 13 Jun 2008 18:03:26 -0400 Subject: why can i still able to reproduce the SimpleHTTPServer bug whichis said fixed 3 years ago? References: <4e307e0f0806130002u6795c55ejce02b71753df33ae@mail.gmail.com> Message-ID: "Gabriel Genellina" wrote in message news:op.ucokc3o6x6zn5v at gabriel2.softlabbsas.com.ar... En Fri, 13 Jun 2008 04:02:48 -0300, Leo Jay escribi?: > http://bugs.python.org/issue1097597 > > in my python 2.5.2, i still find these code in SimpleHTTPServer.py, > is that deliberate? According to http://bugs.python.org/issue839496 it should have been corrected, but apparently the patch was only applied to the 2.4 maintenance branch, not to the trunk. Both 2.5 and 2.6 have the same problem. 3.0 doesn't have this problem but probably it was fixed independently. =========================== I reopened this so it will appear on the weekly bug report, in case the original committer does not see it. From Gilles at Wed Jun 4 12:26:35 2008 From: Gilles at (nospam@nospam.com) Date: Wed, 04 Jun 2008 18:26:35 +0200 Subject: [XP] Batch-print bunch of RTF files? Message-ID: Hello, I have about two hundred individual RTF files to print from an XP host. Word 2000 doesn't seem to have this feature, so I'm looking for a way to print those RTF files from an ActivePython script. Would someone have some working code handy? Thank you. From fabiofz at gmail.com Thu Jun 19 12:11:06 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Thu, 19 Jun 2008 13:11:06 -0300 Subject: Pydev 1.3.18 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.18 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Auto-import: Groups imports when possible. * Auto-import: Doesn't bring imports for completions already in the document even if a parse is not successful. * Organize Imports (ctrl+shift+O): Suggests imports to the undefined tokens in the editor. * Import quick-fix: Icons correspondent to the element being imported. Release Highlights in Pydev: ---------------------------------------------- * Executing external programs: Using Runtime.exec(String[] cmdargs) instead of a string with the generated command (fixes problems regarding having spaces in the installation). * Organize Imports (ctrl+shift+O): Imports can be grouped. * Cygwin: sys.executable in cygwin was not returning '.exe' in the end of the executable as it should. * Additional paths for PYTHONPATH (Patch from Eric Wittmann): extension point allows plugins to contribute paths to the PYTHONPATH. * Code-completion: typing '.' won't apply the selected completion, but will still request a new one with the current contents. * Pydev Package Explorer: Problem while trying to show active editor on the pydev package explorer. What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com From gagsl-py2 at yahoo.com.ar Mon Jun 16 01:02:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 16 Jun 2008 02:02:28 -0300 Subject: A package import question References: <15e4667e0806131601r14759c54jac431a8fc531414d@mail.gmail.com> <15e4667e0806131838p7258b00by66db0fe8393ddfa5@mail.gmail.com> Message-ID: En Fri, 13 Jun 2008 22:38:24 -0300, Dan Yamins escribi?: >> Gabriel, thanks. I understood about the fact that import only loads the > first time, but didn't realize that "del" only removes the bound reference > to the object, not as I had hoped the thing from the namespace itself. > > Also, I did _try_ to use reload. however, that failed since .archive was no > longer an attribute associated with Operations: > > >>> import Operations.archive > >>> del Operations.archive > >>> reload(Operations.archive) > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'archive' I don't get *why* do you want to remove the 'archive' attribute before reloading the module. Just reload it *without* using `del` previously. > It seems unfortunately that the "del" operation on the one hand doesn't > really remove the .archive from memory but just it's bound name, but > nonetheless prevents me from reloading the object kept in memory. > > I guess I'm trying to find a clean way to remove all the attributes > associated with a module when I reload it. Is there any way to do this? > (The operation of recursively searching through the attributes of the module > and deleting those first seems to be bad since when I did that and then try > to _reload_ the module, the attributes I deleted are _not_ reloaded.) When you reload a module, new definitions for existing names replace the old objects; new names are added; old names without a new value keep the previous value. (That is, objects are *replaced* and *added* but not *removed*). Isn't it enough? Or do you actually want to be sure that old names, now unused, are no longer available? -- Gabriel Genellina From __peter__ at web.de Thu Jun 26 05:40:49 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 26 Jun 2008 11:40:49 +0200 Subject: Looping-related Memory Leak References: <94312edc-babb-4c1b-8db1-233404aa4a02@i76g2000hsf.googlegroups.com> Message-ID: Tom Davis wrote: > I am having a problem where a long-running function will cause a > memory leak / balloon for reasons I cannot figure out. Essentially, I > loop through a directory of pickled files, load them, and run some > other functions on them. In every case, each function uses only local > variables and I even made sure to use `del` on each variable at the > end of the loop. However, as the loop progresses the amount of memory > used steadily increases. > > I had a related problem before where I would loop through a very large > data-set of files and cache objects that were used to parse or > otherwise operate on different files in the data-set. Once again, > only local variables were used in the cached object's methods. After > a while it got to the point where simply running these methods on the > data took so long that I had to terminate the process (think, first > iteration .01sec, 1000th iteration 10sec). The solution I found was > to cause the cached objects to become "stale" after a certain number > of uses and be deleted and re-instantiated. Here the alleged "memory leak" is clearly the cache, and the slowdown is caused by garbage collector. The solution is to turn it off with gc.disable() during phases where your programm allocates huge amounts of objects with the intent of keeping them for a longer time. > However, in the current case, there is no caching being done at all. > Only local variables are involved. It would seem that over time > objects take up more memory even when there are no attributes being > added to them or altered. Has anyone experienced similar anomalies? > Is this behavior to be expected for some other reason? If not, is > there a common fix for it, i.e. manual GC or something? Unless you post a script demonstrating the leak I will assume you are overlooking a reference that keeps your data alive -- whether it's a true global or within a long-running function doesn't really matter. Peter From tomkur2006-takehome at yahoo.com Fri Jun 27 21:17:22 2008 From: tomkur2006-takehome at yahoo.com (tom) Date: Fri, 27 Jun 2008 18:17:22 -0700 (PDT) Subject: httplib HTTP: Logging request message Message-ID: <57053381-d73a-4099-af6b-da672b8718be@i36g2000prf.googlegroups.com> With module httplid, I can do conn.request("POST", "/target", params, headers) Now, I want to log the request message that is sent by the request method. I don't don't see a method for that task. Any suggestion? For a response, I can log the response message by using the call method. Though, I have to get rid of the extra strings "replay: " and "header: ". data = response.read() print data /***what the print call will output***/ reply: 'HTTP/1.0 204 \r\n' header: Content-Length: 0 From byte8bits at gmail.com Wed Jun 18 10:28:38 2008 From: byte8bits at gmail.com (brad) Date: Wed, 18 Jun 2008 10:28:38 -0400 Subject: Looking for lots of words in lots of files Message-ID: Just wondering if anyone has ever solved this efficiently... not looking for specific solutions tho... just ideas. I have one thousand words and one thousand files. I need to read the files to see if some of the words are in the files. I can stop reading a file once I find 10 of the words in it. It's easy for me to do this with a few dozen words, but a thousand words is too large for an RE and too inefficient to loop, etc. Any suggestions? Thanks From martin at v.loewis.de Mon Jun 16 18:24:12 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 17 Jun 2008 00:24:12 +0200 Subject: PEP 372 -- Adding an ordered directory to collections In-Reply-To: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> Message-ID: <4856e80c$0$30401$9b622d9e@news.freenet.de> > ``odict.byindex(index)`` > > Index-based lookup is supported by ``byindex()`` which returns > the key/value pair for an index, that is, the "position" of a > key in the ordered dict. 0 is the first key/value pair, -1 > the last. > > >>> d.byindex(2) > ('foo', 'bar') For this API, I think it's important to make some performance guarantees. It seems fairly difficult to make byindex O(1), and simultaneously also make insertion/deletion better than O(n). IOW, the PEP should somehow specify which operations are efficient, and which ones aren't. Regards, Martin From sjmachin at lexicon.net Sun Jun 15 18:25:57 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 15 Jun 2008 15:25:57 -0700 (PDT) Subject: Hard to understand 'eval' References: <485381e7_2@news.tm.net.my> <4854e4a7_2@news.tm.net.my> <0eSdnazUa_iJGcjVnZ2dnUVZ_jadnZ2d@earthlink.com> Message-ID: <4c82ca10-ce6e-4f04-93df-00e57fb8e1c3@g16g2000pri.googlegroups.com> On Jun 16, 7:05 am, Dennis Lee Bieber wrote: > On Sun, 15 Jun 2008 17:45:12 +0800, TheSaint > declaimed the following in comp.lang.python: > > > is it an if....elif....elif probing only the first matching case and drop the > > remaining checks? > > Unless the compile/interpret pass is very unoptimized, once a branch > has been taken, the others should be totally skipped. > Don't you mean "Unless the "compile/interpret pass is VERY VERY BROKEN", as in "omits to drop in a jump to the end of the 'if' statement after each chunk of action code"? From dyamins at gmail.com Tue Jun 17 18:21:50 2008 From: dyamins at gmail.com (Dan Yamins) Date: Tue, 17 Jun 2008 18:21:50 -0400 Subject: Execfile issue Message-ID: <15e4667e0806171521p57eb7834r80e9e25afd0e84c2@mail.gmail.com> I'm having (what I assume is) a simple problem regarding the way import and execfile interact. I apologize in advance for my naivete. Lets say I have the function: def Func1(): print dir() execfile('testfile') print dir() X and the file #file: testfile X = 3 Then, when I run Func1 , I get the output: >>> Func1() [] ['X'] Traceback (most recent call last): File "", line 1, in File "", line 5, in Func1 NameError: global name 'X' is not defined SO, I have three questions: 1) Naively, I would think that the call to "execfile" in Func1 would act as if the line was replaced with the lines of 'testfile'. But obviously not, in some way that has to do with the subtlety of the python compilation process. Can someone explain exactly what the problem is? 2) Why would something show up in the dir() call, but not be defined (e.g. like 'X' did in the second dir() call in Func1()) ? 3) Is there any way to fix this that does not involved (essentially in one way or another) importing "testfile" as a py module? I would like to avoid that scenario for a variety of reasons ... Thanks! Dan -------------- next part -------------- An HTML attachment was scrubbed... URL: From subhabrata.iisc at hotmail.com Fri Jun 27 07:22:57 2008 From: subhabrata.iisc at hotmail.com (subhabrata.iisc at hotmail.com) Date: Fri, 27 Jun 2008 04:22:57 -0700 (PDT) Subject: Question on List References: <7f03fa3f-c8fd-45a8-b4a5-d7c66982aa4a@q27g2000prf.googlegroups.com> <8131e1be-a767-42c0-9409-b7353c7466ab@y38g2000hsy.googlegroups.com> Message-ID: <60e130f4-edea-49fa-9193-7c739ae90afe@g16g2000pri.googlegroups.com> Hi Chris, I solved the problem some other way round but thanx for your suggestion, I'll review it also. Best Regards, Subhabrata. Chris wrote: > On Jun 27, 9:51?am, subhabrata.i... at hotmail.com wrote: > > Dear All, > > I am trying to write the following code: > > > > def try1(n): > > ? ? ? ? a1="God Godess Borother Sister Family" > > ? ? ? ? a2=a1.split() > > ? ? ? ? a3=raw_input("PRINT A WORD") > > ? ? ? ? a4=a1.find(a3) > > ? ? ? ? print a4 > > ? ? ? ? a5=[] > > ? ? ? ? if a4>0: > > ? ? ? ? ? ? ? ? a5=a2.index(a3) > > ? ? ? ? ? ? ? ? a6=a5+1 > > ? ? ? ? ? ? ? ? a7=a2[a6] > > ? ? ? ? ? ? ? ? print "The new word is" > > ? ? ? ? ? ? ? ? print a7 > > ? ? ? ? ? ? ? ? a8=a5.append(a7) > > ? ? ? ? ? ? ? ? print a5 > > ? ? ? ? elif a4<0: > > ? ? ? ? ? ? ? ? a11=a3 > > ? ? ? ? ? ? ? ? print "The word is not availiable in String" > > ? ? ? ? ? ? ? ? print a11 > > ? ? ? ? ? ? ? ? a6=a5.append(a11) > > ? ? ? ? ? ? ? ? print a5 > > ? ? ? ? else: > > ? ? ? ? ? ? ? ? print "Error" > > > > Now, my question is I like to see a5 or the empty list as appended > > with elements. Results I am getting is a5 giving single value like > > ['God'],['Godess']... but I like to see it as ['God','Godess'...] etc. > > Am I going wrong? > > Do I have to rethink it in some other way? > > If any one can kindly let me know. > > Best Regards, > > Subhabrata. > > First notes, the string .find() method return -1 for not found and > zero or above if the search string is present. Remember you count > from zero. Secondly, list .append() methods do not return a new list > but modify the list in place. Thirdly, the .index() method of a list > requires an integer and not a string. And lastly, indentation should > be 4 spaces not 8. > > Just doing a sloppy job on the code (and my interpretation of what you > wanted) > > def try1(n): > new_list = [] > input_string="God Godess Borother Sister Family" > while n: > user_selection=raw_input("PRINT A WORD") > if input_string.find(user_selection) > -1: > s = input_string.split() > i = [i for i,j in enumerate(s) if j == user_selection] > new_word = s[i+1] > print 'The new word is %s' % new_word > new_list.append(new_word) > print new_list > else: > print 'User selection of "%s" not in the string.' % > user_selection > new_list.append(user_selection) > print new_list > n -= 1 > > Obviously I'm going to assume that the code you posted excluded your > loop control for the "try n amount of times". What was most likely > the cause is that you loop through your structure for every attempt of > the n times but each time you reset your list when you re-create it. > > Hope that helps some. > Chris From wolfgang.grafen at ericsson.com Mon Jun 16 05:25:50 2008 From: wolfgang.grafen at ericsson.com (Wolfgang Grafen) Date: Mon, 16 Jun 2008 11:25:50 +0200 Subject: PEP 372 -- Adding an ordered directory to collections In-Reply-To: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> Message-ID: <4856319E.9050006@ericsson.com> Armin Ronacher schrieb: > Other implementations of ordered dicts in various Python projects or > standalone libraries, that inspired the API proposed here, are: > > - `odict in Babel`_ > - `OrderedDict in Django`_ > - `The odict module`_ > - `ordereddict`_ (a C implementation of the odict module) > - `StableDict`_ > - `Armin Rigo's OrderedDict`_ > > > .. _odict in Babel: http://babel.edgewall.org/browser/trunk/babel/util.py?rev=374#L178 > .. _OrderedDict in Django: > http://code.djangoproject.com/browser/django/trunk/django/utils/datastructures.py?rev=7140#L53 > .. _The odict module: http://www.voidspace.org.uk/python/odict.html > .. _ordereddict: http://www.xs4all.nl/~anthon/Python/ordereddict/ > .. _StableDict: http://pypi.python.org/pypi/StableDict/0.2 > .. _Armin Rigo's OrderedDict: http://codespeak.net/svn/user/arigo/hack/pyfuse/OrderedDict.py I want add to this list my seqdict package, maybe the first implementation of an ordered dict in Python? http://home.arcor.de/wolfgang.grafen/Python/Modules/Modules.html I have never seen a real world dictionary which wasn't in order, so I ever felt the Python dictionary was not complete. I support the idea of an ordered dictionary in Python. Best regards Wolfgang From pavlovevidence at gmail.com Sat Jun 28 19:09:40 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 28 Jun 2008 16:09:40 -0700 (PDT) Subject: Pygame, how to show window without loop? no loop=popupand close... References: <8ecb6375-356a-4e73-be21-18ffe0f5c4f2@r66g2000hsg.googlegroups.com> <4d886194-7afb-46ff-8731-52cc82ad38d5@m45g2000hsb.googlegroups.com> <062d0d88-4f22-4a50-8cf4-411b629f4fb0@m45g2000hsb.googlegroups.com> Message-ID: <433841b8-ec5e-47aa-99de-3cc7ee0b3f83@y21g2000hsf.googlegroups.com> On Jun 28, 6:49 pm, defn noob wrote: > On 28 Juni, 08:32, Carl Banks wrote: > > > On Jun 27, 10:58 pm, defn noob wrote: > > > > right. im an idiot anyway. i can just draw the lines before entering > > > the loop, problem solved... > > > Do not do that; it'll create a busy loop and use 100% of CPU. Use > > pygame.event.wait() instead. It waits for an event to occur, without > > using CPU cycles. > > > Carl Banks > > pygame.init() > screen = pygame.display.set_mode(size) > > while 1: > for event in pygame.event.get(): > if event.type == pygame.QUIT: sys.exit() > screen.fill(screencolor) > draw((500, 20), 5) > pygame.display.flip() > pygame.event.wait() > > running that i cant close the program... what must i do? create an > event at mouse click? A. pygame.event.wait is used in lieu of pygame.event.get B. RTFM. I suggested pygame.event.wait with the expectation that you would refer to the pygame documentation to learn how to use it yourself. Carl Banks From mnordhoff at mattnordhoff.com Thu Jun 19 18:37:09 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 19 Jun 2008 22:37:09 +0000 Subject: Simple Class/Variable passing question In-Reply-To: <8a0cb1c6-8b54-4123-8f94-c0e0d465a1e9@e39g2000hsf.googlegroups.com> References: <8a0cb1c6-8b54-4123-8f94-c0e0d465a1e9@e39g2000hsf.googlegroups.com> Message-ID: <485ADF95.5060000@mattnordhoff.com> monkeyboy wrote: > Hello, > > I'm new to python, and PythonCard. In the code below, I'm trying to > create a member variable (self.currValue) of the class, then just pass > it to a simple function (MainOutputRoutine) to increment it. I thought > Python "passed by reference" all variables, but the member variable > doesn't seem to be incremented. If I make the function just increment > the member variable directly, without passing it in, it works fine? > > In the code below, "self.currValue" stays at 5, and value evaluates to > 1? Any insight would be appreciated... > > > class TestModel(model.Background): > > def on_initialize(self,event): > self.currValue = 5 > > def on_startBtn_mouseClick(self, event): > self.MainOutputRoutine(self.currValue) > self.OutputRoutine(self.currValue) > > def OutputRoutine(self,value): > self.components.txtBox1.text = str(value) > > def MainOutputRoutine(self,value): > value = value + 1 That's not how Python works. When you call "self.MainOutputRoutine(self.currValue)", in that method's scope, the local name "value" points to the same object as self.currValue does. When you do "value = value + 1", the local name "value" now points to a different object. That has no bearing on self.currValue. Err, I can't find a guide here. Um, read the language spec? I dunno. However: >>> my_list = [1] >>> def function(l): ... l.append(2) >>> function(my_list) >>> my_list [1, 2] That's because function() is *mutating* the list; it's not changing what the "l" name points to. It's calling the "append" method of the list object, which changes said list object. If it were doing, say, "l = 42", that would only rebind the function's local name "l": >>> my_list = [1] >>> def function(l): ... l = 42 >>> function(my_list) >>> my_list [1] Note that strings and integers are immutable, so whenever you think you're mutating them (e.g. "s.replace('a', 'b')" or "i += 1"), you're actually getting a whole new, different object, with all that that implies. -- From jared.grubb at gmail.com Fri Jun 27 13:54:45 2008 From: jared.grubb at gmail.com (Jared Grubb) Date: Fri, 27 Jun 2008 10:54:45 -0700 Subject: Hamming Distance Message-ID: <925822270806271054j57905cf4lc4568e5e075c3ed0@mail.gmail.com> Matimus, I was surprised that "lazy" was the algorithm that won your time tests, and I saw a way to improve it even better (algorithm is O(# ones in number) rather than O(# bits in number)) def lazy2(a, b, bits=32): x = (a ^ b) & ((1 << bits) - 1) tot = 0 while x: tot += 1 x &= x-1 return tot # times on my system (run a few times just to check for sure) python -mtimeit -s"from ham import *" "test(lazy)" 10000 loops, best of 3: 121 usec per loop python -mtimeit -s"from ham import *" "test(lazy2)" 10000 loops, best of 3: 62.4 usec per loop Check my math, but I think that's correct. Here's my derivation (but it's been a while since my Boolean algebra days, so I may've made a mistake!) It sounds right, though, since subtracting one in two's complement flips the rightmost one and inverts the zeros to the right of it. So, x & (x-1) would remove the rightmost one. Right? Long Derivation: The "trick" to finding the rightmost one in a number: pos = x ^ (x-1) It has to do with how two's-complement works. In our algorithm above, we are trying to count them, so we want to flip off the bits one by one from the right. So in each loop: x = x & ~pos But, then you notice you can simplify it even more (let y=x-1) and use mult/add syntax for & and | and use X=~x and Y=~y x * ~(x ^ y) x * ~(xY+Xy) [ def of ^ ] x * (~(xY)*~(Xy)) [ DeMoires Law ] x * ( (X+y)*(x+Y) ) [ inversion] x * (X+y) * (x+Y) [ associative] (xX+xy)*(x+Y) [ distributive ] xy*(x+Y) [ xX = 0 ] xy+xyY [ distrib ] xy [yY = 0] So, x &= x-1 On 19 Jun 2008, at 17:37, Matimus wrote: On Jun 19, 4:27 pm, godavemon wrote: I need to calculate the Hamming Distance of two integers. The hamming distance is the number of bits in two integers that don't match. I thought there'd be a function in math or scipy but i haven't been able to find one. This is my function but it seems like there should be a faster way. I do this computation many times and speed up is important. def hamdist( a, b , bits = 32): def _hamdist( x, bits): if bits: return (x & 1) + _hamdist(x >> 1, bits-1) return x & 1 return _hamdist( a ^ b, bits) Another alternative would be to convert the XOR to a binary string and count the # of 1's. Which would be fastest? Are there better alternatives? Thanks! I see no good reason to use recursion for this type of thing. Here are some of my attempts: [code] from math import log def yours(a, b , bits = 32): def _hamdist( x, bits): if bits: return (x & 1) + _hamdist(x >> 1, bits-1) return x & 1 return _hamdist(a ^ b, bits) def simple(a, b, bits=32): x = a ^ b return sum((x >> i & 1) for i in xrange(bits)) def lazy(a, b, bits=32): x = (a ^ b) & ((1 << bits) - 1) tot = 0 while x: tot += x & 1 x >>= 1 return tot def fancy(a, b, bits=32): x = (a ^ b) & ((1 << bits) - 1) tot = 0 while x: tot += 1 x ^= 1 << int(log(x, 2)) return tot test_vals = ( ((0xffffffff, 0), 32), ((0,0), 0), ((1,0), 1), ((0x80000000, 0), 1), ((0x55555555, 0), 16) ) def test(f): test_vals = ( ((0xffffffff, 0), 32), # ALL ((0,0), 0), # None ((1,0), 1), # First ((0x80000000, 0), 1), # Last ((0x55555555, 0), 16), # Every Other ((0xffff, 0), 16), # First Half ((0xffff0000, 0), 16), # Last Half ) for i, (args, exp) in enumerate(test_vals): if f(*args) != exp: return 0 return 1 if __name__ == "__main__": for f in (yours, simple, lazy, fancy): if not test(f): print "%s failed"%f.__name__ [/code] The python module `timeit` is handy for testing speed: python -mtimeit -s"from hamdist import *" "test(yours)" 10000 loops, best of 3: 95.1 usec per loop python -mtimeit -s"from hamdist import *" "test(simple)" 10000 loops, best of 3: 65.3 usec per loop python -mtimeit -s"from hamdist import *" "test(lazy)" 10000 loops, best of 3: 59.8 usec per loop python -mtimeit -s"from hamdist import *" "test(fancy)" 10000 loops, best of 3: 77.2 usec per loop Even the ridiculous `fancy` version beat the recursive version. Matt -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From anandology at gmail.com Sat Jun 21 06:28:13 2008 From: anandology at gmail.com (Anand) Date: Sat, 21 Jun 2008 03:28:13 -0700 (PDT) Subject: exec with custom dict Message-ID: <3ad8d167-7436-4688-9a34-72169804f97e@x1g2000prh.googlegroups.com> Hi, I am trying to use exec with custom dict. I am trying to print the value of variable x in 2 places. It is printing it at the first place and failing at the second place. class Env(dict): def __getitem__(self, key): return self.get(key, key) code = """ print x def f(): return x """ env = Env() exec(code, env) print env['f']() Here is the output I'm getting. x Traceback (most recent call last): File "a.py", line 14, in print env['f']() File "", line 3, in f NameError: global name 'x' is not defined Can somebody explain me what is happening? -Anand From musiccomposition at gmail.com Fri Jun 27 21:57:02 2008 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 27 Jun 2008 18:57:02 -0700 (PDT) Subject: Embedded Python Import problem References: Message-ID: <63950245-6995-4eff-b77d-2c3962366844@b1g2000hsg.googlegroups.com> On Jun 27, 5:47?pm, sleek wrote: > I am having trouble with the following code: > > PyObject *module = PyImport_ImportModule(modulename); > if (module == NULL) { > > ? ? PyObject* et, *ev, *etr; > ? ? PyErr_Fetch(&et, &ev, &etr); > ? ? PyObject* traceback = PyImport_ImportModule("traceback"); > ? ? PyObject* tb = PyObject_CallMethodObjArgs(traceback, > PyString_FromString("format_exception"), et, ev, etr, NULL); This is probably failing and returning NULL; When you call PyObject_Str on NULL, you get "." > > ? ? char *message = PyString_AsString(PyObject_Str(tb)); > ? ? ... > ? ? ... > > } From jeffrey at fro.man Wed Jun 18 16:54:01 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Wed, 18 Jun 2008 13:54:01 -0700 Subject: Ternary operator alternative in Ptyhon References: <485947df$0$869$ba4acef3@news.orange.fr> Message-ID: jeremie fouche wrote: > You can also use : > self.SomeField = params.has_key("mykey") and params["mykey"] or None Have caution with this solution: it may not provide the desired result in the case where params["mykey"] is a false value, such as 0, or [] Jeffrey From jkugler at bigfoot.com Thu Jun 26 13:13:58 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Thu, 26 Jun 2008 09:13:58 -0800 Subject: I Need A Placeholder References: Message-ID: Ampedesign wrote: > I'm trying to build a try/except case, and I want to have the except > function like such: > > try: > # Do some code here > var = 1 # For example > except: > #Do nothing here > > The only problem is if I leave a comment only in the except block, I > get an error back saying that the except block is not properly > formatted, since it has no content other than a comment. > > So if anyone could suggest some code to put there as a placeholder > that would be wonderful. except: pass is the usual technique there. j From Lie.1296 at gmail.com Wed Jun 25 13:49:31 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 25 Jun 2008 10:49:31 -0700 (PDT) Subject: Question: How do I format printing in python References: Message-ID: <98d2a6fc-bcd3-44b8-bcf6-7059859683ff@c19g2000prf.googlegroups.com> On Jun 24, 12:12?am, joemacbusin... at yahoo.com wrote: > Hi All, > > How do I format printed data in python? > I could not find this in the Python Reference Manual:http://docs.python.org/ref/print.html > Nor could I find it in Matloff's great tutorial:http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf > > For example, how do I turn this: > > 512 Jun 5 2004 X11r6 > 22 Jan 17 2005 a2p > 22 Jan 17 2005 acctcom > 5374 Sep 15 2002 acledit > 5664 May 13 2004 aclget > 12020 May 13 2004 aclput > 115734 Jun 2 2004 adb > 46518 Jun 4 2004 admin > 66750 Sep 16 2002 ali > 1453 Sep 15 2002 alias > 28150 Jun 4 2004 alog > 15 May 12 2005 alstat > > into this: > > 512 ? ? ? ?Jun ? 5 ? 2004 ? ?X11r6 > 22 ? ? ? ? Jan ? 17 ?2005 ? ?a2p > 22 ? ? ? ? Jan ? 17 ?2005 ? ?acctcom > 5374 ? ? ? Sep ? 15 ?2002 ? ?acledit > 5664 ? ? ? May ? 13 ?2004 ? ?aclget > 12020 ? ? ?May ? 13 ?2004 ? ?aclput > 115734 ? ? Jun ? 2 ? 2004 ? ?adb > 46518 ? ? ?Jun ? 4 ? 2004 ? ?admin > 66750 ? ? ?Sep ? 16 ?2002 ? ?ali > 1453 ? ? ? Sep ? 15 ?2002 ? ?alias > 28150 ? ? ?Jun ? 4 ? 2004 ? ?alog > 15 ? ? ? ? May ? 12 ?2005 ? ?alstat > > Thank you There is string formatting print formatspecifier_string % data_sequence The format specifier is similar to the one used in C's printf, and data sequence may be tuple or list. Dictionary may also be used for data, but it has its own way to specify string formatting since dictionary is unordered but "indexed" by the dict key. From Lie.1296 at gmail.com Tue Jun 3 06:52:15 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 3 Jun 2008 03:52:15 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <5ea78616-e955-4ee0-8e60-a22734ec31be@79g2000hsk.googlegroups.com> Message-ID: <207cafc4-ba3a-47cb-95d6-50b2b709b84b@j33g2000pri.googlegroups.com> On May 24, 9:14?pm, Fuzzyman wrote: > On May 24, 2:58 pm, Ben Finney > wrote: > > > Sh4wn writes: > > > first, python is one of my fav languages, and i'll definitely keep > > > developing with it. But, there's 1 one thing what I -really- miss: > > > data hiding. I know member vars are private when you prefix them with > > > 2 underscores, but I hate prefixing my vars, I'd rather add a keyword > > > before it. > > > From whom are you trying to hide your attributes? > > Actually, 'data hiding', although vastly overused by the static crowd > can be a reasonable thing to want. > > For example, at Resolver Systems we expose the spreadsheet object > model to our users. It hasa public, documented, API - plus a host of > undocumented internally used methods. > > We would really *much* rather hide these, because anything our > customers start using (whether documented or not) we will probably > have to continue supporting and maintaining. > > The 'we told you not to use that' approach, when applied to paying > customers doesn't really work... all they see is that you broke their > spreadsheet code by changing your API. > > You can make members truly private by proxying, but it is a bit > ungainly. Then don't document it, or separate internal documentation (which is never to pass through the wall) and public documentation (which your users use). Nobody would (apart from your dev team and anyone told by your dev team, which means you may fire the person for "lack of discipline") know that there is such a thing and in consequence wouldn't use it. Don't tell your user not to use something, just don't tell them that it exists and they won't use it. From mccredie at gmail.com Tue Jun 17 17:03:48 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 17 Jun 2008 14:03:48 -0700 (PDT) Subject: 2d graphics - drawing a vescica piscis in Python References: <02c29cf2-5281-4c6f-966c-cb47101529ee@26g2000hsk.googlegroups.com> Message-ID: <7c4301f6-9ec4-4d40-91ea-2b0425c193b7@u36g2000prf.googlegroups.com> On Jun 17, 12:45?pm, Terrence Brannon wrote: > Hello, I have written a program to draw a vescica piscis en.wikipedia.org/wiki/Vesica_piscis> > > from turtle import * > > def main(): > ? ? setup(width=400, height=400) > > ? ? r = 50 > ? ? color("black") > ? ? circle(r) > ? ? color("white") > ? ? forward(r) > ? ? color("black") > ? ? circle(r) > ? ? x = raw_input('please enter a string:') > > if __name__ == '__main__': > ? ? main() > > ... but I would like the following: > > 1 - I dont like how the bottom of the first circle is not complete > 2 - I would like for the left circle to be filled with verticle lines > and the right circle to be filled with horizontal lines, so that the > vescica piscis is cross-hatched. > > And finally, is turtle the "best" option for what I'm doing? pyCairo > looked a bit hard to get going with, but very powerful. sping looked a > bit alpha/beta. I would just draw on the tk canvas: >>> import Tkinter as tk >>> can = tk.Canvas() >>> can.pack(fill=tk.BOTH, expand=True) >>> c1 = can.create_oval(10,10,110,110) >>> c2 = can.create_oval(60,10,170,110) You can draw cross hatching using can.create_line(...). Have fun, Matt From sri_annauni at yahoo.co.in Sat Jun 14 17:38:41 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Sun, 15 Jun 2008 03:08:41 +0530 (IST) Subject: Socket Programming Message-ID: <841331.49664.qm@web7903.mail.in.yahoo.com> Hi, Is there any way(method) to find whether the socket got closed or not?? Thanks, Srini Best Jokes, Best Friends, Best Food and more. Go to http://in.promos.yahoo.com/groups/bestofyahoo/ From sam at mitre.org Thu Jun 5 10:29:18 2008 From: sam at mitre.org (Samuel Bayer) Date: Thu, 05 Jun 2008 10:29:18 -0400 Subject: select.poll in MacOS Leopard? Message-ID: <4847F83E.80002@mitre.org> All - The Python that comes with MacOS 10.5 doesn't have select.poll. The MacOS X build from python.org does, and works fine in 10.5. Any idea why the Apple build is broken? Anybody come across this before? Thanks in advance - Sam Bayer The MITRE Corporation sam at mitre.org From tjreedy at udel.edu Thu Jun 26 18:24:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 26 Jun 2008 18:24:15 -0400 Subject: list previous or following list elements In-Reply-To: References: Message-ID: antar2 wrote: > Hello > > > Suppose I have a textfile (text1.txt) with following four words: I see seven. Just say 'list of words' > > Apple > balcony > cartridge > damned > paper > bold > typewriter > > and I want to have a python script that prints the words following the > word starting with the letter b (which would be cartridge) or > differently put, a script that prints the element following a > specified element: > > I am more experienced in Perl, and a beginner in python > > I wrote a script that - of course - does not work, that should print > the element in a list following the element that starts with a b I believe wordlist = open('words.txt','r').read().split('\n') should give you the list in Python. In any case, wordlist = ['Apple','balcony', 'cartridge', 'damned', 'paper', 'bold', 'typewriter'] for i, word in enumerate(wordlist): if word[0] == 'b': print(wordlist[i+1]) # 3.0 break #prints cartridge (in 3.0) From pavlovevidence at gmail.com Mon Jun 23 18:19:41 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 23 Jun 2008 15:19:41 -0700 (PDT) Subject: regexp: match only if previous matched? References: <95ccceb7-c628-49f8-95bc-17f3740b1b27@m3g2000hsc.googlegroups.com> Message-ID: <33df6dd4-1df3-4dbc-8740-6605ae83efef@y21g2000hsf.googlegroups.com> On Jun 23, 6:02?pm, cirfu wrote: > I need to extract prices froma html-document. > > [0-9]*\$ matches 112$ 45$ etc but also just a $. why that shouldnt > really matter and it is unlikely anyway to appear a $sign with no > price attahced to it I still want to prevent it. > > How do I avoid matching "$"? It has to be "nbr$". The answer to your question is to use a + instead of *. + matches 1 or more elements, * matches zero or more. The second point to mention is that, at least where I come from, the currency symbol comes before the number: $112 and $45 In which case your regexp should be somehting like this: \$[0-9]+ Carl Banks From sean_mcilroy at yahoo.com Sat Jun 28 16:22:21 2008 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: Sat, 28 Jun 2008 13:22:21 -0700 (PDT) Subject: tictactoe (reprise) Message-ID: <8510f91b-bbc1-4ebf-8426-d7cd376e2daa@w8g2000prd.googlegroups.com> """ AUTHOR: Sean McIlroy LANGUAGE: Python 2.5 OVERVIEW: instances of "tictactoeplayer" play optimal tictactoe SPECIALIZED TYPES: player={ex,oh}; empty={blank}; cell=player+empty; board=[cell] TYPE RELATIONS: bool(c)==True for any c in cell """ ex, oh, blank = 'X', '0', ' ' linear = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8], [2,4,6]] lines = lambda board: [[board[i] for i in x] for x in linear] mover = lambda board: board.count(ex)==board.count(oh) and ex or oh opponent = lambda player: player==ex and oh or ex makesthreat = lambda player, cells: cells.count(blank)==1 and opponent(player) not in cells numthreats = lambda player, board: len([x for x in lines(board) if makesthreat(player,x)]) haswon = lambda player, board: [player]*3 in lines(board) marked = lambda board, index: [(board[i],mover(board))[i==index] for i in range(9)] display = lambda board: '\n\n' + '\n-+-+-\n'.join(['|'.join(board[3*i: 3*(i+1)]) for i in range(3)]) + '\n\n' blankindices = lambda board: [i for i in range(9) if board[i]==blank] isfinished = lambda board: blankindices(board)==[] or [ex]*3 in lines(board) or [oh]*3 in lines(board) numownthreats = lambda board: numthreats(mover(board),board) numopponentsthreats = lambda board: numthreats(opponent(mover(board)),board) outcomevalue = lambda board: haswon(opponent(mover(board)),board) and (-1) or haswon(mover(board),board) and (+1) or 0 assessment = lambda board: [outcomevalue(board), (-1)*numopponentsthreats(board),(+1)*numownthreats(board)] value = lambda board, index: blankindices(board) in [[],[index]] and assessment(marked(board,index)) or \ min([assessment(marked(marked(board,index),i)) for i in blankindices(board)if not i==index]) blankindexvalues = lambda board: [value(board,i) for i in blankindices(board)] analogisoptimal = lambda list1, list2, optimum: [x for (i,x) in enumerate(list1) if list2[i]==optimum(list2)] optimalblankindices = lambda board: blankindices(board) and analogisoptimal(blankindices(board),blankindexvalues(board),max) optimalmoves = lambda board: [marked(board,i) for i in optimalblankindices(board)] centergrabs = lambda board: [marked(board,i) for i in [4] if i in blankindices(board)] cornergrabs = lambda board: [marked(board,i) for i in [0,2,6,8] if i in blankindices(board)] tictactoemove = lambda board: len(blankindices(board)) in [8,9] and (centergrabs(board) or cornergrabs(board))[0] or \ optimalmoves(board) and optimalmoves(board)[0] or isfinished(board) and board class tictactoeplayer: def __init__(self): globals()['mark'] = self.mark globals()['newgame'] = self.newgame globals()['turn'] = self.turn print 'ENTER mark(i) TO PLACE A MARK ON THE i-TH CELL' print '123' + '\n' + '456' + '\n' + '789' print 'ENTER newgame() TO START A NEW GAME' print 'ENTER turn() TO GIVE UP YOUR TURN' self.newgame() def mark(self,offbyoneindex): self.board = marked(self.board,offbyoneindex-1) print 'your move:' + display(self.board) self.turn() def newgame(self): self.board = [blank]*9 print 'new game:' + display(self.board) def turn(self): self.board = tictactoemove(self.board) print 'my move:' + display(self.board) From nick at craig-wood.com Wed Jun 11 04:30:57 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 11 Jun 2008 03:30:57 -0500 Subject: mysql to sqlite References: Message-ID: Gandalf wrote: > I'm trying to convert mysql database to sqlite. is their any free tool > that does that? > I can convert my mysql db to XML file through phpmyadmin, will it be > easier to convert from XML to SQlite then from Mysql? I'd probably create the sqlite tables first by editing the database schemas produced by mysqldump to make the acceptable to feed to sqlite. I would then write a script which connects to both databases at once and copies the table data across. (At least that is what I did last time I needed to do that which was from MSSQL->MySQL). You'll find that different databases have subtly different ways of doing things (eg autoincrement fields on mysql) so you'll most likely need a custom script anyway. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From gandalf at shopzeus.com Fri Jun 6 09:54:06 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 06 Jun 2008 15:54:06 +0200 Subject: How to kill a thread? In-Reply-To: <608040960806060522m32c4e6abp836684b15c98aac3@mail.gmail.com> References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <608040960806060522m32c4e6abp836684b15c98aac3@mail.gmail.com> Message-ID: <4849417E.90605@shopzeus.com> > > def run(self): > while True: > if exit_event.isSet(): > # Thread exiting > return > try: > data = q_in.get(timeout = .5) > except Queue.Empty: > continue > # ... process data > > And then in the MainThread I do exit_event.set() and wait for all > threads to exit. It's a pretty awkward solution but works. > > BTW Guys, is something like Thread.kill() planned for the future? Or > is there a reason not to have it? Python threads are cooperative. I think there was a discussion about this, about a year ago or so. The answer was that in CPython, the interpreter has this GIL. Python threads are always running on the same processor, but they are not "native". There are operating system functions to kill a thread but you must not use them because it can crash the interpreter. Python MUST clean up object reference counts, manage memory etc. The OS function would kill the thread in a way so that it would be impossible to fee up memory, and also the interpreter can be left in bad state. I'm not sure about the details, but the short answer is that it is not planned. Many programmers said that you have to write cooperative threads anyway. Killing threads forcedly is not a good idea in any language. I hope others will correct me if I'm wrong. Best, Laszlo From akineko at gmail.com Thu Jun 26 21:00:18 2008 From: akineko at gmail.com (akineko) Date: Thu, 26 Jun 2008 18:00:18 -0700 (PDT) Subject: What happened to _tkinter.so? Message-ID: <38a292f9-d127-48cd-8e06-62ce7ab6d62f@u6g2000prc.googlegroups.com> Hello Python developers, I have noticed something curious while I was investigating a problem with the PyInstaller. In my environment, the PyInstaller couldn't find TCL/TK installation path even I have it. I found the PyInstaller uses output from ldd to find the a path to TCL/TK libraries. But no dynamic libraries under my Python 5 lib-dynload directoty contain a path to TCL/TK libraries. When I posted this problem to the PyInstaller newsgroup, a guy responded that he didn't have such problem. After several exchanges, what we found was his lib-dynload directory contains _tkinter.so (even he has the same Python2.5.2) while my lib- dynload directory doesn't have it. He installed the Python using package tool (no fresh compile) while I installed my Python from src (clean compile). I recompiled Python 2.4 and confirmed that Python 2.4 creates _tkinter.so. After browsing the Makefile under Python 2.5, I had an impression that Python 2.5 no longer uses _tkinter.so. Am I correct? If that is the case, I need to warn the PyInstaller developers that the scheme to find TCL/TK path is no longer valid. Any comments will be highly appreciated. Thank you for your attention. Aki Niimura From andreas.tawn at ubisoft.com Fri Jun 13 05:30:50 2008 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Fri, 13 Jun 2008 11:30:50 +0200 Subject: boolian logic In-Reply-To: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> References: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> Message-ID: <8AEDA5E3386EA742B8C24C95FF0C7580042EA82B@PDC-MAIL3.ubisoft.org> if a != b and a != c and a != d: doStuff() else: doOtherStuff() Cheers, Drea >HI all, I'm a bit stuck with how to work out boolian logic. > >I'd like to say if A is not equal to B, C or D: > do something. > >I've tried > >if not var == A or B or C: >and various permutations but can't seem to get my head around it. I'm >pretty sure I need to know what is calulated first i.e the not or the >'OR/AND's > >thanks, Marc. From userprogoogle-139 at yahoo.co.uk Wed Jun 25 05:38:47 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Wed, 25 Jun 2008 02:38:47 -0700 (PDT) Subject: Mobile Devices Message-ID: Hi, I have been scouting around online for information on how to use Python and a GUI toolikit to develop mobile devices. At present I am using wxPython for desktop apps and would like to continue using that if possible. Anyway, I would like to know what people would recommend for developing mobile applications which can run on Windows Mobile and Mac OS X (iPhone etc)? It would also be cool if the same apps could run where possible (or atleast part of them) on desktop machines as well. Any tips, experiences etc welcome. This is really to stimulate some general discussion. Best, rod From larry.bates at websafe.com` Thu Jun 26 22:15:34 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 26 Jun 2008 21:15:34 -0500 Subject: python interface to Firefox and Thunderbird In-Reply-To: <6c5dab9f-3521-4434-8100-65ad1fe207d0@i36g2000prf.googlegroups.com> References: <6c5dab9f-3521-4434-8100-65ad1fe207d0@i36g2000prf.googlegroups.com> Message-ID: yardennis wrote: > Hi, > > I need python moudles that can > > auto install python 2.5 (web install or a EXE file) > > auto download and install Firefox3 and Thunderbird 2 > auto import from IE 6, 7 and OE 5,6 and Outlook > > read contacts and emails from Thunderbird store > read Firefox 3 bookmarks, history, cookies and password > > Can anyone point to a open source solution ? > > If you know of any freelancer that can help me develop the module > please let me know. > > Thanks > > Dennis > yardennis at gmail dot com The reason you haven't gotten any responses is that you didn't provide adequate information> You didn't say what O/S, so I have to guess that since you said Outlook it must be windows. - Auto download and install FF3/TB2. Why? Dowload the installers and put them somewhere (CD/ROM, Flash Drive, etc) , then write a batch file that installs them. - Auto download and install Python. Same as FF/TB. Get setup.exe from ActiveState Python. - Auto import from IE 6, 7 and OE 5,6 and Outlook. Auto import what into what? Is OE Outlook Express? What do you want to import and what are you importing into? - Read contacts and emails from Thunderbird store. Why? Wouldn't it be easier to read them from the POP3/IMAP server? - Read Firefox 3 bookmarks, history, cookies and password. There are plug-ins that allow you to export these items (at least bookmarks and passwords). History/cookies can be easily cleared by the users. If you want to monitor sites visited, there are better ways. As you can see we will need to know more about what you are trying to accomplish to help more. -Larry From mccredie at gmail.com Fri Jun 20 17:10:27 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 20 Jun 2008 14:10:27 -0700 (PDT) Subject: Tkinter canvas drag/drop obstacle References: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> <09ec833f-7751-4991-8d09-45c200fb4c18@z72g2000hsb.googlegroups.com> Message-ID: On Jun 20, 11:10?am, Matimus wrote: > On Jun 20, 9:11?am, Peter Pearson wrote: > > > Tkinter makes it very easy to drag jpeg images around on a > > canvas, but I would like to have a "target" change color when > > the cursor dragging an image passes over it. ?I seem to be > > blocked by the fact that the callbacks that might tell the > > target that the mouse has entered it (, , > > even ) aren't called if the mouse's button is down. > > What am I missing? ?Have I failed to find the right Tkinter > > document? ?Is Tkinter the wrong tool for this job? ?Thanks. > > > -- > > To email me, substitute nowhere->spamcop, invalid->net. > > I have used a combination of and . You might also > throw in a event to keep track of whether or not the mouse > button was down when it entered the widget or not. > > Depending on what you really want to do though, you might take > advantage of the 'active' state: > > import Tkinter as tk > > can = tk.Canvas() > can.pack(fill=tk.BOTH, expand=True) > > can.create_rectangle( > ? ? ? ? 10,10,100,100, > ? ? ? ? fill="black", > ? ? ? ? activewidth=5, > ? ? ? ? activeoutline="blue" > ? ? ? ? ) > > can.mainloop() > > The 'active*' options take effect when the mouse is on top of that > item. > > If all you are _really_ interested in is a visual indicator, this > should work for you. Note that there is also a disabled state. I only > discovered this by looking at the options available and guessing. > > >>> from pprint import pprint > >>> import Tkinter as tk > >>> can = tk.Canvas() > >>> can.pack(fill=tk.BOTH, expand=True) > >>> r = can.create_rectangle(10,10,100,100) > >>> pprint(can.itemconfig(r)) > > {'activedash': ('activedash', '', '', '', ''), > ?'activefill': ('activefill', '', '', '', ''), > ?'activeoutline': ('activeoutline', '', '', '', ''), > ?'activeoutlinestipple': ('activeoutlinestipple', '', '', '', ''), > ?'activestipple': ('activestipple', '', '', '', ''), > ?'activewidth': ('activewidth', '', '', '0.0', '0.0'), > ?'dash': ('dash', '', '', '', ''), > ?'dashoffset': ('dashoffset', '', '', '0', '0'), > ?'disableddash': ('disableddash', '', '', '', ''), > ?'disabledfill': ('disabledfill', '', '', '', ''), > ?'disabledoutline': ('disabledoutline', '', '', '', ''), > ?'disabledoutlinestipple': ('disabledoutlinestipple', '', '', '', ''), > ?'disabledstipple': ('disabledstipple', '', '', '', ''), > ?'disabledwidth': ('disabledwidth', '', '', '0.0', '0'), > ?'fill': ('fill', '', '', '', ''), > ?'offset': ('offset', '', '', '0,0', '0,0'), > ?'outline': ('outline', '', '', 'black', 'black'), > ?'outlineoffset': ('outlineoffset', '', '', '0,0', '0,0'), > ?'outlinestipple': ('outlinestipple', '', '', '', ''), > ?'state': ('state', '', '', '', ''), > ?'stipple': ('stipple', '', '', '', ''), > ?'tags': ('tags', '', '', '', ''), > ?'width': ('width', '', '', '1.0', '1.0')} > > The 'state' option can be set to 'normal', 'hidden' or 'disabled'. So > if you want to make your canvas items look different when they are > disabled, set the disabled* options and set 'state' to 'disabled'. > > Matt I appologize. I didn't actually test this before posting the code, but if you have the mouse button down before entering an item on the canvas, even the active state doesn't seem apply. So, well, I hope someone finds this information useful, but I guess it isn't going to solve the original posters issue. Matt From rhamph at gmail.com Sat Jun 14 13:04:15 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Sat, 14 Jun 2008 10:04:15 -0700 (PDT) Subject: Automatically restarting system calls? References: Message-ID: On Jun 13, 10:41 am, Dan Stromberg wrote: > I wrote a script(1) replacement in python (http://stromberg.dnsalias.org/ > ~dstromberg/pypty/), but I'm encountering a problem in it. > > I think I know the solution to the problem, but I'd've thought python was > high level enough that this solution isn't required, so I wanted to > inquire about it here. > > Specifically, the program has a signal handler for window size changes. > And if the window is resized during an os.write() (for example), I get a > python exception about needing to restart the system call. > > In C, I know you're supposed to wrap your system calls with while loops > until you don't get an ERESTART, but does one really need to wrap all of > one's os.write()'s (for example) with such while loops in python? Unfortunately, signals are sometimes used to intentionally interrupt system calls, so we can't always loop on ERESTART. However, os.write() is a low level API. Maybe file.write() or socket.send() would be a little more robust? From cwitts at gmail.com Thu Jun 12 09:22:25 2008 From: cwitts at gmail.com (Chris) Date: Thu, 12 Jun 2008 06:22:25 -0700 (PDT) Subject: get keys with the same values References: <7334507d-24e7-43f9-baa3-4e9e87eb20fa@w7g2000hsa.googlegroups.com> Message-ID: <017bbfe2-9ba7-4e8c-bb9c-fec923fd54a8@z72g2000hsb.googlegroups.com> On Jun 12, 2:15?pm, Nader wrote: > On Jun 12, 2:05 pm, Chris wrote: > > > > > On Jun 12, 1:48 pm, Nader wrote: > > > > On Jun 12, 1:35 pm, bearophileH... at lycos.com wrote: > > > > > Nader: > > > > > > d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} > > > > > I will something as : > > > > > d.keys(where their values are the same) > > > > > That's magic. > > > > > > With this statement I can get two lists for this example: > > > > > l1= ['a','e'] > > > > > l2=['b','d'] > > > > > Would somebody tell me how I can do it? > > > > > You can create a new dict where the keys are the values of the input > > > > dict and the values are a list of the keys of the original dict. So > > > > scanning the keys, values of the input dict, you can fill the second > > > > dict. Then you can scan the second dict, and create a list that > > > > contains only value lists longer than one. > > > > > Bye, > > > > bearophile > > > > Is it niet possible with one or two statement, maybe with list > > > comprehension. For exmple: > > > > l = [(k,v) for k in d.keys() for v in d.values() | en here we need > > > some extra logic (v = 1)] > > > > I don;t konw how we can define a logic statement in a list > > > comprehension. > > > It will be very compact, if it would possible. > > > > Nader > > > If you are going to use this reverse look-up alot you'd be better off > > building another dictionary with the original values being keys and > > the original keys being values, if it is used infrequently enough you > > can search for it with result_list = [k for k,v in dictionary.items() > > if v == search_value] > > Thank you! It is the anwser which I was looking for. [(k,v) for k,v > in ?d.items() if v is pattern]. > But I don't understand what tou mean of "reverse look-up a lot"! I > have to read some informations inclusive (latitudes and longitudes) > form a file and after some processing to save part of this information > to other file. > Why do I make a new dictionary? > > Nader If you are just going to perform the lookup once or twice then it's fine to traverse (step through) your original dictionary. If you are going to look up data often though it might be a better idea to build another dictionary with the reverse of your original dictionary as it will yield faster results. For example, your original dictionary of values is built and then you perform a handful of operations and move on, then use the list comprehension to get your data and move on. If, on the other hand, you build your dictionary and then maybe iterate over a file and need to look-up the information for every line in the file it would be better suited to build a new dictionary that transposed the key and value pairs for less resource intensive and faster operation. eg: reverse_dict = {} for k,v in original_dict: if v in reverse_dict: reverse_dict[v].append(k) else: reverse_dict[v] = [k] Then once that is built and you want to find which keys in the original dictionary have the value of "1" you can just do "list_of_keys = reverse_dict[1]". Essentially if you are going to do alot of searching for values that match values found in a dictionary you would be better off to create the new data structure. Hope that helps. From Russ.Paielli at gmail.com Wed Jun 11 02:11:02 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 10 Jun 2008 23:11:02 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <4847d39d$0$7614$426a74cc@news.free.fr> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> <484cf5f6$0$15495$426a74cc@news.free.fr> <127975a3-b3d9-4799-9673-b292ec8d37e3@x19g2000prg.googlegroups.com> <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> <484e3526$0$30894$426a74cc@news.free.fr> <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> <783c55ec-a294-4600-91d9-4a0d78632c49@t12g2000prg.googlegroups.com> Message-ID: <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> On Jun 10, 11:58 am, Jonathan Gardner > Who cares what the type of an object is? Only the machine. Being able > to tell, in advance, what the type of a variable is is a premature > optimization. Tools like psyco prove that computers (really, > programmers) nowadays are smart enough to figure things out the right > way without any hints from the developer. Static typing is no longer > necessary in today's world. You couldn't be more wrong. Even Guido recognizes the potential value of static typing, which is why he is easing it into Python as on optional feature. He recognizes, correctly, that it can detect errors earlier and facilitate more efficient execution. But there's another, more significant potential benefit for safety-critical and mission- critical applications: static typing facilitates advanced static analysis of software. To get an idea of what that is about, take a look at http://www.sofcheck.com Here is an excerpt from their website: "SofCheck?s advanced static error detection solutions find bugs in programs before programs are run. By mathematically analyzing every line of software, considering every possible input, and every path through the program, SofCheck?s solutions find any and all errors that cause a program to crash or produce an undefined result." Me again: static analysis does not replace traditional dynamic and unit testing, but it is far more advanced and finds many errors very quickly that might require weeks or months of dynamic testing -- or might not be found at all with dynamic testing until the product is in the field. With more and more automation of safety-critical systems these days, we need this more than ever. Your assertion that "Static typing is no longer necessary in today's world," is just plain naive. > Who cares about private declarations, or interface declarations at > all? It is only a message to the developers. If you have a problem > with your users doing the right thing, that is a social problem, not a > technical one, and the solution is social, not technical. Yes, it is > work, but it is not coding---it is explaining to other living, > breathing human beings how to do a specific task, which is what you > should have been doing from the start. You may be right to an extent for small or medium-sized non-critical projects, but you are certainly not right in general. I read something a while back about the flight software for the Boeing 777. I think it was something like 3,000,000 lines of Ada code. Normally, for a project of that magnitude the final integration would be expected to take something like three months. However, the precise interface specs and encapsulation methods in Ada allowed the integration to be completed in just three days. By your recommended method of social interaction, that would be one hell of a lot of talking! I realize that Python is not designed for such large projects, but don't you think certain general principles can be learned anyway? Perhaps the benefits of interface specs and encapsulation are not as obvious for smaller projects, but certainly they are not zero. From bearophileHUGS at lycos.com Tue Jun 17 13:09:18 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 17 Jun 2008 10:09:18 -0700 (PDT) Subject: Pattern Matching Over Python Lists References: <21a9c996-75ff-4f7c-b7e9-c94247f65674@c58g2000hsc.googlegroups.com> <87ej6w6ql6.fsf@internal.daycos.com> Message-ID: <61ea5c70-4352-4d2f-a0ef-62eb76ba933a@m36g2000hse.googlegroups.com> Kirk Strauser: > Hint: recursion. Your general algorithm will be something like: Another solution is to use a better (different) language, that has built-in pattern matching, or allows to create one. Bye, bearophile From expertleong at gmail.com Mon Jun 30 22:59:09 2008 From: expertleong at gmail.com (Hongster) Date: Mon, 30 Jun 2008 19:59:09 -0700 (PDT) Subject: Functions associated with a class. References: Message-ID: <56c16601-569c-4eec-9497-c5803eee051c@g16g2000pri.googlegroups.com> Like what you mentioned, each class has a set of methods and properties (variables). Example of a class: Human Properties of a Human class: height, weight, birthday, occupation, ... Methods of a Human class: eat(food), move(speed, destination), sleep(), ... Methods of a class is just an ordinary function, with an "self" parameter (by convention). You can define more than 1 arguments for a function. Tom = Human() Dick = Human() Tom.eat(corn) Dick.eat(potato) Tom and Dick are both instances of a Human class. They are not arguments. "corn" and "potato" contain values that are passed to the eat() function as argument. The '.' notation is used to indicate which instance's method/property you are referring to. The 'x' and 'y' you mentioned are just different instances, they are not arguments. This is my first post, hopes it helps. On Jul 1, 7:44?am, Kurda Yon wrote: > Hi, > > I start to learn the object oriented programing in Python. As far as I > understood, every class has a set of corresponding methods and > variables. For me it is easy to understand a method as a one-argument > function associated with a class. For example, if I call "x.calc" and > "y.calc" and if "x" and "y" belongs to different classes I, actually, > call to different function (the first one is associated with the first > class and the second one with the second class). If "x" and "y" > belongs to the same class, the "x.calc" and "y.calc" refer to the same > function (but called with different arguments ("x" and "y", > respectively)). > > In the above described case we have one-argument function. But what > should we do if we one two have a two-argument function. For example, > we want to have a method "calc" which take two objects and returns one > value. How do we call this method? Like "x&y.calc"? Or just calc(x,y)? > In the case of the one-argument functions Pythons automatically decide > which function to call (associated with the first class or with the > second class). Will it be the same in the case of the two-argument > function. > > I am not sure that I am clear. If I am not clear, just ask me. I will > try to reformulate my questions. > > Thank you. From martin at v.loewis.de Tue Jun 10 02:56:15 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 10 Jun 2008 08:56:15 +0200 Subject: Cannot install python under Win32 In-Reply-To: <82d86466-0b90-47aa-af40-f52b52eb2526@d77g2000hsb.googlegroups.com> References: <82d86466-0b90-47aa-af40-f52b52eb2526@d77g2000hsb.googlegroups.com> Message-ID: <484e258f$0$13627$9b622d9e@news.freenet.de> > Hello, I have tried to install python 2.5.1 and 2.5.2 with the same > error. The installer starts fine, but when it gets to the part that > says "Status: Copying new files" it terminates with an error code of > 2356. > > Does anyone have a clue to what to do? Run the installer with msiexec /i /l*v py.log, then study py.log to find out what went wrong. Are you by any chance running the installer from a SUBSTed drive? Regards, Martin From apardon at forel.vub.ac.be Wed Jun 4 02:41:44 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Jun 2008 06:41:44 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <5ea78616-e955-4ee0-8e60-a22734ec31be@79g2000hsk.googlegroups.com> <7f1a9057-83c7-4ca6-8fd8-38195db45865@s33g2000pri.googlegroups.com> Message-ID: On 2008-06-03, Lie wrote: > > Python has an extremely good design because the BDFL doesn't just > listen to everyone and create a product that tries to please > everybody, no, he listens to those that have good ideas and tells the > stupid ideas to go away and he applies a subjective decision which > more often than not leads to a better python. I agree that Guido van Rossum has done an excellent job. That doesn't mean he has to be painted as unfailable in which the ideais he accepts are good ideas and those he rejects are bad ideas almost by definition. Guido has been known to change his mind, which is an admirabele quality, but it does show that at some point he rejected a good idea or accepted a bad idea. -- Antoon Pardon From cwitts at gmail.com Fri Jun 6 05:45:37 2008 From: cwitts at gmail.com (Chris) Date: Fri, 6 Jun 2008 02:45:37 -0700 (PDT) Subject: import cherrypy2 References: <0853b1cc-33bb-416e-9b2e-0fa146ede1c1@79g2000hsk.googlegroups.com> Message-ID: <7c00f301-5d49-4f49-98fd-d0f5e72aa135@c65g2000hsa.googlegroups.com> On Jun 6, 10:59?am, luca72 wrote: > On 6 Giu, 10:31, Chris wrote: > > > > > On Jun 6, 10:22 am, luca72 wrote: > > > > Hello i can't import cherrypy2 but i don't know why this is the sys > > > path: > > > > '', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > > setuptools-0.6c7-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > > python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg', '/home/pirataja/ > > > opo.net/python/lib/python2.5/site-packages/TurboKid-1.0.4-py2.5.egg', > > > '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > > TurboJson-1.1.2-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > > python2.5/site-packages/TurboCheetah-1.0-py2.5.egg', '/home/pirataja/ > > > opo.net/python/lib/python2.5/site-packages/simplejson-1.9.1-py2.5- > > > linux-i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site- > > > packages/RuleDispatch-0.5a0.dev_r2306-py2.5-linux-i686.egg', '/home/ > > > pirataja/opo.net/python/lib/python2.5/site-packages/PasteScript-1.6.2- > > > py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > > FormEncode-1.0.1-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > > python2.5/site-packages/DecoratorTools-1.7-py2.5.egg', '/home/pirataja/ > > > opo.net/python/lib/python2.5/site-packages/configobj-4.5.2-py2.5.egg', > > > '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > > CherryPy-2.3.0-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > > python2.5/site-packages/kid-0.9.6-py2.5.egg', '/home/pirataja/opo.net/ > > > python/lib/python2.5/site-packages/Cheetah-2.0.1-py2.5-linux- > > > i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > > PyProtocols-1.0a0dev_r2302-py2.5-linux-i686.egg', '/home/pirataja/ > > > opo.net/python/lib/python2.5/site-packages/PasteDeploy-1.3.1- > > > py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > > Paste-1.7-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > > python25.zip', '/home/pirataja/pirata-jacopo.net/python/lib/ > > > python2.5', '/home/pirataja/opo.net/python/lib/python2.5/plat- > > > linux2', > > > '/home/pirataja/opo.net/python/lib/python2.5/lib-tk', > > > '/home/pirataja/opo.net/python/lib/python2.5/lib-dynload', '/home/ > > > pirataja/opo.net/python/lib/python2.5/site-packages'] > > > > For my is all ok but whe i do import cherrypy2 i get no mudule name > > > cherrypy2 > > > > Regards > > > > Luca > > > because it's "import cherrypy" and not "import cherrypy2" > > sorry but from another python installation i import cherrypy2 as > cherrypy and all works > > Regards > > Luca Did you install Lino on the other installation ? http://lino.sourceforge.net/src/3.html It's the only mention of a cherrypy2 I know of. From ptmcg at austin.rr.com Tue Jun 3 12:15:10 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 3 Jun 2008 09:15:10 -0700 (PDT) Subject: trinity school defender References: Message-ID: <94969559-96f0-4e72-ae1d-4d3bb5273fab@m73g2000hsh.googlegroups.com> On Jun 3, 10:26?am, Dino Dragovic wrote: > u gorenavedenom flajeru u 8. redu: > > "postoji vi?e od 60.000 virusa i drugih ?tetnih programa " > > samo virusa ima nekoliko stotina tisuca, zajedno sa potencijalno stetim > aplikacijama i ostalim malicioznim kodom brojka ide preko milion.... castironpi, call your office... From upton at virginia.edu Tue Jun 10 11:49:12 2008 From: upton at virginia.edu (Dan Upton) Date: Tue, 10 Jun 2008 11:49:12 -0400 Subject: Does the python library of Google Data API is truly free? In-Reply-To: <18115776-edf7-41b8-a5e9-639847c57a6a@x41g2000hsb.googlegroups.com> References: <3ac654b2-61b4-44ce-8e03-75f2344d5869@s50g2000hsb.googlegroups.com> <6fb57ab1-b0d2-4b7d-93c1-b919ca0e51a0@i36g2000prf.googlegroups.com> <3a296d00-d4e0-4f03-b6b3-bef4c5d628dd@x35g2000hsb.googlegroups.com> <6b5mloF3aeui4U1@mid.uni-berlin.de> <18115776-edf7-41b8-a5e9-639847c57a6a@x41g2000hsb.googlegroups.com> Message-ID: <5504f9ac0806100849s316e1907l391f1fd7603f3f65@mail.gmail.com> >> Or if they prohibit you to host malicious, offending or otherwise >> problematic content served by the free apache - is that "against free >> software?" > Please, don't be demagogue. Please don't be [a] troll....? I fail to see what is so hard to understand about the difference between free software and services provided via free software. From markjturner at gmail.com Thu Jun 12 11:37:16 2008 From: markjturner at gmail.com (Mark) Date: Thu, 12 Jun 2008 08:37:16 -0700 (PDT) Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <6bcokhF3b2mo7U1@mid.uni-berlin.de> <485131a1$0$11175$c3e8da3@news.astraweb.com> Message-ID: On Jun 12, 3:45?pm, Aidan wrote: > Aidan wrote: > > Mark wrote: > >> John, it's a QuerySet coming from a database in Django. I don't know > >> enough about the structure of this object to go into detail I'm > >> afraid. > > >> Aidan, I got an error trying your suggestion: 'zip argument #2 must > >> support iteration', I don't know what this means! > > > well, if we can create 2 iterable sequences one which contains the user > > the other the scores, it should work > > > the error means that the second argument to the zip function was not an > > iterable, such as a list tuple or string > > > can you show me the lines you're using to retrieve the data sets from > > the database? then i might be able to tell you how to build the 2 lists > > you need. > > wait you already did... > > predictions = Prediction.objects.all() > pairs = [(p.predictor.id,p.predictionscore) for p in predictions] > > those 2 lines will will build a list of user/score pairs. ?you can then > replace the call to zip with pairs > > any luck? Thanks Aidan, this works great! Thanks also to everyone else, I'm sure your suggestions would have worked too if I'd been competent enough to do them properly! From koblas at gmail.com Wed Jun 4 13:35:05 2008 From: koblas at gmail.com (koblas) Date: Wed, 4 Jun 2008 10:35:05 -0700 (PDT) Subject: Import removing first module component Message-ID: <75481b47-87ec-4a84-8063-7abbdb286d62@u6g2000prc.googlegroups.com> Have the following line: import notewave.runner.LMTP Yeilding the following error: ImportError: No module named runner.LMTP For the life of me I don't understand why the first component "notewave" is being stripped off, when the import is happening. Thanks, From bruno.desthuilliers at gmail.com Wed Jun 25 15:29:06 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 25 Jun 2008 12:29:06 -0700 (PDT) Subject: reading from list with paths References: <6c1ed580-259a-4df2-b389-ecf38296a138@25g2000hsx.googlegroups.com> Message-ID: <69ac18bf-a9a4-45ed-aa74-ccdf2b5f0570@i76g2000hsf.googlegroups.com> On 25 juin, 20:59, antar2 wrote: > Hello, > (snip repost of the very same question) > I already got one answer for this question, but it did not work For which definition of "did not work" ? How is your code ? What did you expect, and what did you get ? Sorry to ask these questions, but my crystal ball is currently down for maintainance... From bronger at physik.rwth-aachen.de Sat Jun 14 15:47:39 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 14 Jun 2008 21:47:39 +0200 Subject: Making wxPython a standard module? References: <6bidd7F3bg8usU1@mid.uni-berlin.de> Message-ID: <87fxrfx0h0.fsf@physik.rwth-aachen.de> Hall?chen! Grant Edwards writes: > On 2008-06-14, Diez B. Roggisch wrote: > >>>> And on a personal note: I find it *buttugly*. >>> >>> Do you mind explaining "why" you find it *buttugly*? > > [...] > >> For the curious: Not the look & feel (albeit I prefer KDE on >> linux over Gnome, which is a Qt/GTK thing and thus affects wx >> look & feel as well), but the code & the designers. > > I've never used any of the designers, but I agree 100% that > wxPython code is nasty ugly. wxPython has a very un-Pythonic API > that's is, IMO, difficult to use. I know that such requests may start a never-ending thread but I'd really like to know what you mean with this. I had almost no GUI experience when I started to use wxPython, yet it was a pleasure for me. Really, aesthetics of the source is important to me being a hobby programmer, and I don't like wxPython's camel case and getters and setters. However, even many (if not most) core Python modules don't respect PEP8 or don't use current language features. Besides, passing function names as strings is also a wart, and *I* have simply never understood signal and slots. Maybe we should accept that there is no silver bullet in GUI toolkits, and any personal preferences amongst the Big Four are just a matter of taste. This "un-Pythonic" thing is arbitrary and unfair wording in my opinion. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From sjmachin at lexicon.net Sun Jun 22 19:39:44 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 22 Jun 2008 16:39:44 -0700 (PDT) Subject: listcomprehension, add elements? References: <13452c64-ef91-49a2-bb73-7f33c088660e@d45g2000hsc.googlegroups.com> <7dc3d1d6-12d7-4a9e-ac7a-91406610e106@d19g2000prm.googlegroups.com> Message-ID: <510c6f38-24f8-431e-9b37-c70ed91b3ee2@z24g2000prf.googlegroups.com> On Jun 23, 9:23 am, Paul Hankin wrote: > On Jun 23, 10:32 am, cirfu wrote: > > > [a+b for a,b in zip(xrange(1,51), xrange(50,0,-1))] > > > [51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, > > 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, > > 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51] > > > i want to add all the elemtns a s well. can i do this all in a > > listcomprehension? > > > i can do this ofc: > > reduce(lambda x,y:x+y,[a+b for a,b in zip(xrange(1,51), > > xrange(50,0,-1))]) > > > but reduce is a functional way of doing it, what is the more pythonic > > way of doing this? > > Use the builtin 'sum' function. > > sum(a + b for a, b in zip(xrange(1, 51), xrange(50, 0, -1))) > Instead of sum(a + b for a, b in zip(foo, bar)) why not use sum(foo) + sum(bar) ? From fc14301589 at icqmail.com Thu Jun 12 03:38:37 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Thu, 12 Jun 2008 15:38:37 +0800 Subject: My fight with classes :) References: <484fde63_1@news.tm.net.my> Message-ID: <4850d287_2@news.tm.net.my> On 04:51, gioved? 12 giugno 2008 Terry Reedy wrote: First of all a big thank you, all. > def makeappender(): > data = ['',''] > def appender(val): > > return appender I'll give it a try. I just doubting if the data will be shared outside the function. Actually, my practice goes to send all variables to the functions and expecting a returned value. Usually I'm not relying on that module's variables are read inside a function. Probably I got wrong learning or experiences. > For multiple functions, use classes. That's what I'm leaning to :) Then I re-elaborated the class according your points and now it's what I wanted to be. :) (last time I forgot to past the first line) Here it comes: class StrJoin: """ Join a pair of strings according to the leading first letter A or D, it returns a list of 2 elements""" def __init__(self): self.valueA= '' self.valueD= '' def append(self, value): if not isinstance(value, str): raise TypeError, 'Wrong type concatenation' if value.lower().startswith('a'): self.valueA += value if value.lower().startswith('d'): self.valueD += value return [self.valueA ,self.valueD] def __getitem__(self,idx): if idx > 1 : return self if idx == 0 : return self.valueA if idx == 1 : return self.valueD __call__= append def __repr__(self): return '['+ self.valueA+ ','+ self.valueD+ ']' And the shell >>: >>> from utilities import StrJoin as zx >>> k = zx() >>> k [,] >>> k('add') ['add', ''] >>> k[2] [add,] >>> k[1] '' >>> k[0] 'add' >>> k('dad') ['add', 'dad'] >>> k('sad') ['add', 'dad'] >>> k('Alfa') ['addAlfa', 'dad'] >>> k('Dude') ['addAlfa', 'dadDude'] >>> k('Omega') ['addAlfa', 'dadDude'] >>> k('Dome') ['addAlfa', 'dadDudeDome'] >>> k.append[k] Traceback (most recent call last): File "", line 1, in TypeError: 'instancemethod' object is unsubscriptable >>> k(89) Traceback (most recent call last): File "", line 1, in File "utilities.py", line 33, in append raise TypeError, 'Wrong type concatenation' TypeError: Wrong type concatenation >>> Mostly I'll use the call option. I also like to pass it into a function in order to modularize the loop where it gets started. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From nick at craig-wood.com Tue Jun 24 04:32:11 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 24 Jun 2008 03:32:11 -0500 Subject: MD5 hash for url and utf unicode converting to ascii References: Message-ID: joe shoemaker wrote: > I would like to convert url into md5 hash. My question is that md5 > hash will create collision at 2^64. If you do long(value,16), where > value is the md5 hash string, would value returned from long(value, > 16) be unique as long as md5 hashed string is unique? when you move > md5 hashed string to long, where will the collision occur, at anything > >= 2^64? > > hash = md5.new() > hash.update("some_url_") > value = hash.digest() > value_in_int = long(value, 16) #would this be unique as long as > hashed string is unique(i.e < 2^64) > hash = md5.new() hash.update("some_url_") value = hash.digest() > value_in_int = long(value, 16) #would this be unique as long as hashed > string is unique(i.e < 2^64) MD5 Sums don't guarantee uniqueness for any length of string. If your hash had as many or more bits in as the input string then there are hashes which are guaranteed unique, but MD5 isn't one of them. You could (lets say) AES encrypt the string instead. > Do I need to also convert the value to base64.encodestring(value)? > What is the purpose of base64.encodestring? To turn the buffer into printable characters. You can do it like this also... >>> import md5 >>> hash = md5.new() >>> hash.update("some_url_") >>> value = hash.digest() >>> value '\xc9\x11}\x8f?64\x83\xf3\xcaPz\x1d!\xddd' >>> value.encode("hex") 'c9117d8f3f363483f3ca507a1d21dd64' >>> long(value.encode("hex"), 16) 267265642849753964132104960801656397156L >>> > For unicode encoding, I can do, md5.update(value.encode('utf-8')) to > give me ascii values. Yes that would be fine -- Nick Craig-Wood -- http://www.craig-wood.com/nick From chrisspen at gmail.com Thu Jun 19 20:44:09 2008 From: chrisspen at gmail.com (Chris) Date: Thu, 19 Jun 2008 17:44:09 -0700 (PDT) Subject: Pattern Matching Over Python Lists References: <21a9c996-75ff-4f7c-b7e9-c94247f65674@c58g2000hsc.googlegroups.com> <87ej6w6ql6.fsf@internal.daycos.com> <61ea5c70-4352-4d2f-a0ef-62eb76ba933a@m36g2000hse.googlegroups.com> Message-ID: <0796be8f-647c-4d19-86e5-e2472fb2daa3@34g2000hsh.googlegroups.com> Thanks for your help. Those weren't quite what I was looking for, but I ended up figuring it out on my own. Turns out you can actually search nested Python lists using simple regular expressions. From martin at marcher.name Mon Jun 2 10:23:00 2008 From: martin at marcher.name (Martin Marcher) Date: Mon, 2 Jun 2008 16:23:00 +0200 Subject: Python's doc problems: sort In-Reply-To: <929d5ce9-9063-4e6c-98aa-89526f89fba3@y18g2000pre.googlegroups.com> References: <929d5ce9-9063-4e6c-98aa-89526f89fba3@y18g2000pre.googlegroups.com> Message-ID: <5fa6c12e0806020723r306bb44dx99aaa0696210ce3b@mail.gmail.com> Hi, On Wed, Apr 30, 2008 at 4:48 AM, xahlee at gmail.com wrote: > For example, in last week, that page is fetched 550 times. > The second most popular page, trails quite a distance. Here's the top yup that was me, i have access to a couple of machines and wanted to test some intercommunication, I faked most of the user agent strings but still was locked out by popular pages. I then figured it would be much better to fetch a useless page a couple of times. Sorry for the lognoise... /martin -- http://www.xing.com/profile/Martin_Marcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From deets at nospam.web.de Thu Jun 12 15:32:10 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 12 Jun 2008 21:32:10 +0200 Subject: Mapping None. Why? In-Reply-To: References: Message-ID: <6bdbtuF3aqe92U1@mid.uni-berlin.de> Paddy schrieb: > Iam wondering why the peculiar behavior of map when the function in > given as None: > > Help on built-in function map in module __builtin__: > > map(...) > map(function, sequence[, sequence, ...]) -> list > > Return a list of the results of applying the function to the items > of > the argument sequence(s). If more than one sequence is given, the > function is called with an argument list consisting of the > corresponding > item of each sequence, substituting None for missing values when > not all > sequences have the same length. If the function is None, return a > list of > the items of the sequence (or a list of tuples if more than one > sequence). > > > It seems as the action whith none is the same as using a function of > lambda *x: x > As in the following example: > >>>> l1 = 'asdf' >>>> l2 = 'qwertyuip' >>>> l3 = range(3) >>>> l1,l2,l3 > ('asdf', 'qwertyuip', [0, 1, 2]) >>>> map(lambda *x: x, l1,l2,l3) == map(None, l1,l2,l3) > True > > > On looking up map on Wikipedia there is no mention of this special > behaviour, > So my question is why? Because it is undefined what should happen in case of no function given at all - and because there is no identity function in python pre-defined, it could be considered sensible to make None the quivalent of that function. And it only follows that *if* you imply a function even though there is None given, that the passed tuple is returned. I don't see anything on wikipedia that defines any other behavior. Diez Diez From ptmcg at austin.rr.com Wed Jun 18 15:51:16 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 18 Jun 2008 12:51:16 -0700 (PDT) Subject: Does '!=' equivelent to 'is not' References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> <20080617120941.GE7349@dragontoe.org> Message-ID: <0fcecc82-0edd-4f57-865a-b2e558577281@x35g2000hsb.googlegroups.com> On Jun 18, 2:22?pm, Lie wrote: > > I'm not a native English speaker, although I think my parents would > have liked me to be more straightforward when talking, cause I tend to > say things like "possibly", "maybe", "probably", and other ambiguous > expressions to the extent that it has frustrated them now and then. Well, at least you *talk* to your parents! Mostly what I get from my kids is, "can I borrow 10 dollars?" -- Paul From saqib.ali.75 at gmail.com Fri Jun 20 16:17:54 2008 From: saqib.ali.75 at gmail.com (susan_ali@hotmail.com) Date: Fri, 20 Jun 2008 13:17:54 -0700 (PDT) Subject: How do I create a new Node using pulldom? Message-ID: I'm using xml.dom.pulldom to parse through an XML file. I use expandNode() to scrutinize certain blocks of it that I'm interested in. Once I find a block of XML in the input file that I'm interested in, I need to add my own block ..... to the pulldom tree I'm building in memory. The documentation on PullDom is worse than atrocious. It is simply non- existant. I can't even find a simple explanation of what the functions are named and what arguments they take. Sheesh. When I have a node N of the tree, I think that I can use N.appendChild() to do what I want (just guessing from the function name which I can see). appendChild takes 1 argument -- a new node. But I don't know how to create such a node. Can someone out there please post a code fragment showing how to create a pulldom node? The simpler and more commented it is the better. THANKS!!! - Saqib From ludvig.ericson at gmail.com Tue Jun 24 17:35:38 2008 From: ludvig.ericson at gmail.com (ludvig.ericson at gmail.com) Date: Tue, 24 Jun 2008 14:35:38 -0700 (PDT) Subject: logging module's documentation lies? Message-ID: Quote from the docs: FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s" logging.basicConfig(format=FORMAT) d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} logging.warning("Protocol problem: %s", "connection reset", extra=d) would print something like 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset If we try to run that exact example, which doesn't seem logically flawed in any way: >>> import logging >>> FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s" >>> logging.basicConfig(format=FORMAT) >>> d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} >>> logging.warning("Protocol problem: %s", "connection reset", extra=d) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/site-packages/logging/__init__.py", line 1266, in warning apply(root.warning, (msg,)+args, kwargs) File "/usr/lib/python2.5/site-packages/logging/__init__.py", line 969, in warning apply(self._log, (WARNING, msg, args), kwargs) TypeError: _log() got an unexpected keyword argument 'extra' I tried using **d instead, no show. I tried extra=d in Python 2.4, no show. I tried **d in Python 2.4, no show. So, my question unto the lot of you is: Do the docs for the logging module lie to me? URL: http://docs.python.org/lib/module-logging.html From hv at tbz-pariv.de Tue Jun 3 08:05:56 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Tue, 03 Jun 2008 14:05:56 +0200 Subject: Image Processing (batch) Message-ID: <6akqd5F37rofnU1@mid.individual.net> Hi, I tried PIL for image batch processing. But somehow I don't like it - Font-Selection: You need to give the name of the font file. - Drawing on an image needs a different object that pasting and saving. - The handbook is from Dec. 2006. What image libraries do you suggest? I think there are these alternatives: - Python binding for image magick - python-gtk - python-gdk-imlib - call convert (imagemagick) with subprocess. This is how I did it up to now. But I want to avoid it. Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From bruno.42.desthuilliers at websiteburo.invalid Fri Jun 13 03:00:35 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 13 Jun 2008 09:00:35 +0200 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: References: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> <4850e95d$0$10444$426a74cc@news.free.fr> Message-ID: <48521aae$0$7558$426a74cc@news.free.fr> Duncan Booth a ?crit : > Bruno Desthuilliers wrote: > >> FWIW, metaclasses do have a class attribute that refers to itself !-) >> > One metaclass (i.e. type) has a class attribute that refers to itself. > > Other metaclasses have a class attribute that refers to the metaclass's > metaclass. I can't think of any situation where a metaclass would be its > own metaclass except for 'type' itself, but then I think I've got a > headache trying to think about this Yeps, same pattern here :-/ Thanks for the correction, anyway. (snip) From pistacchio at gmail.com Wed Jun 25 05:13:42 2008 From: pistacchio at gmail.com (pistacchio) Date: Wed, 25 Jun 2008 02:13:42 -0700 (PDT) Subject: Apache2 + Python WITHOUT mod_pytho Message-ID: <4f90e1e5-056e-4f61-866b-015a15030ebf@e39g2000hsf.googlegroups.com> Hi to all! How can i configure apache2 so that it processes all .py files with python _without_ using mod_python? I'm on Ubuntu 8.4. currently my /etc/apache2/sites-available/default file reads: __________________________ NameVirtualHost * ServerAdmin webmaster at localhost DocumentRoot /var/www/ Options FollowSymLinks AllowOverride None #Options +ExecCGI Indexes FollowSymLinks MultiViews Options All AllowOverride None Order allow,deny Allow from all #AddHandler mod_python .py #PythonHandler mod_python.publisher #PythonDebug On ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all ErrorLog /var/log/apache2/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/apache2/access.log combined ServerSignature On Alias /doc/ "/usr/share/doc/" Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 __________________________ Thanks in advance Gustavo From bioinf at physics.iisc.ernet.in Fri Jun 13 02:59:08 2008 From: bioinf at physics.iisc.ernet.in (bioinf at physics.iisc.ernet.in) Date: Fri, 13 Jun 2008 12:29:08 +0530 (IST) Subject: error showing file not found Message-ID: <3183.10.16.30.11.1213340348.squirrel@physics.iisc.ernet.in> Hi, I am new to python.I have installed Biopython in Windows.I am working using IDLE.When I want to get structure of local pdb file it is showing error that "no such file or directory".Can anybody tell what is the problem. -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From bob at mellowood.ca Thu Jun 12 13:51:31 2008 From: bob at mellowood.ca (bvdp) Date: Thu, 12 Jun 2008 10:51:31 -0700 Subject: Simple and safe evaluator References: <80b23a5a-8613-4232-8954-7f7e4181322e@k37g2000hsf.googlegroups.com> Message-ID: Matimus wrote: > On Jun 11, 9:16 pm, George Sakkis wrote: >> On Jun 11, 8:15 pm, bvdp wrote: >> >> >> >>> Matimus wrote: >>>> The solution I posted should work and is safe. It may not seem very >>>> readable, but it is using Pythons internal parser to parse the passed >>>> in string into an abstract symbol tree (rather than code). Normally >>>> Python would just use the ast internally to create code. Instead I've >>>> written the code to do that. By avoiding anything but simple operators >>>> and literals it is guaranteed safe. >>> Just wondering ... how safe would: >>> eval(s, {"__builtins__":None}, {} ) >>> be? From my testing it seems that it parses out numbers properly (int >>> and float) and does simple math like +, -, **, etc. It doesn't do >>> functions like int(), sin(), etc ... but that is fine for my puposes. >>> Just playing a bit, it seems to give the same results as your code using >>> ast does. I may be missing something! >> Probably you do; within a couple of minutes I came up with this: >> >>>>> s = """ >> ... (t for t in 42 .__class__.__base__.__subclasses__() >> ... if t.__name__ == 'file').next()('/etc/passwd') >> ... """>>> eval(s, {"__builtins__":None}, {} ) >> >> Traceback (most recent call last): >> File "", line 1, in >> File "", line 3, in >> IOError: file() constructor not accessible in restricted mode >> >> Not an exploit yet but I wouldn't be surprised if there is one. Unless >> you fully trust your users, an ast-based approach is your best bet. >> >> George > > You can get access to any new-style class that has been loaded. This > exploit works on my machine (Windows XP). > > [code] > # This assumes that ctypes was loaded, but keep in mind any classes > # that have been loaded are potentially accessible. > > import ctypes > > s = """ > ( > t for t in 42 .__class__.__base__.__subclasses__() > if t.__name__ == 'LibraryLoader' > ).next()( > ( > t for t in 42 .__class__.__base__.__subclasses__() > if t.__name__ == 'CDLL' > ).next() > ).msvcrt.system('dir') # replace 'dir' with something nasty > """ > > eval(s, {"__builtins__":None}, {}) > [/code] > > Matt Yes, this is probably a good point. But, I don't see this as an exploit in my program. Again, I could be wrong ... certainly not the first time that has happened :) In my case, the only way a user can use eval() is via my own parsing which restricts this to a limited usage. So, the code setting up the eval() exploit has to be entered via the "safe" eval to start with. So, IF the code you present can be installed from within my program's scripts ... then yes there can be a problem. But for the life of me I don't see how this is possible. In my program we're just looking at single lines in a script and doing commands based on the text. Setting/evaluating macros is one "command" and I just want a method to do something like "Set X 25 * 2" and passing the "25 * 2" string to python works. If the user creates a script with "Set X os.system('rm *')" and I used a clean eval() then we could have a meltdown ... but if we stick with the eval(s, {"__builtins__":None}, {}) I don't see how the malicious script could do the class modifications you suggest. I suppose that someone could modify my program code and then cause my eval() to fail (be unsafe). But, if we count on program modifications to be doorways to exploits then we might as well just pull the plug. Bob. From leodp at yahoo.com Mon Jun 30 05:47:52 2008 From: leodp at yahoo.com (leodp) Date: Mon, 30 Jun 2008 02:47:52 -0700 (PDT) Subject: Getting sorting order References: <7cb9ebb7-e722-41e1-bdf2-693954a21b92@j22g2000hsf.googlegroups.com> Message-ID: > Or provide a better explanation and an example. Do you mean something like > this? > Hi Peter, a small example: master=[1,4,3,2] slave1=['d','c','b','a'] slave2=[1,2,3,4] master.sort() # this is ok, but does not return infos on how the list was sorted slave1.sort(key=_maybe_something_here_referring_to_master_) slave2.sort(key=_maybe_something_here_referring_to_master_) Then I should get: master=[1,2,3,4] slave1=['d','a','b','c'] slave2=[1,4,3,2] Hope it is more clear now. Thanks, leodp From rcdailey at gmail.com Tue Jun 3 18:32:07 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 3 Jun 2008 17:32:07 -0500 Subject: Continuous Timer In-Reply-To: <48456b96$0$17165$742ec2ed@news.sonic.net> References: <496954360805301850u4ce63746vc8fcc84ad1b72824@mail.gmail.com> <48456b96$0$17165$742ec2ed@news.sonic.net> Message-ID: <496954360806031532o306d6481rce476c4237645960@mail.gmail.com> I just need a repeating timer, I could care less about microsecond accuracies. On Tue, Jun 3, 2008 at 11:19 AM, John Nagle wrote: > Gabriel Genellina wrote: > >> En Fri, 30 May 2008 22:50:13 -0300, Robert Dailey >> escribi?: >> >> Reading through the Python 2.5 docs, I'm seeing a Timer class in the >>> threading module, however I cannot find a timer object that will >>> continuously call a function of my choice every XXXX amount of >>> milliseconds. >>> For example, every 1000 milliseconds I want a function named Foo to be >>> called. This would continue to happen until I terminate the timer in my >>> main >>> thread. Thanks for the help. >>> >> >> Use an Event object; its wait() will provide the sleep time, and when it >> is set() the thread knows it has to exit. >> >> import threading >> import time >> >> def repeat(event, every, action): >> while True: >> event.wait(every) >> if event.isSet(): >> break >> action() >> > > Actually, to do this right, it's necessary to account for the time used > by > "action". The code above will run no sooner than the time "every" after > the COMPLETION of action. > > I've done this sort of thing under QNX, the real-time operating system, > which has better timing primitives, and seen the action executed within > a few microseconds of the correct time, every time. But that was in C++. > > If you're trying to do hard real time in Python on Linux or Windows, > don't expect reliable timing. Remember, Python isn't really preemptive, > because of the global interpreter lock and the lack of thread priorities. > > John Nagle > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Tue Jun 3 11:07:24 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 03 Jun 2008 17:07:24 +0200 Subject: Webpy vs Django? In-Reply-To: <7db4dfb2-1e50-4a89-a47b-7356119b2741@r66g2000hsg.googlegroups.com> References: <7db4dfb2-1e50-4a89-a47b-7356119b2741@r66g2000hsg.googlegroups.com> Message-ID: <48455e01$0$11974$426a74cc@news.free.fr> circularfunc at yahoo.se a ?crit : > i have been trying to get Django running for 2 days now and it drives > me crazy. > > i played with webpy a bit and it is easy to get going with. but django > seems like once you have it all up and running it will be easier. > just that the barrier of entry is much higher. Django is indeed a bit more complex than webpy. > is django worth it? seems so ridicoulusly hard to get it running. i > run into trouble every time i advance a little, firstin the > installationa nd now in the tutorial(creating polls). I'm a bit surprised by your report of having problems running Django. Deploying it on production can be a pain sometimes (well... I don't like sys-admin stuff anyway...), but running Django on the builtin test server with SQLite or MySQL is almost OOTB. > > what do you think of webpy for big projects that need performance? Nothing. Never tried it. From bignose+hates-spam at benfinney.id.au Mon Jun 16 08:50:22 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 16 Jun 2008 22:50:22 +1000 Subject: sorted or .sort() ? References: <99b0cc1e-1fb5-4581-8094-e50274acc2e8@k37g2000hsf.googlegroups.com> Message-ID: <87k5gpee7l.fsf@benfinney.id.au> Peter Bengtsson writes: > My poor understanding is that the difference between `sorted(somelist, > key=lambda x:...)` and `somelist.sort(lambda x,y...)` is that one > returns a new list and the other sorts in-place. Yes. > Does that mean that .sort() is more efficient and should be favored > when you can (i.e. when you don't mind changing the listish object)? No, it means you should choose the version that expresses what you actually want to do. Efficiency of the programmers ? including the unknown number of programmers who will have to read the code after you write it ? is in many cases a much more important criterion than efficiency of the CPU. People's time continues to be much more expensive than computer time, after all. -- \ "Are you pondering what I'm pondering?" "Umm, I think so, | `\ Brain, but what if the chicken won't wear the nylons?" -- | _o__) _Pinky and The Brain_ | Ben Finney From bruno.desthuilliers at gmail.com Wed Jun 25 15:34:45 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 25 Jun 2008 12:34:45 -0700 (PDT) Subject: Notice For All pyHook users References: <7e8718e7-2c75-4120-9ba3-dbd1669100f5@a1g2000hsb.googlegroups.com> Message-ID: <872f92c4-f04b-48b3-bd54-6ecd3727ce3c@a70g2000hsh.googlegroups.com> On 25 juin, 19:47, Gandalf wrote: > If you want to compile your program the new py2exe release 0.6.8 wont > work! > the pyhook function will be ignored > > you'll have to uninstall the 0.6.8 version and to install the 0.6.6 > instead > > it took me 2 days to find the solution. > > maybe some day someone will bump the same problem and find this > message through google py2exe bugtracker is here: http://sourceforge.net/tracker/?atid=115583&group_id=15583&func=browse and there's a page on the wiki named ProblemsToBeFixed: http://www.py2exe.org/index.cgi/ProblemsToBeFixed From omer at no-log.org Wed Jun 25 09:02:07 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Wed, 25 Jun 2008 15:02:07 +0200 Subject: newb question on strings In-Reply-To: References: Message-ID: <200806251502.07418.omer@no-log.org> Le Tuesday 24 June 2008 22:27:33 regex_jedi, vous avez ?crit?: > ok, I have looked a lot of places, and can't seem to get a clear > answer... > > I have a string called > each_theme > > Some values of the string may contain a single quote as in - > Happy > Sad > Nice > Frank's Laundry > Explosion > > Notice that the 4th value has a single quote in it. Well, I need to > make sure that the single quote is escaped before handing it off for > further processing to a class I later call for some other processing. > > So I thought, no big deal, I should be able to find a way to escape > the single quote on the string. I am a perl and PHP guy, so I do a > lot of regex stuff. I did a quick search and found someone had said > to use this re.sub function, so I tried. But the following doesn't > work. To be honest, I am a little lost with all the modules and > classes required to do simple math or string functions in Python. > None of it seems built it in.. its all import modules... Here is what > I am trying... > > # escape single quotes in theme name > re.sub('''(['"])''', r'\\\1', each_theme) > No python has no builtin support for regexp like perl. There's nothing wrong with your code, you just need to import the 're' module. Add this at the beginning of your script: import re But imho escaping the quote in the first part would be more readable than using triple quotes: >>> name = "Frank's Laundry" >>> re.sub(r"([\"'])", r"\\\1", name) "Frank\\'s Laundry" You'll find a list of all the standard modules in the python docs, including this one: http://docs.python.org/modindex.html http://docs.python.org/lib/module-re.html -- C?dric Lucantis From jason.scheirer at gmail.com Mon Jun 16 18:11:44 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Mon, 16 Jun 2008 15:11:44 -0700 (PDT) Subject: Please explain Python "__whatever__" construct. References: <02c8f509-2889-433b-a548-62ead677bd19@p39g2000prm.googlegroups.com> Message-ID: <48d3c41d-2a17-4017-b6d4-bd0bb2c8b194@d45g2000hsc.googlegroups.com> On Jun 16, 2:56?pm, bsag... at gmail.com wrote: > After a couple of weeks studying Python, I already have a few useful > scripts, including one that downloads 1500 Yahoo stock quotes in 6 > seconds. However, many things are puzzling to me. I keep on seeing > things like "__main__" in scripts. ?A more obscure example would be > "__add__" used in string concatenation. For example, I can use "Hello > "+"world (or just "Hello" "world") to join those two words. But I can > also use "Hello ".__add__("world"). When and why would I ever use > "__main__" or the many other "__whatever__" constructs? http://docs.python.org/lib/genindex.html#letter-_ From __peter__ at web.de Fri Jun 13 02:33:58 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Jun 2008 08:33:58 +0200 Subject: Plotting Graphs + Bestfit lines References: <1a919a2b-6430-4e2e-a190-2e00e43a6138@25g2000hsx.googlegroups.com> Message-ID: arslanburney at gmail.com wrote: > Hello. Ive got two functions here. Somehow the program does not go in > to the second function wehn i call it. The bestfit function. Could > some1 help me identify the problem. Heres the code: Same problem as before, you have to keep the Gnuplot instance alive if you want to see the graph. Note that instead of for i in range(len(uinput)): sigmaxy = uinput[i][0] * uinput[i][1] + sigmaxy you could write for x, y in uinput: sigmaxy += x * y High time to take a look into a good Python tutorial... # --- combine.py --- import Gnuplot def bestfit(uinput): sigmax = sigmay = sigmaxy = sigmaxwhl = sigmaxsq = 0 for i in range(len(uinput)): n = len(uinput) sigmax = uinput[i][0] + sigmax sigmay = uinput[i][1] + sigmay sigmaxy = uinput[i][0] * uinput [i][1] + sigmaxy sigmaxwhl = sigmax * sigmax sigmaxsq = uinput[i][0] * uinput[i][0] + sigmaxsq sigmaxsigmay = sigmax * sigmay num = sigmaxsigmay - (n * sigmaxy) den = sigmaxwhl - (n* sigmaxsq) num2 = (sigmax * sigmaxy) - (sigmay * sigmaxsq) gradient = num / den intercept = num2 / den m = gradient c = intercept p = Gnuplot.Gnuplot() p.plot ('%f * x+%f'%(m,c)) return p def plot(original, expected, actual): gp = Gnuplot.Gnuplot() gp('set data style lines') # Make the plot items plot1 = Gnuplot.PlotItems.Data(original, title="Original") plot2 = Gnuplot.PlotItems.Data(expected, title="Expected") plot3 = Gnuplot.PlotItems.Data(actual, title="Acutal") gp.plot(plot1, plot2, plot3) return gp def show_plots(original, expected, actual): gp = combine.plot( original, expected, actual) raw_input("first") gp = combine.bestfit(expected) raw_input("second") gp = combine.bestfit(actual) raw_input("third") # --- combine_main.py --- import combine combine.show_plots([(2,3), (4,8), (5,9), (6,2)], [(1,7), (3,3), (4,5), (5,6)], [(1,3), (3,10), (4,8), (7,9) ] ) From ppearson at nowhere.invalid Sun Jun 22 22:41:53 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: Sun, 22 Jun 2008 21:41:53 -0500 Subject: Tkinter canvas drag/drop obstacle References: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> Message-ID: On Fri, 20 Jun 2008 13:41:35 -0300, Guilherme Polo wrote: > On Fri, Jun 20, 2008 at 1:11 PM, Peter Pearson wrote: >> Tkinter makes it very easy to drag jpeg images around on a >> canvas, but I would like to have a "target" change color when >> the cursor dragging an image passes over it. I seem to be >> blocked by the fact that the callbacks that might tell the >> target that the mouse has entered it (, , >> even ) aren't called if the mouse's button is down. >> What am I missing? Have I failed to find the right Tkinter >> document? Is Tkinter the wrong tool for this job? Thanks. >> > > I believe the only way to achieve this is binding to the > entire canvas, then checking if the x, y coords are inside the > "target". Ugh. OK, thanks. -- To email me, substitute nowhere->spamcop, invalid->net. From deets at nospam.web.de Fri Jun 13 11:07:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 13 Jun 2008 17:07:30 +0200 Subject: weird iteration/assignment problem In-Reply-To: <61936860-de3f-4bb1-8806-08f9f21ad113@m36g2000hse.googlegroups.com> References: <61936860-de3f-4bb1-8806-08f9f21ad113@m36g2000hse.googlegroups.com> Message-ID: <6bfgpoF3bpl84U1@mid.uni-berlin.de> cirfu schrieb: > for i in xrange(0, len(texts)): > texts[i] = "yes" > > for i in texts: > i = "no" > > why is the first one working but not the second. i mean i see why the > firts one works but i dont udnerstand why the second doesnt. Because in the second you only bind the contents of texts to a name i. But that doesn't mean that i magically became an "alias" for texts[index] - it just happens to point at the same object. To accomplish what you want, the pythonic idiom is to use enumerate: for i, text in enumerate(texts): text[i] = "yes" Diez From dmitrey.kroshko at scipy.org Thu Jun 12 14:04:39 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Thu, 12 Jun 2008 11:04:39 -0700 (PDT) Subject: howto split string with both comma and semicolon delimiters Message-ID: <3e2540ab-1d2a-45a5-a5b6-3f7ae7a4efac@x35g2000hsb.googlegroups.com> hi all, howto split string with both comma and semicolon delimiters? i.e. (for example) get ['a','b','c'] from string "a,b;c" I have tried s.split(',;') but it don't work Thx, D. From cwitts at gmail.com Tue Jun 17 04:17:30 2008 From: cwitts at gmail.com (Chris) Date: Tue, 17 Jun 2008 01:17:30 -0700 (PDT) Subject: print problem References: <2MWdnYXqCY3yy8rVnZ2dnUVZ_sbinZ2d@posted.internode> Message-ID: On Jun 17, 8:15?am, pirata wrote: > I was trying to print a dot on console every second to indicates > running process, so I wrote, for example: > > for i in xrange(10): > ? ? print ".", > ? ? time.sleep(1) > > Idealy, a dot will be printed out each second. But there is nothing > print out until after 10 seconds, all 10 dots come out together. > > I've tried lose the comma in the print statement, and it works. > > Is that because of the print statement buffer the characters until > there is a new line character? > > Thanks import sys for i in xrange(10): sys.stdout.write('.') sys.stdout.flush() From pscott at uwc.ac.za Fri Jun 6 06:57:52 2008 From: pscott at uwc.ac.za (Paul Scott) Date: Fri, 06 Jun 2008 12:57:52 +0200 Subject: Convert Word .doc to Acrobat .pdf files In-Reply-To: <1dc26c3a0806060352k442475ccp6716b713268c161a@mail.gmail.com> References: <1dc26c3a0806060352k442475ccp6716b713268c161a@mail.gmail.com> Message-ID: <1212749872.6200.30.camel@paul-laptop> On Fri, 2008-06-06 at 16:22 +0530, Dinil Karun wrote: > hi, > > I am using the below code but i am getting a error saying pyUno module > not found. > can u please help. I just wrote the same thing! Take a look at http://cvs2.uwc.ac.za/trac/python_tools/browser/oooconv It should do what you want (and a little more). Sorry, the code quality is pretty bad, but I am in the process of cleaning it up still. --Paul -------------- next part -------------- All Email originating from UWC is covered by disclaimer http://www.uwc.ac.za/portal/public/portal_services/disclaimer.htm From fc14301589 at icqmail.com Sun Jun 15 05:58:24 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Sun, 15 Jun 2008 17:58:24 +0800 Subject: Configuration files References: <485419f0$0$5958$e4fe514c@dreader16.news.xs4all.nl> Message-ID: <4854e7c0_2@news.tm.net.my> On 04:11, domenica 15 giugno 2008 Daniel Fetchinson wrote: > Check this out: http://www.voidspace.org.uk/python/configobj.html > Let me add: cfgparse, iniparse I've look at all to find a simple solution for my interest, but I realized not a good result. I'm using three of them ConfigParser, cfgparse and optparse. Just to let read a configuration file and let user to subclass option at the console. If I'll get experienced by cfgparse I think I'll drop ConfigParser, because I'd like the idea to override file rules on console. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From deets at nospam.web.de Wed Jun 11 13:45:05 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 11 Jun 2008 19:45:05 +0200 Subject: question about import In-Reply-To: <886765d0-2be7-4a66-b838-032aebae0622@d1g2000hsg.googlegroups.com> References: <886765d0-2be7-4a66-b838-032aebae0622@d1g2000hsg.googlegroups.com> Message-ID: <6bah94F3b327sU1@mid.uni-berlin.de> Jonathan Vanasco schrieb: > I'm a little unclear about import / __import__ > > I'm exploring dynamically importing modules for a project, and ran > into this behavior > > works as expected: > app = __import__( myapp ) > appModel = __import__( myapp.model ) > > but... > appname= 'myapp' > app = __import__( "%s" % appname ) > appModel = __import__( "%s.model" % appname ) > > In the latter example, app and appModel will always seem to be > imported as 'myapp' , and I've yet to find a way to address the .model > namespace > > I know 'dynamically importing modules' is cursed upon -- and I'm > likely rewriting hundreds of line of codes so I can work around this > with a registration system -- however I'd like to understand why this > occurs and know if what i'm trying is even possible. Is it cursed upon? Didn't know that. However, __import__ only gives you the topmost module - in your case myapp. So you need to do it like this (untested): name = "a.b.c.d" mod = __import__(name) for part in name.split(".")[1:]: mod = getattr(mod, part) print mod Diez From noorhanabbas at yahoo.co.uk Thu Jun 5 12:19:51 2008 From: noorhanabbas at yahoo.co.uk (Noorhan Abbas) Date: Thu, 5 Jun 2008 16:19:51 +0000 (GMT) Subject: Loading Python programs on the net. Message-ID: <965558.33707.qm@web27401.mail.ukl.yahoo.com> Hello, I have developed a program in Python.? I need to put this program on the web. Could somebody advice me on the different tools that I can use to do this job. My python program basically displays a tree ctrl that allows users to choose from it and displays text as an output.? I need to develop a web page that displays this tree ctrl and accesses the text files to produce the output. Thank you very much, Nora. __________________________________________________________ Sent from Yahoo! Mail. A Smarter Email http://uk.docs.yahoo.com/nowyoucan.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From stdenton at sbcglobal.net Sat Jun 7 12:24:26 2008 From: stdenton at sbcglobal.net (Sam Denton) Date: Sat, 07 Jun 2008 11:24:26 -0500 Subject: Python and Flaming Thunder In-Reply-To: <4847ecf6$0$25178$c3e8da3@news.astraweb.com> References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <4847ecf6$0$25178$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > "Dave Parker" wrote in message > news:a95c09d9-94c3-4dac-9439-9176038d93d9 at w8g2000prd.googlegroups.com... > On May 20, 7:05 pm, Collin wrote: > > --- > For example, consider the two statements: > > x = 8 > x = 10 > > The reaction from most math teachers (and kids) was "one of those is > wrong because x can't equal 2 different things at the same time". > --- > > Aw, come on. I'm a novice programmer but even after reading the most basic > of introductions to a programming language I can tell that x is being > assigned one value, then another. I've long believed that '=' should be banned from programming languages. Use '==' for equality tests, and ':=' for assignments. From socyl at 987jk.com.invalid Fri Jun 13 12:05:06 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 13 Jun 2008 16:05:06 +0000 (UTC) Subject: Python noob's simple config problem References: Message-ID: In =?iso-8859-1?q?Robin_K=E5veland?= Hansen writes: >On Thu, 12 Jun 2008 21:32:34 +0000, kj wrote: >> I'm sure this is a simple, but recurrent, problem for which I can't hit >> on a totally satisfactory solution. >> >> As an example, suppose that I want write a module X that performs some >> database access. I expect that 99.999% of the time, during the >> foreseeable future, the database connection parameters will remain >> unchanged. The only exception that I envision for this would be during >> testing or debugging. >> >> Given all this, I am tempted to turn these connection parameters into >> hard-coded module attributes that I can always override (i.e. overwrite) >> when necessary. >> >> But for as long as I can remember the dogma has been that hard-coded >> values are bad, and that one should use other techniques, such as >> configuration files, or parameters to a suitable constructor, etc. >> >> This is where I begin to get confused: whose responsibility is it to >> know of and read the config file? I can think of two distinct >> scenarios: 1) module X is being used by a large, full-fledged >> application A that already uses a config file for its own configuration; >> 2) module X is being used by a simple script that has no need for a >> config file. In case 1 I'd be glad to let application A set module X's >> connection parameters using values read from its own (i.e. A's) config >> file; this minimizes the number of config files that need to be >> maintained. In case 2, however, it would be preferable for module X to >> read its connection params from its own (i.e. X's) config file. In this >> way the script won't have to bother setting some parameters that are in >> fact practically constant... >> >> After going round and round on this, my original idea of hard-coding the >> values as module attributes begins to look pretty attractive again. >> >> How would you handle such situations? >> >> Thanks! >> >> kynn >I think I would just abstract it away with a "getter" for the connection, >a function that takes some optional parameters, if not supplied, it >simply fetches them from a default configuration. Ie: >def connect(params=None): > if params is None: > return dblayer.connect(conf["default"]) > else: > return dblayer.connect(params) >Unless I have misunderstood you completely? Now people can change your >scripts config file, and if someone wants to use your code, they can use >the getter directly. >I hope this is of some help. Thanks! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From gh at ghaering.de Tue Jun 3 11:10:39 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 03 Jun 2008 17:10:39 +0200 Subject: UTC datetime.fromtimestamp In-Reply-To: References: Message-ID: Alok Kumar wrote: > Dear All, > > I have UTC datetime as > datetime.fromtimestamp(ParseDateTimeUTC("2007-12-06 20:37:05")) Just datetime.timedelta(days=1). -- Gerhard From paul at boddie.org.uk Thu Jun 19 05:17:13 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 19 Jun 2008 02:17:13 -0700 (PDT) Subject: Combining music or video files? References: <4855d5a5$0$11609$607ed4bc@cv.net> Message-ID: On 16 Jun, 04:53, John Salerno wrote: > Before I try this and destroy my computer :) I just wanted to see if > this would even work at all. Is it possible to read a binary file such > as an mp3 or an avi, put its contents into a new file, then read another > such file and append its contents to this same new file as well, thereby > making, for example, a single long video instead of two smaller ones? Probably not, as people have pointed out, but I imagine you could use GStreamer and a few processing pipelines, as I pointed out in a comment on the following article (for another task): http://jessenoller.com/2008/05/06/lazyweb-question-python-video-manipulation-libraries/ This is probably as close as you can get to treating the files as if they were simple things which can be concatenated. Paul From wmcbrine at users.sf.net Sun Jun 22 20:01:16 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Mon, 23 Jun 2008 00:01:16 GMT Subject: Learning Python: Code critique please References: <2f25e0ae-5828-4651-8ac6-55ba8bb50089@p25g2000pri.googlegroups.com> Message-ID: On Sun, 22 Jun 2008 08:44:25 -0500, Saul Spatz wrote: > macoovacany wrote: >> http://macoovacany.wordpress.com/ > When I tried to run it, I got all kinds of syntax errors because of > non-ASCII characters; namely, you have fancy left and right single and > double quotes. That's probably WordPress' doing. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From apardon at forel.vub.ac.be Mon Jun 2 05:38:43 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 2 Jun 2008 09:38:43 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> Message-ID: On 2008-05-24, Sh4wn wrote: > Hi, > > first, python is one of my fav languages, and i'll definitely keep > developing with it. But, there's 1 one thing what I -really- miss: > data hiding. I know member vars are private when you prefix them with > 2 underscores, but I hate prefixing my vars, I'd rather add a keyword > before it. > > Python advertises himself as a full OOP language, but why does it miss > one of the basic principles of OOP? Will it ever be added to python? > > Thanks in advance, > Lucas If you really need it, you can do data hiding in python. It just requires a bit more work. ----------------------------- Hide.py --------------------------------- class Rec(object): def __init__(__, **kwargs): for key,value in kwargs.items(): setattr(__, key, value) def __getitem__(self, key): return getattr(self, key) def __setitem__ (self, key, val): setattr(self, key, val) class Foo(object): def __init__(self): hidden = Rec(x=0, y=0) def SetX(val): hidden.x = val def SetY(val): hidden.y = val def GetX(): return hidden.x def GetY(): return hidden.y self.SetX = SetX self.SetY = SetY self.GetX = GetX self.GetY = GetY -------------------------------------------------------------------------- $ python Python 2.5.2 (r252:60911, Apr 17 2008, 13:15:05) [GCC 4.2.3 (Debian 4.2.3-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> From Hide import Foo >>> var = Foo() >>> var.GetX() 0 >>> var.SetX(5) >>> var.GetX() 5 >>> var.x Traceback (most recent call last): File "", line 1, in AttributeError: 'Foo' object has no attribute 'x' >>> var.hidden.x Traceback (most recent call last): File "", line 1, in AttributeError: 'Foo' object has no attribute 'hidden' -- Antoon Pardon From tilmaniac at gmail.com Fri Jun 6 17:13:16 2008 From: tilmaniac at gmail.com (Tilman Kispersky) Date: Fri, 6 Jun 2008 14:13:16 -0700 (PDT) Subject: Macro like functionality for shorthand variable names Message-ID: I have python code in a class method translated from C++ that looks sort of like this: >>> self.dydt[1] = self.a * (self.b * self.y[0] - self.y[1]) To make this more readable in C++ I had made macros to achieve this: #define du (dydt[1]) #define u (y[1]) #define V (y[0]) du = a * (b * V - u); I realize the value of not having macros in Python. They've tripped me up more than once in C++. My question is: Is there any way to write a shorterhand more readable version of the python code above? I'm doing several calculations one after the other and some of the lines are quite long. From matthieu.brucher at gmail.com Sat Jun 14 09:54:24 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Sat, 14 Jun 2008 15:54:24 +0200 Subject: Platform independent code? In-Reply-To: References: Message-ID: Hi, Python is a platform independent language, period. You can always excute a Python script with python script.py. Now, with Windows, you can execute the script by doucle-clicking on it. With Linux, it's different, you have to use the shebang line to execute a script with the correct interpreter. But this has nothing to do with the fact that Python is a platform independent language. Some modules may not be available on all platform, for the answer to this question, see the documentation of the module ;) Matthieu 2008/6/14 saneman : > I have read that Python is a platform independent language. But on this > page: > > http://docs.python.org/tut/node4.html#SECTION004220000000000000000 > > it seems that making a python script executable is platform dependant: > > 2.2.2 Executable Python Scripts > On BSD'ish Unix systems, Python scripts can be made directly executable, > like shell scripts, by putting the line > > > #! /usr/bin/env python > (assuming that the interpreter is on the user's PATH) at the beginning of > the script and giving the file an executable mode. The "#!" must be the > first two characters of the file. On some platforms, this first line must > end with a Unix-style line ending ("\n"), not a Mac OS ("\r") or Windows > ("\r\n") line ending. Note that the hash, or pound, character, "#", is used > to start a comment in Python. > > The script can be given an executable mode, or permission, using the chmod > command: > > > $ chmod +x myscript.py > > > > Are there any guidelines (API'S) that gurantees that the python code will be > platform independent? > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher From ubikvist at gmail.com Mon Jun 23 05:33:36 2008 From: ubikvist at gmail.com (ubikvist) Date: Mon, 23 Jun 2008 02:33:36 -0700 (PDT) Subject: Learning Python in a group References: <507738ef0806220343r3e9ea053neeec0baf0ccfdbe6@mail.gmail.com> <18c1e6480806220422x5d06c54byd23b249bb699691f@mail.gmail.com> <507738ef0806220452s74358615v44518469cf3b5f45@mail.gmail.com> <18c1e6480806220511s5117aef4gb4ec93bceb44a0ac@mail.gmail.com> Message-ID: <337ab3f9-5334-4737-baac-fded524e6d99@s50g2000hsb.googlegroups.com> I guess it's time to choose what a project your group will work at. Personally, I'm working at the project relating to text analysis, but it's rather specific because I use Russian texts. So, maybe we should to choose more 'international' implementation. -Ed From tjreedy at udel.edu Thu Jun 5 16:40:44 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 5 Jun 2008 16:40:44 -0400 Subject: line continuation for lines ending in "and" or "or" References: <90ee8b5d-1509-4463-aaab-f712f7e72d4b@j33g2000pri.googlegroups.com> <0d723e6d-f81b-4545-b406-fc60b20c5433@u6g2000prc.googlegroups.com> Message-ID: "Russ P." wrote in message news:0d723e6d-f81b-4545-b406-fc60b20c5433 at u6g2000prc.googlegroups.com... |. Well, it wouldn't be a bad idea for Python to do | what I thought it did, *plus* what I said it ought to do. A line ending in an operator is ambiguous in that it *could* indicate that the programmer intends to continue on the next line while it also could indicate that the programmer forgot to finish before hitting return, or that something got erased but not replaced. Moreover, the second possibility is actual (it actually happens) and not just theoretical. Moreover, the next line realistically could 'complete' the incomplete line 'by accident', so that the syntax bug would not get flagged. In such situations, some might lean toward the plausible guess choice, but Guido leans in the direction of choosing the bug interpretation. So he included the '\' mechanism. It is already used in strings to mean "do not take the next char literally", so having it mean "do not take the following end-of-line literally" is only a tiny step. Terry Jan Reedy From enlighten.power at gmail.com Fri Jun 6 21:20:00 2008 From: enlighten.power at gmail.com (Golu) Date: Fri, 6 Jun 2008 18:20:00 -0700 (PDT) Subject: need really help Message-ID: respected please help me i am really need of money please pay me through donation from my site. http://www.computersolution.co.cc i will be very thankful to you . please donate atleast 5$ or 2$ through my site http://www.computersolution.co.cc hope i will be able to clear my debts because of you all From stef.mientki at gmail.com Sun Jun 29 17:03:19 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 29 Jun 2008 23:03:19 +0200 Subject: list extension ? Message-ID: <4867F897.3020306@gmail.com> hello, I basically need a list with a few extra attributes, so I derived a new object from a list, and it works perfect. But I wonder why the newly derived list component is much more flexible ? # so here is the new list object class tGrid_List ( list ) : def __init__ ( self, value = [] ) : list.__init__ ( self, value ) # and with this new list component, I can add new attributes on the fly a = tGrid_list ( [ 2, 3 ] ) a.New_Attribute = 'some text' # I'm not allowed to this with the standard list a = [ 2, 3 ] a.New_Attribute = 'some text' <== ERROR Can someone explain this different behavior ? thanks, Stef Mientki From cjw at ncf.ca Mon Jun 23 10:38:57 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 23 Jun 2008 10:38:57 -0400 Subject: PyOpenGL New Installation Message-ID: I have just installed PyOpenGL and get a series of warning messages: Best match: PyOpenGL 3.0.0b3 Downloading http://downloads.sourceforge.net/pyopengl/PyOpenGL-3.0.0b3.zip?modtime=1213363873&big_mirror=0 Processing PyOpenGL-3.0.0b3.zip Running PyOpenGL-3.0.0b3\setup.py -q bdist_egg --dist-dir c:\docume~1\cjw\locals~1\temp\easy_install-hjyff7\PyOpenGL-3.0.0b3\egg-dist-tmp-iqd53p warning: no previously-included files matching '*.odt' found anywhere in distribution warning: no previously-included files matching '*.odp' found anywhere in distribution warning: no previously-included files matching '.cvsignore' found anywhere in distribution warning: no previously-included files matching '*.diff' found anywhere in distribution warning: no previously-included files found matching 'src\*.h' warning: no previously-included files found matching 'src\*.xml' warning: no previously-included files found matching 'src\*.zip' Adding pyopengl 3.0.0b3 to easy-install.pth file Installed c:\python25\lib\site-packages\pyopengl-3.0.0b3-py2.5.egg Processing dependencies for PyOpenGL Finished processing dependencies for PyOpenGL Could someone please advise the significance of these messages? Colin W. From alexnbryan at gmail.com Mon Jun 23 12:07:48 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Mon, 23 Jun 2008 11:07:48 -0500 Subject: Going from Tkinter to pyQT Message-ID: I had a guy on this mailing list tell me that pyQT is much better than Tkinter, and after looking into it a bit I think he is right. However, I can't find much on it. I want to know if there are any good books or online tutorials that would be helpful. I doubt there is one, but if there is one on going from Tkinter to pyQT, that would be amazing. Well if any of you guys have any tips or suggestions on any of this I would appreciate it. From bkasterm at gmail.com Sat Jun 21 16:49:38 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Sat, 21 Jun 2008 13:49:38 -0700 (PDT) Subject: String Concatenation O(n^2) (was: Re: Explaining Implementing a Binary Search Tree.) References: Message-ID: On Jun 17, 1:01?am, "Gabriel Genellina" wrote: > En Mon, 16 Jun 2008 07:34:06 -0300, Bart Kastermans escribi?: > > > Summary: can't verify big O claim, how to properly time this? > > > This is interesting. ?I had never attempted to verify a big O > > statement > > before, and decided that it would be worth trying. ?So I wrote some > > code to > > collect data, and I can't find that it goes quadratic. > > In your test code, you're concatenating only two strings, that's a *single* operation, and takes time proportional to the total length. > The quadratic behavior appears when you do *several* concatenations in a row (like in your original code, where += was used several times to build a result). > If you want to verify it, try joining N strings of size M (for varying values of N and M), and plot total time vs. N (for a given M value), and total time vs. M (for a given N value) and finally total time vs. (N*M), see what happens and post your findings again. > > -- > Gabriel Genellina I did the work and found that for trees it does not go quadratic at all, from the computations you suggest it is easy to get quadratic behavior though. Also this does not depend in any way I can see on the implementation by Python. Actual time might certainly improve by doing it differently (changing the constants), but the big O results won't. For pictures and math I have put it up on my blog again see: http://kasterma.wordpress.com/2008/06/21/complexity-of-string-concatenation-ii/ Thanks to everyone who commented so far on this subject. I had some good fun with it so far. Best, Bart From sjmachin at lexicon.net Sat Jun 21 10:29:40 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 21 Jun 2008 07:29:40 -0700 (PDT) Subject: Getting column names from a cursor using ODBC module? References: Message-ID: On Jun 22, 12:19 am, John Machin wrote: > On Jun 21, 11:58 pm, dana... at yahoo.com wrote: > > > Is there any way to retrieve column names from a cursor using the ODBC > > module? Or must I, in advance, create a dictionary of column position > > and column names for a particular table before I can access column > > values by column names? I'd prefer sticking with the ODBC module for > > now because it comes standard in Python. > > > I'm using Python 2.4 at the moment. > > Do you mean the odbc module? If so, it doesn't come standard in > Python; it's part of the win32 package. > > I haven't used it for years -- my preference on Windows these days > would be mxODBC if the client would pay the licence fee, otherwise > pyodbc. Sorry I'm not answering your question ... perhaps you should > be asking a different question :) > > Cheers, > John But to help you answer your question: if the module that you are using supports the 2.0 version of the database API (see http://www.python.org/dev/peps/pep-0249/), then it will support the cursor.description attribute, which gives you not only the name but the type and 5 other bits of info about each column. If it doesn't, I'd suggest moving on. HTH, John From bruno.42.desthuilliers at websiteburo.invalid Thu Jun 12 05:47:05 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 12 Jun 2008 11:47:05 +0200 Subject: My fight with classes :) In-Reply-To: <4850d287_2@news.tm.net.my> References: <484fde63_1@news.tm.net.my> <4850d287_2@news.tm.net.my> Message-ID: <4850f03a$0$17485$426a74cc@news.free.fr> TheSaint a ?crit : > On 04:51, gioved? 12 giugno 2008 Terry Reedy wrote: > > First of all a big thank you, all. > >> def makeappender(): >> data = ['',''] >> def appender(val): >> >> return appender > > I'll give it a try. I just doubting if the data will be shared outside the > function. Each time makeappender is called, it returns a new appender function object with it's own 'data' object. So 'data' won't be shared between different instances of the appender function. > Actually, my practice goes to send all variables to the functions and > expecting a returned value. Mostly a sane, sound and sensible approach IMHO - but doesn't work that well when the function needs to maintain own state between calls. > Usually I'm not relying on that module's > variables are read inside a function. Probably I got wrong learning or > experiences. As long as you only *read* module's globals from within a function, that's mostly ok. When you start *writing* them it may be time to reconsider the design (not that it's necessarily bad, but it's a possible signal that something is wrong). >> For multiple functions, use classes. Well... Closures are poor men's objects, or so they say (or is that the other way round ?-). def make_person(name, age): state = dict(name=name, age=age) def set_name(new_name=None): state['name'] = new_name def get_name(): return state['name'] def grow(): state['age'] += 1 def get_age() return state['age'] return set_name, get_name, grow, get_age (toto_set_name, toto_get_name, toto_grow, toto_get_age) = make_person('toto', 42) A bit cumbersome, indeed !-) From nicola.musatti at gmail.com Wed Jun 4 05:26:11 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Wed, 4 Jun 2008 02:26:11 -0700 (PDT) Subject: Help need with subprocess communicate References: <0312b7e9-bffe-4360-bf3a-f5b3b26d243d@l64g2000hse.googlegroups.com> Message-ID: On Jun 3, 11:04 pm, rdab... at gmail.com wrote: > I'm trying to perform following type of operation from inside a python > script. > 1. Open an application shell (basically a tcl ) > 2. Run some commands on that shell and get outputs from each command > 3. Close the shell [...] > Following is my code: > > from subprocess import * > p2 = Popen('qdl_tcl',stdin=PIPE,stdout=PIPE) > o,e = p2.communicate(input='qdl_help \n qdl_read \n > qdl_reg_group_list ') > > Please suggest a way to perform it interactively with killing the > process each time I want to communicate with it. Here's what you need: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 Cheers, Nicola Musatti From morton.thomas at googlemail.com Mon Jun 9 08:02:44 2008 From: morton.thomas at googlemail.com (Thomas Morton) Date: Mon, 9 Jun 2008 13:02:44 +0100 Subject: Getting current screen resolution Message-ID: <8e02cf540806090502q427f22b6h4fb85bbe14736e76@mail.gmail.com> This is a "thing" that has been annoying me all morning: and I can't work out how to do it. I need a way to get the DPI or screen resolution of the monitor that a script is currently runnign on. I have a way in Windows but it doesnt port to Unix (which is important). Any ideas? -- Thomas Morton Lead Developer || Founder TomNRob Web Services www.tomnrob.com From http Mon Jun 2 20:11:16 2008 From: http (Paul Rubin) Date: 02 Jun 2008 17:11:16 -0700 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> Message-ID: <7xhccbe5sr.fsf@ruckus.brouhaha.com> "Russ P." writes: > I also realize, by the way, that Python allows a client of a class to > define a new class member from completely outside the class > definition. Obviously, that cannot be declared private. This is bogus about 95% of the time though. For the cases where it is really desired, I think it's best to require the target class to be enable it specifically somehow, maybe by inheriting from a special superclass. That could let the compiler statically resolve member lookups the rest of the time. From Sengly.Heng at gmail.com Sat Jun 7 15:14:29 2008 From: Sengly.Heng at gmail.com (Sengly) Date: Sat, 7 Jun 2008 12:14:29 -0700 (PDT) Subject: simple question on list manipulation from a newbie Message-ID: <76ccc0a8-90de-4717-9e6f-06836827b1e1@i18g2000prn.googlegroups.com> Dear all, I am working with wordnet and I am a python newbie. I'd like to know how can I transfer a list below In [69]: dog Out[69]: [{noun: dog, domestic_dog, Canis_familiaris}, {noun: frump, dog}, {noun: dog}, {noun: cad, bounder, blackguard, dog, hound, heel}, {noun: frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, weenie}, {noun: pawl, detent, click, dog}, {noun: andiron, firedog, dog, dog-iron}] to a list like this with python: [dog, domestic_dog, Canis_familiaris, frump, dog, dog, cad, bounder, blackguard, dog, hound, heel, frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, weenie}, pawl, detent, click, dog}, andiron, firedog, dog, dog-iron] Thank you. Sengly From tjreedy at udel.edu Sun Jun 29 14:35:57 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 29 Jun 2008 14:35:57 -0400 Subject: Why is recursion so slow? In-Reply-To: <5504f9ac0806290703h1bf44639jbfe5331c4a2d1369@mail.gmail.com> References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> <5504f9ac0806290703h1bf44639jbfe5331c4a2d1369@mail.gmail.com> Message-ID: Dan Upton wrote: > On Sun, Jun 29, 2008 at 1:27 AM, Terry Reedy wrote: >> >> slix wrote: >>> Recursion is awesome for writing some functions, like searching trees >>> etc but wow how can it be THAT much slower for computing fibonacci- >>> numbers? >> The comparison below has nothing to do with recursion versus iteration. (It >> is a common myth.) You (as have others) are comparing an exponential, >> O(1.6**n), algorithm with a linear, O(n), algorithm. >> > > FWIW, though, it's entirely possible for a recursive algorithm with > the same asymptotic runtime to be wall-clock slower, just because of > all the extra work involved in setting up and tearing down stack > frames and executing call/return instructions. Which is exactly why I continued with "In Python, an algorithm written with iteration is faster than the same algorithm written with recursion because of the cost of function calls. But the difference should be a multiplicative factor that is nearly constant for different n. (I plan to do experiments to pin this down better.) Consequently, algorithms that can easily be written iteratively, especially using for loops, usually are in Python programs." People should read posts to the end before replying, in case it actually says what one thinks it should, but just in a different order than one expected. If each call does only a small amount of work, as with fib(), I would guess that time difference might be a factor of 2. As I said, I might do some measurement sometime in order to get a better handle on when rewriting recursion as iteration is worthwhile. tjr From Lie.1296 at gmail.com Sun Jun 15 13:22:02 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 15 Jun 2008 10:22:02 -0700 (PDT) Subject: Creating a TCP/IP connection on already-networked computers References: <4853f269$0$11615$607ed4bc@cv.net> Message-ID: <32dc420e-4a54-4665-95e8-0978a529ede1@v26g2000prm.googlegroups.com> On Jun 14, 11:31?pm, John Salerno wrote: > Let me see if this question even makes sense...I'm reading Core Python > Programming and I jumped ahead to the more specific topics like network > programming. I plan to follow along with the example in that chapter and > create a socket connection between my desktop and laptop. > > However, these two computers are already connected on my home network > (using the Windows Network Setup Wizard), so I was wondering if this > will have any effect on what I might try to do with Python. In other > words, if the program I write actually works and allows the two > computers to speak to each other, will that be a result purely of the > program, or will it have anything to do with the fact that they are > already on a home network together? (i.e. there's another variable in play?) > > Thanks. The Windows Network Wizard is a poor abstraction to set up layer 3 and 4 (the TCP/IP and lower) and layer 5 (the file sharing). You don't need to run this wizard if you've set up your TCP/IP and lower correctly manually (which, according to me, is easier than using the wizard). In a normal situation, you shouldn't need to worry about setting up the layer 3 and 4, you can assume that this two already set up. Some problem lies when connecting two computers through internet, such as you may have to use external IP address or set up port forwarding on the server-side. This is due to the use of 192.168.xxx.xxx as inside-LAN IP address instead of letting each device on the whole world has their own IP address. From spamtrap at dot-app.org Mon Jun 30 13:49:32 2008 From: spamtrap at dot-app.org (Sherman Pendley) Date: Mon, 30 Jun 2008 13:49:32 -0400 Subject: perl + python tutorial available for download References: <86c4090b-ed0b-4249-b3ee-517c94328741@z32g2000prh.googlegroups.com> <31f90$486914df$11268@news.teranews.com> Message-ID: smallpond writes: > "Pyhton" ?? > > typical Both typical, and illustrative of Xah's skill level. :-) sherm-- -- My blog: http://shermspace.blogspot.com Cocoa programming in Perl: http://camelbones.sourceforge.net From pavel.uvarov at gmail.com Mon Jun 2 11:19:05 2008 From: pavel.uvarov at gmail.com (pavel.uvarov at gmail.com) Date: Mon, 2 Jun 2008 08:19:05 -0700 (PDT) Subject: ThreadPoolingMixIn References: <3d9dac72-ce4d-4ce5-9213-4bb17aff2f9e@r66g2000hsg.googlegroups.com> <1c4d113e-b375-471d-9d54-1401c8844352@t12g2000prg.googlegroups.com> Message-ID: <3ac90c85-e4a0-4564-afbc-df8eec131347@d77g2000hsb.googlegroups.com> On Jun 2, 7:09 pm, pavel.uva... at gmail.com wrote: > On May 31, 9:13 pm, Rhamphoryncus wrote: > > > On May 30, 2:40 pm, pavel.uva... at gmail.com wrote: > > > > Hi, everybody! > > > > I wrote a useful class ThreadPoolingMixIn which can be used to create > > > fast thread-based servers. This mix-in works much faster than > > > ThreadingMixIn because it doesn't create a new thread on each request. > > > Do you have any benchmarks demonstrating the performance difference/ > > To benchmark this I used a simple tcp server which writes a small > (16k) > string to the client and closes the connection. > > I started 100 remote clients and got 500 replies/s for ThreadingMixIn > and more than 1500 replies/s for ThreadPoolingMixIn. I tested it on > FreeBSD 6.2 amd64. > > I'm very curious about the exactness of the number 500 for > ThreadingMixIn. It seems to be the same for various packet sizes. > I suspect there is some OS limit on thread creating rate. > > Below I include a bugfixed ThreadPoolingMixIn and the benchmarking > utility. The utility can be used to start clients on localhost, though > the reply rate will be slower (around 1000 replies/s). > > To start benchmarking server with localhost clients use: > python ./TestServer.py --server=threading --n-clients=100 > or > python ./TestServer.py --server=threadpooling --n-clients=100 I've just tested it on a linux box and got a 240 replies/s vs 2000 replies/s, that is 8x performance improvement. From eliben at gmail.com Mon Jun 23 00:44:55 2008 From: eliben at gmail.com (eliben) Date: Sun, 22 Jun 2008 21:44:55 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> Message-ID: <7c81f724-6c4a-4b5f-9e8a-e4cdb01a9293@2g2000hsn.googlegroups.com> Thanks for all the replies in this post. Just to conclude, I want to post a piece of code I wrote to encapsulate function creation in this way: def create_function(code): """ Create and return the function defined in code. """ m = re.match('\s*def\s+([a-zA-Z_]\w*)\s*\(', code) if m: func_name = m.group(1) else: return None d = {} exec code.strip() in globals(), d return d[func_name] Although the 'def' matching in the beginning looks a bit shoddy at first, it should work in all cases. Eli From pataphor at gmail.com Thu Jun 5 05:02:10 2008 From: pataphor at gmail.com (pataphor) Date: Thu, 5 Jun 2008 11:02:10 +0200 Subject: multiprocessing module (PEP 371) References: <877a5774-d3cc-49d3-bb64-5cab8505a419@m3g2000hsc.googlegroups.com> Message-ID: In article <877a5774-d3cc-49d3-bb64-5cab8505a419 @m3g2000hsc.googlegroups.com>, sturlamolden at yahoo.no says... > I don't see pyprocessing as a drop-in replacement for the threading > module. Multi-threading and multi-processing code tend to be > different, unless something like mutable objects in shared memory is > used as well (cf. Python Shared Objects). If this limitation can > educate Python programmers to use queues instead of locks and mutable > objects, even multi-threaded Python programs may actually benefit. > Some API differences between threading and multiprocessing do not > matter. Programmers should not consider processes as a drop-in > replacement for threads. This is probably not very central to the main intention of your post, but I see a terminology problem coming up here. It is possible for python objects to share a reference to some other object. This has nothing to do with threads or processes, although it can be used as a *mechanism* for threads and processes to share data. Another mechanism would be some copying and synchronization scheme, which is what posh seems to do. Or maybe not, I haven't used posh yet, I just read some docs (and I already hate the "if process.fork():" idiom, what are they trying to do, reintroduce c-style assignment and swiching?). By the way I haven't done much thread and process programming, but the things I *have* done often combine threads and processes, like starting a console oriented program in a background process, redirecting the IO and communicate with it using an event loop in a thread. I gets more complicated when a gui thread is also involved, for example when retrofitting a gui interface to an existing terminal based chess or go playing program. P. From taygunkekec at gmail.com Wed Jun 25 02:57:34 2008 From: taygunkekec at gmail.com (Taygun Kekec) Date: Tue, 24 Jun 2008 23:57:34 -0700 (PDT) Subject: Using Python to run SSH commands on a remote server References: <03a078c8$0$3229$c3e8da3@news.astraweb.com> <86adnQ8H4MFYdcLVnZ2dnUVZ_sHinZ2d@cablespeedwa.com> <03a08853$0$3220$c3e8da3@news.astraweb.com> <48601b32$0$7361$607ed4bc@cv.net> Message-ID: <1d136a46-3701-4160-badb-9545ff863a74@m36g2000hse.googlegroups.com> Alson you can take a look at pexpect module if you want to automate logging in and process commands , in this way you will no longer wait for loginname and password prompt. From vdutto at gmail.com Tue Jun 3 06:45:39 2008 From: vdutto at gmail.com (V) Date: Tue, 3 Jun 2008 03:45:39 -0700 (PDT) Subject: Books for programmers References: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> Message-ID: <78ef063d-7219-4ffa-bf8f-88dc24dd90bc@r66g2000hsg.googlegroups.com> Hi Matt, and thank you very much for your answer. > Hm, depends of course, how good your programming skills are in the > languages you knwo already, but I rely on the book "Beginning Python - > From Novice to Professional" by Magnus Lie Hetland, published by Apress. I think that I'm interested in a more advance book, ideally one that talk of the Python gotchas, traps, pitfall, idioms, performance, stile, and so on. I really like the style used from Scott Meyers in his Effective C++ series, or from Herb Sutter's Exceptional C++, but after a quick look I did not find anything similar for Python... Best regards. From sturlamolden at yahoo.no Tue Jun 3 23:18:43 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 3 Jun 2008 20:18:43 -0700 (PDT) Subject: can python do some kernel stuff? References: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> <48366cfa$0$15168$607ed4bc@cv.net> <28c432f0-657c-4272-8cd4-a9081b013279@w5g2000prd.googlegroups.com> <69nigsF3499pqU2@mid.uni-berlin.de> <4836994e$0$11625$607ed4bc@cv.net> <69nls3F344g2cU1@mid.uni-berlin.de> <4836a876$0$11623$607ed4bc@cv.net> Message-ID: On Jun 4, 12:41 am, Ethan Furman wrote: > the kernel itself, *is* kernel coding. And as wonderful as Python is, > it is *not* for kernel coding. Not in its present form, no, it would take some porting. But aside from that, is there any reason one could not embed a python interpreter in the kernel? From george.sakkis at gmail.com Sat Jun 21 11:02:34 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 21 Jun 2008 08:02:34 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <79a1c500-1844-4405-8f52-21e845a85f9b@z66g2000hsc.googlegroups.com> <5678904d-93ee-40f1-97b2-78d49ce29fb7@f24g2000prh.googlegroups.com> <7c2386a3-ffba-4bbb-aeab-3e263710ac60@26g2000hsk.googlegroups.com> Message-ID: On Jun 21, 9:40?am, eliben wrote: > > > I see. In my case I only evaluate function definitions with 'exec', so > > > I only need to de-indent the first line, and the others can be > > > indented because they're in a new scope anyway. What you suggest works > > > for arbitrary code and not only function definitions. It's a nice > > > trick with the "if 1:" :-) > > > Have you actually profiled your code? Or are you just basing this > > assumptions on guesses? > > First of all, I see absolutely no connection between your question and > the text you quote. Is there? Or did you pick one post randomly to > post your question on? > > Second, yes - I have profiled my code. > > Third, this is a very typical torture path one has to go through when > asking about code generation. It is true of almost all communities, > except Lisp, perhaps. You have to convince everyone that you have a > real reason to do what you do. The simple norm of getting a reply to > your question doesn't work when you get to code generation. I wonder > why is it so. How many people have been actually "burned" by bad code > generation techniques, and how many are just parroting "goto is evil" > because it's the accepted thing to say. This is an interesting point > to ponder. It's not as much that many people have been burned but that, like goto, 99% of the time there are better alternatives. Off the top of my head, two recurring threads in c.l.py related to dynamic code generation and evaluation are: - Asking how to dynamically generate variable names ("for i in xrange(10): exec 'x%d = %d' % (i,i)") instead of using a regular dictionary. - Using function names instead of the actual function objects and calling eval(), not knowing that functions are first-class objects (or not even familiar with what that means). So even if your use case belongs to the exceptional 1% where dynamic code generation is justified, you should expect people to question it by default. George From pythonblogs at gmail.com Mon Jun 2 14:49:13 2008 From: pythonblogs at gmail.com (pythonblogs at gmail.com) Date: Mon, 2 Jun 2008 11:49:13 -0700 (PDT) Subject: python blogs Message-ID: <19d5037f-837d-4f6b-9e56-d4e6d84b277d@y22g2000prd.googlegroups.com> Hello! It seems like Python blogs are gaining popularity. It seems to me that they play a crucial role in promoting Python as a language. Do you agree with that? Just a few days ago I've finished setting up a dedicated Python blogging environment at: http://www.pythonblogs.com Do you think it will be useful for Python community? By the way, everyone is welcome to join. Sincerely yours, ~pyblog From dfnsonfsduifb at gmx.de Fri Jun 6 18:03:47 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Sat, 07 Jun 2008 00:03:47 +0200 Subject: Newbie question, list comprehension Message-ID: <3rooh5xmap.ln2@joeserver.homelan.net> Hello group, I'm currently doing something like this: import time localtime = time.localtime(1234567890) fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % (localtime[0], localtime[1], localtime[2], localtime[3], localtime[4], localtime[5]) print fmttime For the third line there is, I suppose, some awesome python magic I could use with list comprehensions. I tried: fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % ([localtime[i] for i in range(0, 5)]) But that didn't work: Traceback (most recent call last): File "./test.py", line 8, in ? fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % ([localtime[i] for i in range(0, 5)]) TypeError: int argument required As it appearently passed the while list [2009, 02, 14, 0, 31, 30] as the first parameter which is supposed to be substituted by "%04d". Is there some other way of doing it? Thanks a lot, Regards, Johannes -- "Wer etwas kritisiert muss es noch lange nicht selber besser k?nnen. Es reicht zu wissen, da? andere es besser k?nnen und andere es auch besser machen um einen Vergleich zu bringen." - Wolfgang Gerber in de.sci.electronics <47fa8447$0$11545$9b622d9e at news.freenet.de> From xpahos at gmail.com Fri Jun 6 09:02:44 2008 From: xpahos at gmail.com (phasma) Date: Fri, 6 Jun 2008 06:02:44 -0700 (PDT) Subject: BZip2 decompression and parsing XML Message-ID: Hi. I'm trying to disassemble bzipped file. If I use minidom.parseString, I'm getting this error: Traceback (most recent call last): File "./replications.py", line 342, in ? File "/usr/lib64/python2.4/xml/dom/minidom.py", line 1925, in parseString return expatbuilder.parseString(string) File "/usr/lib64/python2.4/xml/dom/expatbuilder.py", line 940, in parseString return builder.parseString(string) File "/usr/lib64/python2.4/xml/dom/expatbuilder.py", line 223, in parseString parser.Parse(string, True) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 538676, column 17 If I use minidom.parse, I'm getting this error: Traceback (most recent call last): File "./replications.py", line 341, in ? files.xml = minidom.parse(bz2.decompress(dump)) File "/usr/lib64/python2.4/xml/dom/minidom.py", line 1915, in parse return expatbuilder.parse(file) File "/usr/lib64/python2.4/xml/dom/expatbuilder.py", line 922, in parse fp = open(file, 'rb') IOError But XML parsed normally. Code: try: handler = open(args[0], "r") dump = handler.read() handler.close() except IOError, error: print("Can't open dump: %s" % error) sys.exit(1) files.xml = minidom.parse(bz2.decompress(dump)) From zephyrfalcon!NO_SPAM! at gmail.com Wed Jun 4 18:42:31 2008 From: zephyrfalcon!NO_SPAM! at gmail.com (Hans Nowak) Date: Wed, 04 Jun 2008 18:42:31 -0400 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <207cafc4-ba3a-47cb-95d6-50b2b709b84b@j33g2000pri.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <5ea78616-e955-4ee0-8e60-a22734ec31be@79g2000hsk.googlegroups.com> <207cafc4-ba3a-47cb-95d6-50b2b709b84b@j33g2000pri.googlegroups.com> Message-ID: Lie wrote: > On May 24, 9:14 pm, Fuzzyman wrote: >> For example, at Resolver Systems we expose the spreadsheet object >> model to our users. It hasa public, documented, API - plus a host of >> undocumented internally used methods. >> >> We would really *much* rather hide these, because anything our >> customers start using (whether documented or not) we will probably >> have to continue supporting and maintaining. > Then don't document it, or separate internal documentation (which is > never to pass through the wall) and public documentation (which your > users use). Nobody would (apart from your dev team and anyone told by > your dev team, which means you may fire the person for "lack of > discipline") know that there is such a thing and in consequence > wouldn't use it. > > Don't tell your user not to use something, just don't tell them that > it exists and they won't use it. I am not familiar with the actual software, but judging from "we expose the spreadsheet object model to our users", I assume that users can discover the undocumented attributes, using Python's introspection features, like dir(obj), obj.__dict__, the inspect module, etc. So in this case, not telling them that the attributes exist, will not stop them from finding out. -- Hans Nowak (zephyrfalcon at gmail dot com) http://4.flowsnake.org/ From drakonik at gmail.com Fri Jun 27 20:19:00 2008 From: drakonik at gmail.com (Nick Dumas) Date: Fri, 27 Jun 2008 20:19:00 -0400 Subject: Do I need "self" and "other"? In-Reply-To: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Kurda Yon wrote: > Hi, > > I found one example which defines the addition of two vectors as a > method of a class. It looks like that: > > class Vector: > def __add__(self, other): > data = [] > for j in range(len(self.data)): > data.append(self.data[j] + other.data[j]) > return Vector(data) > > In this example one uses "self" and "other". Does one really need to > use this words? And, if yes, why? I have replaced "self" by "x" and > "other" by "y" and everything looks OK. Is it really OK or I can have > some problem in some cases? > > Thank you! In Python, when defining the methods of a class, you pass self as an argument to these methods so that they can have access to the class's variables and methods. Example: class Foo(): self.x = 5 def bar(self): print self.x def baz(): print self.x #This raises an error. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkhlg3QACgkQLMI5fndAv9gQZgCfRV15fQwGb9+n7Lz6JYmfXdeZ 0fYAn0fK90XfR7in/B9TjflwBRFcsgSS =qyXG -----END PGP SIGNATURE----- From deets at nospam.web.de Wed Jun 4 07:48:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 04 Jun 2008 13:48:09 +0200 Subject: new to python, looking for streams clues References: <58bb3360-daa5-4cf8-a3bf-93044ed189b1@x41g2000hsb.googlegroups.com> Message-ID: <6andovF38trhrU1@mid.uni-berlin.de> Thierry wrote: > Hello peoples, > > As I said, I'm new to python, and particularly to XML generation in > python. > Using the 4suite XML package, I have been able to produce XML, but > only directly to STDOUT. > > Refering to the 4suite markupWriter refrence, the class needs a stream > to output the generated XML, and if none is specified, it's the STDOUT > stream that is used. > > What I would like, would be to store the generated XML into a python > object which implement the stream interface to be able to transform it > via XSLT if needed (it's in a web based project). > > But, I've read the python doc for the last 12 hours without finding > anything about an existing object that implements that interface. > Am I missing something, or should I really create that object myself ? > > I mean, I just need something that I can write into and read > thereafter. > It should already exists, no ? See the modules StringIO and cStringIO - which are mentioned on http://docs.python.org/lib/lib.html with the words: 4.5 StringIO -- Read and write strings as files HTH, Diez From goldnery at gmail.com Wed Jun 4 14:14:02 2008 From: goldnery at gmail.com (Gandalf) Date: Wed, 4 Jun 2008 11:14:02 -0700 (PDT) Subject: how should i use this function? Message-ID: <99ed3c04-bd62-4456-ae12-eca4179005dc@r66g2000hsg.googlegroups.com> http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/PyCRichEditCtrl__GetSelText_meth.html GetSelText() I tried to import win32ui.PyCRichEditCtrl, But the shell told me their's no such module. If anyone can show me an example it would be great Thanks! From google at mrabarnett.plus.com Sat Jun 14 17:15:10 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 14 Jun 2008 14:15:10 -0700 (PDT) Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <0213909a-7888-4474-bd88-fc5f148f0abe@y38g2000hsy.googlegroups.com> Message-ID: <9a2940dc-a99e-4077-978b-8c9a400398d7@r66g2000hsg.googlegroups.com> On Jun 14, 4:05 pm, sturlamolden wrote: > On Jun 12, 3:48 pm, Mark wrote: > > > Is this possible? > > def foobar(user,score): > sums = {} > for u,s in zip(user,score): > try: > sums[u] += s > except KeyError: > sums[u] = s > return [(u, sums[u]) for u in sums].sort() > sort() sorts the list in-place and returns None. Try this instead: return sorted([(u, sums[u]) for u in sums]) or, better yet: return sorted(sums.items()) > usersum = foobar(user,score) > for u,s in usersum: > print "%d %d" % (u,s) From pavlovevidence at gmail.com Sun Jun 8 18:46:12 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 8 Jun 2008 15:46:12 -0700 (PDT) Subject: Q re documentation Python style References: Message-ID: <540d2d1d-d274-4614-a46c-4e372190791b@x41g2000hsb.googlegroups.com> On Jun 8, 5:17 pm, kj wrote: > I'm a Perlhead trying to learn the Way of Python. Welcome to the light, my son. > I guess this is a rambling way to ask: are docstrings *it* as far > Python documentation goes? Or is there a second, more flexible > system? You can define a decorator to inject the docstring; at least the docstring will not come between the function line and the body. Define the decorator like this: def doc(docstring): def inject_doc(function): function.func_doc = docstring return function return inject_doc And then you could do this: @doc("This is the docstring.") def some_function(): do_whatever() I think most tools that use docstrings actually execute the module, which means by the time the tool sees it the docstring will have been assigned, though I'm not sure they all do. Carl Banks From gh at ghaering.de Mon Jun 16 17:15:10 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 16 Jun 2008 23:15:10 +0200 Subject: sqlite3 and Python 2.5.1 In-Reply-To: <612ed26a-c6cf-4133-af6c-f256484e3928@x41g2000hsb.googlegroups.com> References: <612ed26a-c6cf-4133-af6c-f256484e3928@x41g2000hsb.googlegroups.com> Message-ID: <6bo3euF3c8etnU1@mid.uni-berlin.de> milan_sanremo wrote: > I have sqlite installed, but when I try to import sqlite3 I receive: > > Python 2.5.1 (r251:54863, Nov 3 2007, 02:54:36) [C] on sunos5 > Type "help", "copyright", "credits" or "license" for more information. >>>> import sqlite3 > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named sqlite3 > > Yet: > > # find /usr/local/python -name "sqlite*" -print > /usr/local/python/lib/python2.5/sqlite3 > > # /opt/csw/bin/sqlite3 > SQLite version 3.2.2 > Enter ".help" for instructions > sqlite> > > What is missing? You compiled Python yourself. During that, the SQLite3 header files could not be found, so the sqlite3 module was not compiled/installed. -- Gerhard From jason.scheirer at gmail.com Sat Jun 14 13:32:50 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Sat, 14 Jun 2008 10:32:50 -0700 (PDT) Subject: Was the move to Python 2.0 as big a deal? References: <4853f365$0$11601$607ed4bc@cv.net> Message-ID: <6bc70020-12ac-4474-9889-d18fee76ae5d@a9g2000prl.googlegroups.com> On Jun 14, 9:35?am, John Salerno wrote: > Just curious if people put up any resistance to 2.0 like some people do > for 3.0. Was it as big of a change in the language, or was the > transition smoother? It seems silly for anyone to say they would prefer > to stick with 1.x versions at this point, so perhaps we'll get there > with 3.0 eventually too. > > Anyway, I'm just trying to figure out if the whole "I don't like 3.0" > mentality (of some people, not all of course) is merely a result of it > still being new and not even released yet, and will completely go away > after a year or two; or if there really are such drastic changes that > people won't want to adopt it at all. A lot of the bigger changes and warts that have emerged in the past decade or so of the 2.0 series (text encoding madness anyone?) have been tabled until the 3.0 transition, so any compatibility breaks for the sake of fixing inconsistencies and ugliness in Python have been accruing and are finally being applied in 3.0. The 1.5->2.0 transition was a little strange, but I think a large reason that it was less painful was because the language was younger, less established and had far fewer people programming in it (and correspondingly smaller codebases) to transition over. From cdcasey at gmail.com Fri Jun 20 11:57:12 2008 From: cdcasey at gmail.com (chris) Date: Fri, 20 Jun 2008 08:57:12 -0700 (PDT) Subject: images on the web References: <2e72bd7d-9d33-43ba-8c08-ba3b39368466@z72g2000hsb.googlegroups.com> <485B4F31.6000104@mattnordhoff.com> <7n0si5-6u3.ln1@nb2.stroeder.com> Message-ID: <354be5d7-e86a-40e3-9cd0-b8a5ceead962@r66g2000hsg.googlegroups.com> On Jun 20, 1:52 am, Michael Str?der wrote: > Matt Nordhoff wrote: > > Matt Nordhoff wrote: > >> You could use data: URIs [1]. > > >> For example, a 43-byte single pixel GIF becomes this URI: > > >> > > >> They don't have universal browser support, but that might not be a > >> problem in this case. > > >> As for generating them with Python, I'm not sure... I just used Hixie's > >> data: URI kitchen [2] for the above example. > > >> [1] > >> [2] > > > Oh.. As > > shows, the reason I couldn't find a data: URI Python library is because > > they're utterly trivial to generate: > > > import base64 > > import urllib > > > raw_data = create_gif() > > uri = 'data:image/gif;base64,' + urllib.quote(base64.b64encode(raw_data)) > > > (And it's even simpler if you leave out the base64-encoding.) > > The caveat with URL schema data: is that the amount of data to be > transferred is significantly higher than including HTML tag > in your HTML source and let the browser fetch the raw binary image data > in a separate HTTP request (you also have to serve from your web > application). > > Ciao, Michael. This sounds like the way I want to go, it's just a matter of figuring it out. Is it just a matter of putting a function call in an img tag? I'll give the URI thing a try, too, From andymac at bullseye.apana.org.au Fri Jun 27 21:11:18 2008 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 28 Jun 2008 12:11:18 +1100 Subject: ImportError: DLL load failed In-Reply-To: <418cd5740806271120n5a43f5cfmd78a5c749b9e1eea@mail.gmail.com> References: <418cd5740806271120n5a43f5cfmd78a5c749b9e1eea@mail.gmail.com> Message-ID: <48658FB6.9040702@bullseye.andymac.org> Tony May wrote: > I'm having trouble importing when I run in Python. The hello world program > passes the test during the bjam build but gives an error about loading > the dll > when I import from a python script. > > first the test from running bjam. > ...patience... > ...found 1915 targets... > ...using 1 temp target... > ...updating 2 targets... > ...using \threading-multi>hello_ext.pyd... > > capture-output bin\hello.test\msvc-8.0express\debug\threading-multi\hello > 1 file(s) copied. > **passed** bin\hello.test\msvc-8.0express\debug\threading-multi\hello.test > ...updated 2 targets... > > then trying to run the script from python > I copied the pyd file and the rest of the output dir to c:\python25\dlls > > C:\Program Files\boost\boost_1_35_0\libs\python\example\tutorial>python > hello.py > > > Traceback (most recent call last): > File "hello.py", line 6, in > import hello_ext > ImportError: DLL load failed: This application has failed to start > because the a > pplication configuration is incorrect. Reinstalling the application may > fix this > problem. The DLL that's actually being imported by your script is not a Python extension module, as the modules initialisation function can't be found. Use the -v option on the Python command line to identify which DLL is actually being imported. You can then decide to move/rename.delete it or your own module as best fits your circumstances. -- ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From timothy.grant at gmail.com Sat Jun 14 15:10:10 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Sat, 14 Jun 2008 12:10:10 -0700 Subject: Creating a TCP/IP connection on already-networked computers In-Reply-To: <485413d0$0$4997$607ed4bc@cv.net> References: <4853f269$0$11615$607ed4bc@cv.net> <4854123f$0$5017$607ed4bc@cv.net> <485413d0$0$4997$607ed4bc@cv.net> Message-ID: On Sat, Jun 14, 2008 at 11:54 AM, John Salerno wrote: > John Salerno wrote: > > ----- >> #!/usr/bin/env python >> >> from socket import * >> from time import ctime >> >> HOST = '192.168.1.100' >> > > > ----- >> #!/usr/bin/env python >> >> from socket import * >> >> HOST = '192.168.1.100' >> > > A question about this. Is the "HOST" referring to the IP address of the > server computer in both of these cases? Because when I ran the program and > got to the part where it says "connected from:" on the server side, it shows > this same IP address. Shouldn't it be something different, since the > requests are coming from a different computer than the server computer? > > -- > http://mail.python.org/mailman/listinfo/python-list > John, It looks to me as if you're running both client and server on the same box, and in effect conecting to yourself. You asked in an earlier message if a friend on a different network could connect to you using your client programme and that depends on a LOT of things. Your friend certainly wouldn't be able to using the 192.168.x.x address as that is an unroutable address. But you would likely have a bit of work to do to get it to work through you and your friend's firewalls (that is likely a conversation for a later time though. -- Stand Fast, tjg. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Tue Jun 10 13:22:10 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 10 Jun 2008 10:22:10 -0700 (PDT) Subject: Python doesn't understand %userprofile% References: Message-ID: <16da3ad6-b51e-4552-99b4-93c31a8e9e27@59g2000hsb.googlegroups.com> On Jun 10, 11:11?am, Tim Golden wrote: > bsag... at gmail.com wrote: > > In xp when I try os.path.getmtime("%userprofile/dir/file%") Python > > bites back with "cannot find the path specified" Since my script has > > to run on machines where the username is unspecified I need a fix. > > Well I can see a few problems here. > > First is that putting percent signs around the whole path is > never going to work anyway. You want something like: > > "%USERPROFILE%/dir/file". > > Secondly, the expansion of environment variables like > USERPROFILE is done for you by the shell or the command > prompt. You have to do it for yourself if you're opening your > own files. You want something like: > > import os > print os.path.getmtime (os.path.join (os.environ['USERPROFILE'], "ntuser.ini")) > > But finally, what do you mean "run on machines where the username is > unspecified"? If you mean: where no user is logged in, then you won't > have a (meaningful) userprofile in any case: it might be the Default User > profile; I'm not sure. But is that what you want? > > You *can* use the functions in the win32profile module of the pywin32 > packages to find out various things about profiles directories, but things > can get quite complicated if users have roaming profiles and the like. > > TJG Tim, I'm surprised you didn't mention your excellent winshell utility. I use it for this sort of issue all the time where I need to update files on login and I don't know the user's name beforehand. The winshell.Desktop() one has been a life saver and I think the OP could probably use winshell for their problem. Or I may be completely off my rocker. Either way, here's the link: http://timgolden.me.uk/python/winshell.html Mike From thijs.triemstra at gmail.com Sun Jun 29 12:34:14 2008 From: thijs.triemstra at gmail.com (Thijs Triemstra | Collab) Date: Sun, 29 Jun 2008 09:34:14 -0700 (PDT) Subject: Docutils rst2html.py gives Unknown Directive type "toctree" References: Message-ID: Getting the same error in the apache logs here, no idea where it's coming from: [Sun Jun 29 18:25:50 2008] [error] :10: (ERROR/3) Unknown directive type "toctree". [Sun Jun 29 18:25:50 2008] [error] [Sun Jun 29 18:25:50 2008] [error] .. toctree:: [Sun Jun 29 18:25:50 2008] [error] :maxdepth: 2 [Sun Jun 29 18:25:50 2008] [error] [Sun Jun 29 18:25:50 2008] [error] :16: (ERROR/3) Unknown interpreted text role "ref". [Sun Jun 29 18:25:50 2008] [error] :17: (ERROR/3) Unknown interpreted text role "ref". [Sun Jun 29 18:25:50 2008] [error] :18: (ERROR/3) Unknown interpreted text role "ref". On Jun 19, 11:19?pm, "Calvin Cheng" wrote: > Hi, > > I am attempting to convert a bunch of .txt files into html using the > docutils package. > > It works for most of the txt files except for the index.txt file which > gives 2 errors: > (1) Unknown Directive type "toctree" > (2) (ERROR/3) Unknown interpreted text role "ref". > > Any idea how I can fix this? > > Would be glad if someone who is familiar with docutils could point me > in the right direction. > > Thank you, > Calvin From t_spens at yahoo.com Fri Jun 27 12:57:06 2008 From: t_spens at yahoo.com (Tim Spens) Date: Fri, 27 Jun 2008 09:57:06 -0700 (PDT) Subject: embedding and extending python C API registering callback handler objects In-Reply-To: <24081.19905.qm@web45113.mail.sp1.yahoo.com> Message-ID: <393211.31628.qm@web45115.mail.sp1.yahoo.com> --- On Fri, 6/27/08, Tim Spens wrote: > From: Tim Spens > Subject: Re: embedding and extending python C API registering callback handler objects > To: python-list at python.org, "Matimus" > Date: Friday, June 27, 2008, 9:16 AM > thanks, but didn't fix the problem. > > > --- On Fri, 6/27/08, Matimus > wrote: > > > From: Matimus > > Subject: Re: embedding and extending python C API > registering callback handler objects > > To: python-list at python.org > > Date: Friday, June 27, 2008, 9:03 AM > > On Jun 27, 8:22 am, Tim Spens > > > wrote: > > > Hello all, > > > > > > I've been trying to get an example found > > > herehttp://codeidol.com/python/python3/Embedding-Python/Registering-Callb... > > > to work. Every thing works fine except when I > try to > > trigger an event from c that will call a python > function. > > Here is my test code: > > > > > > //-----------------------python > > code--------------------------// > > > #! /usr/bin/env python > > > import time > > > import callback > > > > > > def callback1(label,count): > > > print 'callback1 successfully > > triggered from python via callback.so' > > > return 'callback1 => %s number > > %i' % (label, count) > > > > > > def callback2(label,count): > > > return 'callback2 => ' + > > label * count > > > > > > print '\nTest1:' > > > callback.setHandler(callback1) > > > callback.triggerEvent() # simulate events > > caught by C layer > > > > > > print '\nTest2:' > > > callback.setHandler(callback2) > > > > > > print 'Waiting for callback2 to be called > from > > c:' > > > while 1: > > > time.sleep(.001) > > > > > > //-----------------------c > > code-------------------------------// > > > #include > > > #include > > > > > > /* keep Python object in C */ > > > static PyObject *Handler = NULL; > > > > > > void Route_Event(char *label, int count){ > > > char *cres; > > > PyObject *args, *pres; > > > /* call Python handler */ > > > args = Py_BuildValue("(si)", label, > > count); > > > pres = PyEval_CallObject(Handler, args); > > > Py_DECREF(args); > > > if (pres != NULL){ > > > /* use and decref handler result */ > > > PyArg_Parse(pres, "s", > > &cres); > > > printf("%s\n", cres); > > > Py_DECREF(pres); > > > > > > }} > > > > > > // the actual python callback call > > > static PyObject * > > > make_call(PyObject *function, PyObject *args){ > > > if (function == NULL) return NULL; > > > PyObject * val = > PyObject_CallObject(function, > > args); > > > Py_XDECREF(args); > > > return val; > > > > > > } > > > > > > static PyObject * > > > Register_Handler(PyObject *self, PyObject *args){ > > > /* save Python callable object */ > > > Py_XDECREF(Handler); > > > PyArg_Parse(args, "O", > &Handler); > > > Py_XINCREF(Handler); > > > Py_INCREF(Py_None); > > > return Py_None; > > > > > > } > > > > > > static PyObject * > > > Trigger_Event(PyObject *self, PyObject *args){ > > > /* let Python simulate event caught by C */ > > > static int count = 0; > > > Route_Event("spam", count++); > > > Py_INCREF(Py_None); > > > return Py_None; > > > > > > } > > > > > > static struct PyMethodDef callback_methods[] = { > > > {"setHandler", > Register_Handler}, > > /* name, address */ > > > {"triggerEvent", Trigger_Event}, > > > {NULL, NULL}}; > > > > > > > > /* on first "import callback" */ > > > void initcallback(){ /* this > > is called by Python */ > > > (void) Py_InitModule("callback", > > callback_methods); > > > > > > } > > > > > > int main(){ > > > while (1){ > > > printf("1\n"); > > > //attempting to call callback2 > > which is registered to Handler > > > //i've also tried args = > > Py_BuildValue("(si)", label, count); here > but I > > get a segfault. > > > PyObject *args = > > Py_BuildValue("s","c code"); > > > printf("2\n"); > > > PyObject* val = > > make_call(Handler,args); > > > printf("3\n"); > > > Py_XDECREF (val); > > > printf("4\n"); > > > sleep(1); > > > > > > }} > > > > > > //------------------------compiler > > stuff----------------------// > > > gcc callback.c -c -g -Wall -fpic -I > > /usr/include/python2.5 -o callback.o > > > gcc callback.c -g -Wall -I /usr/include/python2.5 > -L > > /usr/local/lib -lpython2.5 -o callback > > > gcc -shared -Wall callback.o -o callback.so > > > > > > //------------------------test code > > results-------------------// > > > ../callback.py > > > Test1: > > > callback1 successfully triggered from python via > > callback.so > > > callback1 => spam number 0 > > > > > > Test2: > > > Waiting for callback2 to be called from c: > > > #NOTHING EVER GETS PRINTED HERE CALLBACK NEVER > GETS > > CALLED? > > > > > > ../callback > > > 1 > > > 2 > > > 3 > > > 4 > > > .... > > > > > > Thanks, > > > Tim > > > > Maybe you just need to flush the stdout buffer in > python. > > `sys.stdout.flush()` > > > > Matt > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > http://mail.python.org/mailman/listinfo/python-list I think I know where the problem is but I'm unsure how to fix it. When I call Register_Handler(...) from python via callback.setHandler1(callback1) this only seems to affect pythons ability to trigger an "event" in c. PyObject *Handler is always NULL even after I call Register_Handler(...). I thought there was some magic here that was assigning the pointer *Handler to my python callback1 handler so it could be triggered from c? -Tim From gnewsg at gmail.com Fri Jun 6 10:23:31 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Fri, 6 Jun 2008 07:23:31 -0700 (PDT) Subject: Partial download with ftplib and retrbinary References: <9dd32f80-ce21-4c2c-8eba-1afd3b80379f@x41g2000hsb.googlegroups.com> Message-ID: <905eff9f-bc91-4f99-83df-7a89fd936b27@f63g2000hsf.googlegroups.com> On 24 Mag, 12:53, fepeac... at googlemail.com wrote: > I am breaking/interrupting my connection with theftpserver at > present when doing a partial download of a file. I have a callback > with retrbinary that raises an exception and ends the download. The > problem is that the server is not notified and hangs. I cannot send > any further commands and need to relogin to download further. Is there > a way to still continue downloading without having to login again. > > My retrbinary function is: > > ftp.retrbinary('RETR '+file, handleDownload,1,bound[0]) > > where bound[0] is an integer specifying the start byte of the > download. > > My callback is: > > def handleDownload(block): > ? ? global count,localfile,number > ? ? localfile.write(block) > ? ? if count==number: > ? ? ? ? ? ? raise(Exception) > ? ? count=count+1 > > where number specifies the number of bytes to download. > > Help would be gratefully received. The server hangs on because the data connection is left open. Unfortunately you have no easy way to close the data connection by using retrbinary. You have to trick a little bit and keep a reference of the data socket and manually close it. The example below starts to retrieve a file and stops when 524288 bytes have been received. Hope this could help you. import ftplib ftp = ftplib.FTP('127.0.0.1', 'user', 'password') ftp.voidcmd('TYPE I') conn = ftp.transfercmd('RETR filename') # the data socket bytes_recv = 0 while 1: chunk = conn.recv(8192) # stop transfer while it isn't finished yet if bytes_recv >= 524288: # 2^19 break elif not chunk: break file.write(chunk) bytes_recv += len(chunk) conn.close() --- Giampaolo http://code.google.com/p/pyftpdlib From kyosohma at gmail.com Thu Jun 19 14:50:19 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 19 Jun 2008 11:50:19 -0700 (PDT) Subject: python/ruby question.. References: <3b017f08-2d42-4c65-9003-19ffc606234d@l64g2000hse.googlegroups.com> Message-ID: <5ea57226-c622-46b5-b792-d95604b1aebe@q24g2000prf.googlegroups.com> On Jun 19, 11:49?am, a... at pythoncraft.com (Aahz) wrote: > In article , > Matt Nordhoff ? wrote: > > > > >You're supposed to use the subprocess module. > > Really? ?Sez who? > > $ python > Python 2.3.4 (#1, Feb ?2 2005, 12:11:53) > [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> import subprocess > > Traceback (most recent call last): > ? File "", line 1, in ? > ImportError: No module named subprocess > -- > Aahz (a... at pythoncraft.com) ? ? ? ? ? <*> ? ? ? ?http://www.pythoncraft.com/ > > "as long as we like the same operating system, things are cool." --piranha The subprocess module supercedes os.popen*, os.system, commands and a few others in Python 2.4+. Thus, those others are deprecated. See the docs here: http://docs.python.org/lib/module-subprocess.html Mike From bjourne at gmail.com Tue Jun 3 06:07:43 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 3 Jun 2008 12:07:43 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> Message-ID: <740c3aec0806030307ld7078bfv15ba2a920d2590e2@mail.gmail.com> On Mon, Jun 2, 2008 at 10:50 PM, Russ P. wrote: > On Jun 2, 6:41 am, Carl Banks wrote: > >> You are not realizing that only useful(**) thing about data hiding is >> that some code has access to the data, other code does not. If you >> "hide" data equally from everyone it's just a useless spelling change. > > I think you're missing the point. > > As I see it, the primary value of data hiding is that it provides > useful information on which data and methods are intended for the > client and which are intended for internal use. It's like putting a > front panel on a TV set with the main controls intended for the > viewer. Here's my two cents. First of all, a TV is a bad analogy compared to reusable software libraries. Really bad analogy. A TV is a horribly complicated device which has to be dumbed down because otherwise it would be to hard to use for ordinary people. A software developers relation to a third party library is more similar to a TV repair man trying to repair a TV than to a random person watching TV. For a repair man, the front panel is just useless and in the way. Oh, and to continue on the TV analogy, one of the reason why a TV is complicated is because its interface is totally different from its implementation. Channels are just a bad abstraction for tuning the receiver to different frequencies and for switching inputs. Merely using a TV doesn't teach you anything about how it actually works. KISS: Keep It Simple Stupid. And it is always simpler to not implement the gunk needed for data hiding than to do it. By keeping things simple you keep your code easy to implement, easy to understand and easy to reuse. Data hiding sacrifices implementation simplicity supposedly to make the interface simpler and to keep backwards compatibility. It allows you to change implementation details without affecting the interface. But do you really want to do that? Consider this silly Java example: class Foo { private int bar; public int getBar() { return bar; } }; Then for some reason you decide that hm, "bar" is not a good attribute name so you change it to "babar". And you can do that without changing the public interface! Woho! So now you have a public getter named "getBar" that returns an attribute named "babar". That's in reality just bad and whoever is maintaining the implementation is going to be annoyed that the getters name doesn't match the attribute name. What would have happened without data hiding? Renaming the public attribute "bar" to "babar" probably cause some grief for someone reusing your library, but you would keep your implementation pure. What about semantic changes? Data hiding doesn't protect you against that, so you'll have to change your interface anyway. The interface for a car hasn't changed much in the last 100 years, but the implementation has. How easy is it to repair a car nowadays compared to 30 years ago? And data hiding as a documentation aid is just a sham. "These methods are public so you can call them, these aren't so hands off!" A reuser of your library *will* want to know what happens on the inside, by trying to make stuff impossible to reach you are just making that kind of information much harder to come by. The better method is to just write proper docstrings that tell the user what the methods do and when they can be called. Another good way to see how useless data hiding is, is to try and unit test a very encapsulated library. You'll see that it is almost impossible to write good unit tests unless you publicly export almost everything in the code. At which point you come to realize that all the data hiding was for naught. -- mvh Bj?rn From circularfunc at yahoo.se Mon Jun 23 13:54:21 2008 From: circularfunc at yahoo.se (cirfu) Date: Mon, 23 Jun 2008 10:54:21 -0700 (PDT) Subject: IDE on the level of Eclipse or DEVc++? References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> Message-ID: i downloaded the extension for eclipse, nice. any opinions of netbeans vs eclipse for python? From mario at ruggier.org Sat Jun 28 06:34:14 2008 From: mario at ruggier.org (mario) Date: Sat, 28 Jun 2008 03:34:14 -0700 (PDT) Subject: Mako vs. Cheetah? References: <4862f57c$0$11621$607ed4bc@cv.net> <4863bf9c$0$14081$c3e8da3@news.astraweb.com> Message-ID: <11fd5899-1c13-4feb-966d-69bbc43317c2@m3g2000hsc.googlegroups.com> A small and ultra-lightweight system, with all the power of any fully featured text-based templating system (such as mako or cheetah) and then some (no constraints on template file names or formats, restricted execution, automatic XSS protection, ...) that can be used in a web context or standalone, while being also incredibly fast, is Evoque Templating: http://evoque.gizmojo.org/ And the simplicity of the system means you can assimilate the entire thing in a single sitting, and thereafter easily remember the few key things to continue using it without constant re-consulting of the docs (that, actually, are also pretty good ;-) So yes, agree with you entirely, that shameless personal preference is important for choosing your templating system... ;) mario From john.gerald.mason at gmail.com Sun Jun 1 15:55:45 2008 From: john.gerald.mason at gmail.com (Mason) Date: Sun, 1 Jun 2008 12:55:45 -0700 (PDT) Subject: convert binary to float Message-ID: <0c15e8e1-948b-4bd6-a312-b1e055da859e@t54g2000hsg.googlegroups.com> I have tried and tried... I'd like to read in a binary file, convert it's 4 byte values into floats, and then save as a .txt file. This works from the command line (import struct); In [1]: f = open("test2.pc0", "rb") In [2]: tagData = f.read(4) In [3]: tagData Out[3]: '\x00\x00\xc0@' I can then do the following in order to convert it to a float: In [4]: struct.unpack("f", "\x00\x00\xc0@") Out[4]: (6.0,) But when I run the same code from my .py file: f = open("test2.pc0", "rb") tagData = f.read(4) print tagData I get this (ASCII??): ?@ I only know how to work with '\x00\x00\xc0@'. I don't understand why the output isn't the same. I need a solution that will allow me to convert my binary file into floats. Am I close? Can anyone point me in the right direction? Thanks, Mason From grante at visi.com Wed Jun 11 14:34:59 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 11 Jun 2008 13:34:59 -0500 Subject: problems with opening files due to file's path References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> <77acc29a-fffa-44d6-b07b-6bcf8b5bdd74@h1g2000prh.googlegroups.com> Message-ID: On 2008-06-11, Alexnb wrote: > Okay, so as a response to all of you, I will be using the Entry() widget in > Tkinter to get this path. OK. > and the repr() function just makes all my backslashes 4 > instead of just 1, and it still screwes it up with the numbers > and parenthesis is has been since the first post. I've absolutely no clue why you would be using the repr() function. > Oh and I know all about escape characters, (\n,\b,\a,etc.) Apparently not. > I can program C, not a lot, but enough to know that I like > python better. Anyway, so far I tried all of your stuff, and > it didn't work. To what does "it" refer? > infact, it puts backslashes in front of the > "'" in some of the words, such as "I'm" goes to "I\'m." Again, "it" doesn't seem to have a concrete referant. > So I posted the code I will be using if you want to see the > Tkinter code I can post it, but I don't see how it will help. If you know what would help and what wouldn't, then you must know enough to fix your problems. So please do so and quit bothering the newgroup. -- Grant Edwards grante Yow! I want another at RE-WRITE on my CEASAR visi.com SALAD!! From eckhardt at satorlaser.com Thu Jun 19 11:49:13 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 19 Jun 2008 17:49:13 +0200 Subject: Simple Python class questions References: <8549940b-e909-4bc6-b9a1-ea7d14284785@z16g2000prn.googlegroups.com> Message-ID: Lie wrote: > I think it's not that hard to see that it's just a pseudo code "...in comms.py I have: ..." actually explicitly says that it is actual code from a file. *shrug* Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From franck110 at gmail.com Sun Jun 1 22:42:55 2008 From: franck110 at gmail.com (Franck Y) Date: Sun, 1 Jun 2008 19:42:55 -0700 (PDT) Subject: Better performance Message-ID: <5ef6911e-c7ec-4eb5-8a53-ee59d5a36817@l64g2000hse.googlegroups.com> Hello Folks, I am facing a problem where i need to parse around 200 files, i have a bit of knowledge in PHP/Perl/Python (the magic P :-P) Which one would you suggest me since i have to generate a web interface ? And each one has his area of 'work' Thanks for your help ! From mensanator at aol.com Fri Jun 13 17:13:06 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 13 Jun 2008 14:13:06 -0700 (PDT) Subject: Python 3000 vs. Python 2.x References: <2c299cdc-adcd-4540-b09f-43b4147e10ca@y21g2000hsf.googlegroups.com> Message-ID: <5087e578-ef11-48c5-97ec-68c4d9d95024@a1g2000hsb.googlegroups.com> On Jun 13, 4:04?pm, mr.opus.peng... at gmail.com wrote: > As a new comer to Python I was wondering which is the best to start > learning. ?I've read that a number of significant features have > changed between the two versions. ?Yet, the majority of Python > programs out in the world are 2.x and it would be nice to understand > those as well. ?Thanks for all the help. > > Creosote, What 3rd party modules are you planning to use? You won't be able to use them until their developers release Python 3000 versions. In my research, I heavily depend on the gmpy module for fast, number theoretic functions. Last time I checked, it was only available for v2.5. So, I could install v2.6 or v3.0, but I wouldn't be able to run any of my programs, so what would be the point? From deets at nospam.web.de Mon Jun 9 17:46:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 09 Jun 2008 23:46:31 +0200 Subject: Does the python library of Google Data API is truly free? In-Reply-To: <3a296d00-d4e0-4f03-b6b3-bef4c5d628dd@x35g2000hsb.googlegroups.com> References: <3ac654b2-61b4-44ce-8e03-75f2344d5869@s50g2000hsb.googlegroups.com> <6fb57ab1-b0d2-4b7d-93c1-b919ca0e51a0@i36g2000prf.googlegroups.com> <3a296d00-d4e0-4f03-b6b3-bef4c5d628dd@x35g2000hsb.googlegroups.com> Message-ID: <6b5mloF3aeui4U1@mid.uni-berlin.de> Kless schrieb: > On 9 jun, 21:40, Lie wrote: >> Do you notice that the terms are for the SERVICE not for the SOFTWARE. >> The terms for the service is quite reasonable, as I see it. >> The software itself is governed by the Apache License 2.0, detailed >> here:http://www.apache.org/licenses/LICENSE-2.0 > > Well, it's used a free license to access to a service that is not free > -it's owner and too restrictive-. And it isn't nothing reasonable that > Google get many rights about your content, and that you have not any > right about the rest of the content. > > This goes against the free software, considering that a service is > software. This is nonsense. If a hosting provider offers you free hosting based on linux - and then goes out of business or is forced to charge money - do you say "that's against free software?" Or if they prohibit you to host malicious, offending or otherwise problematic content served by the free apache - is that "against free software?" A service is a service. It is offered as is, under whatever conditions the provider likes it. Offering a convenient way to access the service using a FOSS license is good style. But you aren't forced to use that, you can write your own. But that doesn't change the terms and conditions of the service itself. Diez From deets at nospam.web.de Thu Jun 12 04:58:28 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 12 Jun 2008 10:58:28 +0200 Subject: Please recommend a blog program written using python-cgi References: <4f16f948-1082-4d3a-9276-cac97945c96b@x1g2000prh.googlegroups.com> Message-ID: <6bc6qrF3asvdfU2@mid.uni-berlin.de> Royt wrote: > Hi, I'm a newbie to Python, but I think it won't be too hard to learn. > A few days ago I registered Google App Engine, it only support Python > 2.5. I want to set my blog on it soon. But it's not easy for me to > finish it in a short time since I'm not very familiar with Python, so > I want find some codes available, throught reading the code, I can > learn something from it. I know there are many frameworks for web > development, but I just want the code using traditional CGI method, > it's easy to use and it doesn't require any additional knowledge about > framework. I need a simple example (support basic function of a > weblog, easy to revise) but not a complicated huge monster (I don't > think such a thing now exists). I guess you are out of luck. Usually people use frameworks because it *does* make work easier. AFAIK google engine supports Django. So try & aquaint you with that - and I bet there are Django-based blogs out there. Diez From dev at projekt01.ch Thu Jun 19 17:15:43 2008 From: dev at projekt01.ch (Roger Ineichen) Date: Thu, 19 Jun 2008 23:15:43 +0200 Subject: AW: [Zope3-Users] Python Package Construction In-Reply-To: <1213901807.2875.95.camel@localhost.localdomain> References: <1213901807.2875.95.camel@localhost.localdomain> Message-ID: Hi Tim > Betreff: [Zope3-Users] Python Package Construction > > Hi All, > > I would like feedback on the proper/best 'Pythonic' approach. > > This is a rather subjective question. Where is the trade-off > between package name lengths and faithfulness to the specifications? > > [Discussion follows] > > I am implementing a set of specifications for healthcare IT > for Python programmers to be able to develop interoperable > healthcare applications. > I am using ZCA (aka.Zope3) extensively. > > My desire is to implement the specs as faithfully as possible for two > reasons: > 1) teachability - how easy/difficult is it to teach the > framework and specifications to new developers? > 2) maintainability - which approach, if either, will make it > easier to maintain the framework if/when the specifications change? > > My first pass was to develop a skeleton of the specs using > Interfaces from the ZCA approach and then the implementations > following the document structure of the specs. > > The specs are available via SVN at: > http://www.openehr.org/svn/specification/TRUNK/publishing/arch > itecture/ > > It is best to probably use real examples. Following the > document structure for packaging AND using the ZCA convention > of having a sub-directory for interfaces caused massive > circular import issues due to some classes being used in the > interface definition of classes inside the same interface > file being imported into the implementation file. If that > sounds confusing; it is. It was confusing to write too. :-) > If anyone has questions I'll try to expand. > > It is best to probably use specific, real examples. > http://www.openehr.org/svn/specification/TRUNK/publishing/arch > itecture/rm/data_types_im.pdf > > (note class names are converted from the upper case, > underscore separated style to CamelCase) > > The package openehr.rm.datatypes.text defines the > implementation class CodePhrase. The associated interface > file openehr.rm.datatypes.interfaces.text needed CodePhrase > as an attribute type in DvCodedText and TermMapping needs > both CodePhrase and DvCodedText. This quickly got out of control. > > So my solution to solving the circular imports is to take > each interface and implementation and put them into one file. > Research tells me that this is probably the second mostly > popular ZCA approach. So, ICodePhrase and CodePhrase are now > in openehr/rm/datatypes/codephrase.py, DvCodeText and > IDvCodedText in openehr/rm/datatypes/dvcodedtext.py, etc. > > But wait, now I don't have a 'text package'. So if > codephrase.py and dvcodedtext.py were in > openehr/rm/datatypes/text/ that would solve the problem. > BUT! Throughout the specs many of the names are VERY long > already. Adding another package name that is from 4 - 15 (or > more) characters long adds to the length of already long > import statements, i.e. > > (sorry for the email line wraps) > > from openehr.am.archetype.creferenceobject import > ICReferenceObject,CReferenceObject > > should really be > > from openehr.am.archetype.constraintmodel.creferenceobject > import ICReferenceObject,CReferenceObject > > Thoughts, opinions and jeers all gratefully accepted. :-) For a usecase like this, I personaly recommend to defina all interfaces in one module which probably is a namespace if you need alot of interfaces to define. e.g. openehr.interfaces.foobar.IFooBar the reason why: - spearate interface from implementation. That's an important aspect in a component architecture. If you define your implementation and interfaces in one file, then you don't need a component architecture. - interfaces are separated in a well know place. This means if you define a module and you like to import an interface you can import just one line: from openehr import interfaces Which makes it very simple. Regards Roger Ineichen > --Tim > > > > > > > > > > -- > Timothy Cook, MSc > Health Informatics Research & Development Services LinkedIn > Profile:http://www.linkedin.com/in/timothywaynecook > Skype ID == timothy.cook > ************************************************************** > *You may get my Public GPG key from popular keyservers or * > *from this link http://timothywayne.cook.googlepages.com/home* > ************************************************************** > From eric.talevich at gmail.com Mon Jun 2 18:02:49 2008 From: eric.talevich at gmail.com (etal) Date: Mon, 2 Jun 2008 15:02:49 -0700 (PDT) Subject: Merging ordered lists References: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> Message-ID: <8140b81b-bfa1-463b-a92a-19c0f6453444@k30g2000hse.googlegroups.com> On Jun 1, 1:49?am, Peter Otten <__pete... at web.de> wrote: > Peter Otten wrote: > > #untested > > Already found two major blunders :( > > # still untested > import difflib > > def _merge(a, b): > ? ? sm = difflib.SequenceMatcher(None, a, b) > ? ? for op, a1, a2, b1, b2 in sm.get_opcodes(): > ? ? ? ? if op == "insert": > ? ? ? ? ? ? yield b[b1:b2] > ? ? ? ? elif op == "replace": > ? ? ? ? ? ? yield a[a1:a2] > ? ? ? ? ? ? yield b[b1:b2] > ? ? ? ? else: # delete, equal > ? ? ? ? ? ? yield a[a1:a2] > > def merge(a, b): > ? ? return sum(_merge(a, b), []) > > def merge_to_unique(sources): > ? ? return unique(reduce(merge, sorted(sources, key=len, reverse=True))) > difflib.SequenceMatcher looks promising; I'll try it. Thanks! > def unique(items): > ? ? u = set(items) > ? ? if len(u) == len(items): > ? ? ? ? return items > ? ? result = [] > ? ? for item in items: > ? ? ? ? if item in u: > ? ? ? ? ? ? result.append(item) > ? ? ? ? ? ? u.remove(item) > ? ? return result You did right by preserving the original (non-alphabetical) ordering, but I'm less enthusiastic about the shape of this function. My original function used 7 lines of code, and only 1 for the unique() step. This uses up to three container objects. Is it really an improvement? (Secret: the reference list (or, any of the sources) is unlikely to be more than a few dozen elements long. The data set that puts merge_to_unique through a workout will be a giant list of comparatively short lists, so the unique() part just needs to be short and conceptually clean, while merge() should attempt sane behavior for large len(sources).) From mnordhoff at mattnordhoff.com Fri Jun 13 18:38:04 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 13 Jun 2008 22:38:04 +0000 Subject: Python 3000 vs. Python 2.x In-Reply-To: <2c299cdc-adcd-4540-b09f-43b4147e10ca@y21g2000hsf.googlegroups.com> References: <2c299cdc-adcd-4540-b09f-43b4147e10ca@y21g2000hsf.googlegroups.com> Message-ID: <4852F6CC.5040303@mattnordhoff.com> mr.opus.penguin at gmail.com wrote: > As a new comer to Python I was wondering which is the best to start > learning. I've read that a number of significant features have > changed between the two versions. Yet, the majority of Python > programs out in the world are 2.x and it would be nice to understand > those as well. Thanks for all the help. > > Creosote, You should learn Python 2. Python 3 is only in alpha/beta, and it won't be very relevant for several years. Python 3 isn't a whole new language; it just breaks backwards compatibility to clean up old warts and make other improvements. It won't be too hard to transition to it when you decide to. -- From M8R-yfto6h at mailinator.com Mon Jun 23 23:38:51 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Mon, 23 Jun 2008 20:38:51 -0700 Subject: String question References: <695fec18-8a3a-48e1-b467-d4957f9065fa@26g2000hsk.googlegroups.com> Message-ID: "Andreu" wrote in message news:g3p72i$432$1 at aioe.org... > Yes, ... don't ask me why, but in fact v1,v2,v3 = str1.split() > does not seem to work. My original problem was I forgot about > the parenthesis as Tim point out. So I ended up converting to a > list as in: v = str1.split() and accessing the elements using > v[0] v[1] ect...it is working now. Thanks. > > Andreu. v1,v2,v3 = str1.split() will only work if there are exactly three things in str1. >>> s = 'this is a test' >>> v1,v2,v3 = s.split() Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack >>> v1,v2,v3 = s.split(' ',2) # limit to two splits maximum >>> v1 'this' >>> v2 'is' >>> v3 'a test' -Mark From tjreedy at udel.edu Fri Jun 13 17:51:14 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 13 Jun 2008 17:51:14 -0400 Subject: Point Of intersection between two plotted functions References: <2fd19881-27f8-48f3-bfa9-2d8a26f31920@26g2000hsk.googlegroups.com> Message-ID: wrote in message news:2fd19881-27f8-48f3-bfa9-2d8a26f31920 at 26g2000hsk.googlegroups.com... | Is there anyway one could find ot the point of intersection between | any two plotted functions Assume you have sequence xi, yi, zi, where yi and zi are function values corresponding to xi. In general, you will never have exact intersection with yi==zi. So in addition, look for successive triples xi,yi,zi and x(i+1), y(i+1), z(i+1) such that yiz(i+1) or the other way around. In other words, zi-yi and z(i+1)-y(i+1) have opposite signs. You might want to also consider abs(zi-yi) < some very small number as possibly indicating touching without crossing (as with tangents). From george.sakkis at gmail.com Wed Jun 18 17:34:39 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 18 Jun 2008 14:34:39 -0700 (PDT) Subject: extra positional arguments before optional parameters syntax References: Message-ID: <4450093c-874f-420f-8d0b-09fbf6f07574@p25g2000hsf.googlegroups.com> On Jun 18, 5:25 pm, MisterWilliam wrote: > I noticed that in PEP 3105, the PEP about turning print to print(), > the syntax for print() is defined as follows: > def print(*args, sep=' ', end='\n', file=None) > > Ignoring the fact that print is a reserved keyword in python, this is > not valid python because extra positional arguments (*args), cannot > come before optional parameters (sep=' ', end='\n', file=None). > > >>> def f(*args, sep=' ', end='\n', file=None): > > File "", line 1 > def f(*args, sep=' ', end='\n', file=None): > ^ > SyntaxError: invalid syntax > > Am I misunderstanding something? Is this type of syntax suppose to be > allowed in a future version of Python? (I can't find anything about > this through my searching.) You didn't search hard enough; it's three PEPs earlier: http://www.python.org/dev/peps/pep-3102/ George From steven.p.clark at gmail.com Wed Jun 25 22:38:54 2008 From: steven.p.clark at gmail.com (Steven Clark) Date: Wed, 25 Jun 2008 22:38:54 -0400 Subject: struct.pack behavior In-Reply-To: References: Message-ID: <663744510806251938x7de7e56dg1e2f1ade0892da50@mail.gmail.com> On Wed, Jun 25, 2008 at 7:03 PM, John Machin wrote: > On Jun 26, 9:00 am, "Steven Clark" wrote: >> Can anyone explain to me why >> struct.pack('HB',1,2) gives 3 bytes, whereas struct.pack('BH',1,2) >> gives 4 bytes? >> > Alignment -- read the manual. > -- > http://mail.python.org/mailman/listinfo/python-list > If "the manual" is the help files for the struct module, I've read it several times over. I understand endianness; I don't understand alignment. Could anyone give a less cryptic / terse answer? From phillip.oldham at gmail.com Fri Jun 13 03:38:09 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Fri, 13 Jun 2008 00:38:09 -0700 (PDT) Subject: Comments on my first script? References: <7e3a7c92-6204-46dd-8df8-90218f2fb314@26g2000hsk.googlegroups.com> <4016716e-0ff7-41aa-951a-ed9562ff2ac8@m44g2000hsc.googlegroups.com> Message-ID: <7bb26acf-8b58-4d29-8e64-05a75eb5e584@d45g2000hsc.googlegroups.com> Thanks guys. Those comments are really helpful. The odd semi-colon is my PHP background. Will probably be a hard habbit to break, that one! ;) If I do accidentally drop a semi-colon at the end of the line, will that cause any weird errors? Also, Chris, can you explain this: a, b = line.split(': ')[:2] I understand the first section, but I've not seen [:2] before. From mcashcash at gmail.com Wed Jun 4 08:03:51 2008 From: mcashcash at gmail.com (mcashcash at gmail.com) Date: Wed, 4 Jun 2008 05:03:51 -0700 (PDT) Subject: Earn = 10,000 US Dollars per month without Investment. Message-ID: <704df407-1108-430c-a2e5-c4860062b52d@i18g2000prn.googlegroups.com> You Have Finally Found It Earn!! = 10,000 US Dollars per month without Investment Genuine Lifetime Income!! http://seniorfriendfinder.com/go/g970599-pmem http://seniorfriendfinder.com/go/g970599-pct http://seniorfriendfinder.com/go/g970599-brk http://alt.com/go/g900909-ppc http://govindswamy-govindaswamy.blogspot.com http://govindaswamy-amman.blogspot.com From francis.girardpython at gmail.com Wed Jun 18 08:27:07 2008 From: francis.girardpython at gmail.com (Francis Girard) Date: Wed, 18 Jun 2008 08:27:07 -0400 Subject: Interpreting string containing \u000a In-Reply-To: References: Message-ID: Thank you very much ! I didn't know about this 'unicode-escape'. That's great! Francis 2008/6/18 Duncan Booth : > "Francis Girard" wrote: > > > I have an ISO-8859-1 file containing things like > > "Hello\u000d\u000aWorld", i.e. the character '\', followed by the > > character 'u' and then '0', etc. > > > > What is the easiest way to automatically translate these codes into > > unicode characters ? > > > > >>> s = r"Hello\u000d\u000aWorld" > >>> print s > Hello\u000d\u000aWorld > >>> s.decode('iso-8859-1').decode('unicode-escape') > u'Hello\r\nWorld' > >>> > > -- > Duncan Booth http://kupuguy.blogspot.com > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hat at se-162.se.wtb.tue.nl Wed Jun 25 02:57:38 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 25 Jun 2008 08:57:38 +0200 Subject: Problem found in tutorial References: Message-ID: On 2008-06-25, John W. Hamill wrote: > 20JUN2008 > By John W. Hamill > > > Errata found in Python tutorial > http://www.python.org Bugs and other problems should be reported in bugs.python.org Otherwise they will probably get lost. > Error Found by John W. Hamill > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > - - > C:\__jh\ftp\python\2_5_2\doc\tutorial\node11.html Next time, please also add a URL that is usable for a larger group of people than those that have access to your C: drive. (Generator expression examples, Section 9.11, see http://docs.python.org/tut/node11.html#SECTION00111100000000000000000) >>>> unique_words = set(word for line in page for word in line.split()) > >>>> valedictorian = max((student.gpa, student.name) for student in > graduates) > > NOTE: page and graduates are not defined and this won't run without them. > I defined them like so to make this work: Correctly seen. Report at bugs.python.org ! > page = ("The quick brown","fox jumped over","the lazy dog's","back 123 > times." ) > > class Graduate: Always derive new classes from object as in class Graduate(object): > def __init__(self, name, gpa): > self.name = name > self.gpa = gpa and indentation is normally 4 spaces, at least in public Python documentation. > gpa = 0 > name = "" Why do you introduce two class variables with the same name? (not useful, you can delete them) > > graduates = (Graduate("Charlie Brown",8.09), Graduate("Snoopy",3.7), > Graduate("Lucy Brown",3.5)) > Albert From dfnsonfsduifb at gmx.de Fri Jun 13 10:32:37 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Fri, 13 Jun 2008 16:32:37 +0200 Subject: pgdb connection string Message-ID: <51dai5xjnc.ln2@joeserver.homelan.net> Hello group, I've run into a small problem with pgdb which is actually not PostgreSQL specific - I just do not understand the Python syntax at one point. I'm trying to initialize a connection to a PG database. So help(pgdb) says: pgdb.connect(connect_string) -> connection connect_string = 'host:database:user:password:opt:tty' All parts are optional. You may also pass host through password as keyword arguments. To pass a port, pass it in the host keyword parameter: pgdb.connect(host='localhost:5432') Now from what I understand is that it accepts a string in the form: "%s:%s:%s:%s" % (conf["db"]["hostname"], conf["db"]["database"], conf["db"]["username"], conf["db"]["password"]) Which actually works. But if I want to pass the port, there's one more colon and it parses garbage. So what exactly is this host="foobar" syntax all about? What exactly is passed to pgdb.connect (because it does not seem to be a string) - is it a dictionary or something? I'm puzzled. Regards, Johannes -- "Wer etwas kritisiert muss es noch lange nicht selber besser k?nnen. Es reicht zu wissen, da? andere es besser k?nnen und andere es auch besser machen um einen Vergleich zu bringen." - Wolfgang Gerber in de.sci.electronics <47fa8447$0$11545$9b622d9e at news.freenet.de> From ivan.illarionov at gmail.com Wed Jun 4 12:35:50 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 4 Jun 2008 16:35:50 +0000 (UTC) Subject: Extending Python with C: Can I specify another C compiler? References: <625c63a6-8f71-48db-9f6a-e3f43b487472@56g2000hsm.googlegroups.com> Message-ID: On Wed, 04 Jun 2008 09:12:18 -0700, spectrumdt wrote: > Hello. > > I am trying to extend my Python program with some C code. > > This thread is sort of a follow-up to another thread of mine, linked > below. I don't know what the conventions are in this newsgroup about > creating new threads vs. staying in existing ones, but I figured I'd > rather make a new one with a title pertaining to my current problem. > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/ d60449f4db19f731# > > Anyway, my question is this: When compiling my C code to include in > Python, using a Python script with the function distutils.core.setup... > can I choose which C compiler to use? On my system it defaults to gcc, > but I would like to use mpicc instead (C compiler for MPI, Message > Passing Interface). > > Can I do this? > > My system, in case it matters, is Fedora Linux. > > Thanks in advance. There is -c option for setup.py build and setup.py build_ext. If it doesn't work for your compiler you probably have to build your extensions manually. Ivan From sylvain.vivien at gmail.com Sat Jun 7 03:49:41 2008 From: sylvain.vivien at gmail.com (Sylvain) Date: Sat, 7 Jun 2008 00:49:41 -0700 (PDT) Subject: cgi, parse_header and semi-colon References: Message-ID: <99af23e4-4a64-48dd-8537-a123db8147b5@b1g2000hsg.googlegroups.com> On Jun 6, 5:33 pm, "Richard Brodie" wrote: > "Sylvain" wrote in message > > news:b80af57f-897d-4fd1-bebc-df0782143314 at 25g2000hsx.googlegroups.com... > > > If we upload a file with a semi-colon (i.e : "C:/my;file.jpg") : > > cgi.FieldStorage.filename returns only "my" everything after the semi- > > colon is missing > > > Is it a bug or i'm missing something ? > > I doubt it's bug inparse_header, since it's meant to split on > semicolons. Whether it's a bug in one of its callers, or the client > not escaping sufficiently, I couldn't say offhand. I've printed the filename in the content-disposition header : filename="my;file.jpg" If you look at the http://www.ietf.org/rfc/rfc2183.txt about "content- disposition" : "A short parameter value containing only ASCII characters, but including `tspecials' characters, SHOULD be represented as `quoted- string'." So my header is correct but i think there is clearly a bug in the parse_header and "content-disposition" should not be "splitted" only with the split(';') method but should look at quoted-string too. Regards From bearophileHUGS at lycos.com Mon Jun 9 10:04:31 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 9 Jun 2008 07:04:31 -0700 (PDT) Subject: Q re documentation Python style References: Message-ID: kj: > I have some functions > that require a very long docstring to document, and somehow I find > it a bit disconcerting to stick a few screenfuls of text between > the top line of a function definition and its body. You may put the main function(s) documentation in the docstring of the module, and a much shorter version in the docstring of the function. Bye, bearophile From gagsl-py2 at yahoo.com.ar Tue Jun 3 22:45:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 03 Jun 2008 23:45:16 -0300 Subject: Different execution time in python code between embedded or standalone References: <207312b70806031258n68b9dfl942e098e5119c1dc@mail.gmail.com> Message-ID: En Tue, 03 Jun 2008 16:58:12 -0300, Pau Freixes escribi?: > Hi list, > > First Hello to all, this is my and hope not end message to the list :P > > This last months I have been writting a program in c like to mod_python > for > embedding python language, it's a middleware for dispatch and execute > python > batch programs into several nodes. Now I'm writing some python program > for > test how scale this into several nodes and comparing with "standalone" > performance. > > I found a very strange problem with one application named md5challenge, > this > aplication try to calculate the max number md5 digest in several seconds, > md5challenge use a simple signal alarm for stop program when time has > passed. This is the code of python script > > def handler_alrm(signum, frame): > global _signal > global _nrdigest > global _f > > > _signal = True > > def try_me(): > global _nrdigest > global _f > global _signal > > _f = open("/dev/urandom","r") > while _signal is not True: > buff = _f.read(_const_b) > md5.md5(buff).hexdigest() > _nrdigest = _nrdigest + 1 > > if _f is not None : > _f.close() > > def main( req ): > global _nrdigest > > > signal.signal(signal.SIGALRM, handler_alrm) > signal.alarm(req.input['time']) > > > try_me() > > req.output['count'] = _nrdigest > > return req.OK > > > if __name__ == "__main__": > > # test code > class test_req: > pass > > req = test_req() > req.input = { 'time' : 10 } > req.output = { 'ret' : 0, 'count' : 0 } > req.OK = 1 > > main(req) > > print "Reached %d digests" % req.output['count'] > > > When I try to run this program in standalone into my Pentium Dual Core > md4challenge reached 1.000.000 milion keys in 10 seconds but when i try > to > run this in embedded mode md5challenge reached about 200.000 more keys > !!! I > repeat this test many times and always wins embedded mode !!! What's > happen ? > > Also I tested to erase read dependencies from /dev/random, and calculate > all > keys from same buffer. In this case embedded mode win always also, and > the > difference are more bigger !!! > > Thks to all, can anybody help to me ? So the above code corresponds to the standalone version - what about the embedded version? Are you sure it is exactly the *same* code? All those global statements are suspicious, and you don't even need most of them. Note that looking up a name in the global namespace is much slower than using a local name. Also, you're including the time it takes the OS to *generate* several megabytes of random data from /dev/urandom (how big is _const_b?). Usually it's easier (and more accurate) to measure the time it takes to compute a long task (let's say, how much time it takes to compute 1000000 md5 values). You're doing it backwards instead. I'd rewrite the test as: def try_me(): from md5 import md5 buff = os.urandom(_const_b) for i in xrange(1000000): md5(buff).hexdigest() def main(req): t0 = time.clock() try_me() t1 = time.clock() # elapsed time = t1-t0 PS: Recuerdo que respond? esto en la lista de Python en castellano, pero ahora veo que mi mensaje nunca lleg? :( -- Gabriel Genellina From ram.rachum at gmail.com Sun Jun 15 15:08:08 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Sun, 15 Jun 2008 12:08:08 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com><3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> Message-ID: <6fb5a49a-d50a-4dac-942d-ab98a369bb25@r66g2000hsg.googlegroups.com> On Jun 15, 10:01?pm, "Terry Reedy" wrote: > wrote in message > > news:1257aa24-14fa-426e-8019-262984c70633 at 2g2000hsn.googlegroups.com... > |> How did you determine that standard python floats are not good enough? > > | I have a physical system set up in which a body is supposed to > | accelerate and to get very close to lightspeed, while never really > |attaining it. > > Just a thought. ?You might do better if you can rearrange your equations in > terms of c-v instead of v. ?Letting c=1, you cannot accutrately express > v = .99999999999999999999 > in Python, but can easily express > 1-v = .00000000000000000001. > And so on. > > tjr Good idea Terry, I'll think about it. From praveen.sunsetpoint at gmail.com Thu Jun 19 01:08:38 2008 From: praveen.sunsetpoint at gmail.com (Sallu) Date: Wed, 18 Jun 2008 22:08:38 -0700 (PDT) Subject: =?ISO-8859-1?Q?Regular_expressions_for_accents_like_=F3_character_in?= =?ISO-8859-1?Q?_python?= Message-ID: i want to restrict to user to not enter accents character. si i need to make an Regular expressions for accents like ? character From __peter__ at web.de Mon Jun 2 17:06:29 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 Jun 2008 23:06:29 +0200 Subject: [Re] Checking each item in m.group()? References: Message-ID: nospam at nospam.com wrote: > I need to go through each line of a CSV file, and extract some fields > using a regex. Then, I need to check each retrieved field, and if it > looks like "", turn this into NULL so that it's correct SQL. You are taking the wrong approach here. Don't build SQL statements as strings; you are enabling the next SQL injection attack. Pass parameters using the DB API instead. Don't use regular expressions to parse a CSV file. Python's csv module is more likely to deal correctly with the quirks of that standard. A self-contained example: import csv import sqlite3 as sqlite from cStringIO import StringIO def records(infile): for row in csv.reader(infile): # replace empty strings in the second column with None # which translates to NULL in the database yield row[0], row[1] or None def main(): # create sample data; you may use a real file infile = StringIO("""\ alpha,beta,gamma zeta,,theta """) # create the database db = sqlite.connect(":memory:") cursor = db.cursor() cursor.execute("create table demo (first, second);") # safely insert data cursor.executemany("insert into demo values (?, ?);", records(infile)) # show contents for row in cursor.execute("select first, second, second is NULL " "from demo order by first, second;"): print row if __name__ == "__main__": main() Peter From musiccomposition at gmail.com Sat Jun 7 23:09:45 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sat, 7 Jun 2008 20:09:45 -0700 (PDT) Subject: ABC question: what is the purpose of the register() method? References: <22c53e8d-1f95-465f-932e-b0b0bbf148ba@x41g2000hsb.googlegroups.com> Message-ID: On Jun 7, 1:37 pm, Kay Schluehr wrote: > I was reading PEP 3119 (http://www.python.org/dev/peps/pep-3119/) and > have done some experiments using Python 3.0a5. Now I'm somewhat > puzzled about the purpose of the ABCMeta.register() method. > > One can use the register() method to register any class as a virtual > subclass of any ABC. For example one can register `int` on `Iterable` > and therefore it is a subclass which is confirmed in the issubclass > check. What is that good for? It's mostly good for types created in C, where it's hard to inherit a class. For example, builtin types register them selves under some ABCs in collections. From ppearson at nowhere.invalid Fri Jun 20 12:11:17 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: Fri, 20 Jun 2008 11:11:17 -0500 Subject: Tkinter canvas drag/drop obstacle Message-ID: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> Tkinter makes it very easy to drag jpeg images around on a canvas, but I would like to have a "target" change color when the cursor dragging an image passes over it. I seem to be blocked by the fact that the callbacks that might tell the target that the mouse has entered it (, , even ) aren't called if the mouse's button is down. What am I missing? Have I failed to find the right Tkinter document? Is Tkinter the wrong tool for this job? Thanks. -- To email me, substitute nowhere->spamcop, invalid->net. From georgeoliverGO at gmail.com Sat Jun 28 03:49:42 2008 From: georgeoliverGO at gmail.com (George Oliver) Date: Sat, 28 Jun 2008 00:49:42 -0700 (PDT) Subject: 2D online multiplayer framework? Message-ID: <6dc6195b-b8a0-42a9-a982-3a4b70943c24@r37g2000prm.googlegroups.com> I'm looking for a framework to support a 2D online real-time multiplayer game (rugby league football with a lo-fi pixel look). The GameProgramming page at the Python wiki had some suggestions but so far nothing looks that promising, does anyone have some recommendations? It would be ideal to play this through a web browser but I don't know if that's practical. This aspect of programming is pretty new to me so I'm not sure if I should start with something general like Twisted or if there's a different path I should take. thanks, George From weheh at yahoo.com Sun Jun 22 16:00:01 2008 From: weheh at yahoo.com (weheh) Date: Sun, 22 Jun 2008 20:00:01 GMT Subject: pyTTS says, '"SAPI" not supported' Message-ID: <5by7k.2739$gE.1491@trnddc07> I'm running Python 2.3 and calling pyTTS. I've had it working forever. Today, I ran out of disk space. After deleting some of my personal files, for no apparent reason, pyTTS no longer runs. For the statement tts = pyTTS.Create() I get the error message: ValueError: "SAPI" not supported Can anybody help me? What's going on? From sjmachin at lexicon.net Thu Jun 26 04:56:08 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 26 Jun 2008 01:56:08 -0700 (PDT) Subject: Freeze problem with Regular Expression References: <6cf614F3f8ocoU1@mid.individual.net> <0e1a9726-cc1d-4bd2-b0ba-b2bcc1c27ee8@f24g2000prh.googlegroups.com> Message-ID: <2969ef42-c4a6-4950-8522-df58a4138776@q24g2000prf.googlegroups.com> On Jun 26, 8:29?am, John Machin wrote: > (2) ALWAYS use a raw string for regexes; your \s* will match on lower- > case 's', not on spaces and should have written: (2) ALWAYS use a raw string for regexes. <<<=== Big fat full stop aka period. but he was at the time only half-way through the first cup of coffee for the day :-) From stef.mientki at gmail.com Mon Jun 30 15:04:12 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 30 Jun 2008 21:04:12 +0200 Subject: list extension ? In-Reply-To: <4868b0ba$0$17063$426a34cc@news.free.fr> References: <4868b0ba$0$17063$426a34cc@news.free.fr> Message-ID: <48692E2C.1090406@gmail.com> thanks guys, > >> def __init__ ( self, value = [] ) : > > Gotcha : default argument values are eval'd only once. Also, it would > make more sense IMHO to follow the parent's class initializer's > behaviour: > > def __init__(self, *args) > >> list.__init__ ( self, value ) > > list.__init__(self, *args) > that's even better, except the call must be list.__init__ ( self, args ) cheers, Stef From hamish at valvesoftware.com Fri Jun 20 17:19:37 2008 From: hamish at valvesoftware.com (Hamish McKenzie) Date: Fri, 20 Jun 2008 14:19:37 -0700 Subject: inheritance question... In-Reply-To: References: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> <09ec833f-7751-4991-8d09-45c200fb4c18@z72g2000hsb.googlegroups.com> Message-ID: <587C2C9324493D4B96BD6BBCDEAC321AA95911@exchange3.valvesoftware.com> I have this class: class Vector(object): TOL = 1e-5 def __eq__( self, other, tolerance=TOL ): print tolerance shortened for clarity obviously. so I want to subclass this class like so: class BigVector(Vector) TOL = 100 for example if I was working with large vectors which I knew would never be very close hence the large tolerance. this doesn't work however - the TOL class variable, while overridden in BigVector, is still using the Vector.TOL variable in the __eq__ method. which kinda makes sense to a certain degree, but how do I get the behaviour where doing: BigVector().__eq__( otherVec ) prints 100 instead of 1e-5? does this question make sense? not sure how clearly I'm phrasing my question... any of you guys python experts? I *could* do this, but its ugly: class Vector(object): TOL = 1e-5 def __eq__( self, other, tolerance=None ): if tolerance is None: tolerance = self.TOL print tolerance From jonhune at yahoo.com Thu Jun 5 18:53:52 2008 From: jonhune at yahoo.com (Jon Hune) Date: Thu, 5 Jun 2008 15:53:52 -0700 (PDT) Subject: soaplib newbie question Message-ID: <729667.58494.qm@web46312.mail.sp1.yahoo.com> hi everyone, I'm totally new to SOAP. Can anyone help with this soap question. I'm trying to use soaplib. I can't find many examples on using soaplib and what I have below if the standard hello world example I find online. Say I want to call the zzz service at yyy. I know that the service inputs are two integers and a string (say a,b,c), and the output is three strings (say d,e,f). URL = "http://www.yyy.com/yyy.wsdl" a = 1 b = 2 c = "3" from soaplib.wsgi_soap import SimpleWSGISoapApp from soaplib.service import soapmethod from soaplib.serializers.primitive import String, Integer, Array class YYY(SimpleWSGISoapApp): @soapmethod(Integer, Integer, String, _returns = Array(String)) def zzz(self, a, b, c): pass from soaplib.client import make_service_client client = make_service_client(URL, YYY()) print client.zzz(a, b, c) I get this error: $ python x.py Traceback (most recent call last): File "x.py", line 32, in orderNumber) File "/usr/lib/python2.5/site-packages/soaplib-0.7.1dev_r17-py2.5.egg/soaplib/ client.py", line 157, in __call__ payload, headers = from_soap(data) File "/usr/lib/python2.5/site-packages/soaplib-0.7.1dev_r17-py2.5.egg/soaplib/ soap.py", line 96, in from_soap if len(body.getchildren()): AttributeError: 'NoneType' object has no attribute 'getchildren' Another question I have is what happens when the output is say an integer and a string? I can't find an example for soaplib. In the above case, the output is 3 strings. I used Array(String). I'm not even sure if that's correct. How should I for instance specify output of an integer and a string? thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From squareswallower at 1ya2hoo3.net Sun Jun 1 17:14:44 2008 From: squareswallower at 1ya2hoo3.net (dave) Date: Sun, 1 Jun 2008 15:14:44 -0600 Subject: Bring object 'out of' Class? References: Message-ID: > Then you can write: > >>>> hands = deck.deal_cards(4, 5) # On fait une belotte? > > And I don't see the need of defining 'Hand' inside 'Deck'. > > HTH Thanks for the input. I believe using 'class Hand(Deck):' is to illustrate (in the book) inheritance and how it can be used. By using 'Hand(Deck)' I can then use the methods (pop_card, add_cards, etc..) defined in the 'Deck' class. From maric at aristote.info Fri Jun 27 06:27:16 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 27 Jun 2008 12:27:16 +0200 Subject: using urllib2 In-Reply-To: <18150669.post@talk.nabble.com> References: <18150669.post@talk.nabble.com> Message-ID: <200806271227.17081.maric@aristote.info> Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit?: > I have never used the urllib or the urllib2. I really have looked online > for help on this issue, and mailing lists, but I can't figure out my > problem because people haven't been helping me, which is why I am here! :]. > Okay, so basically I want to be able to submit a word to dictionary.com and > then get the definitions. However, to start off learning urllib2, I just > want to do a simple google search. Before you get mad, what I have found on > urllib2 hasn't helped me. Anyway, How would you go about doing this. No, I > did not post the html, but I mean if you want, right click on your browser > and hit view source of the google homepage. Basically what I want to know > is how to submit the values(the search term) and then search for that > value. Heres what I know: > > import urllib2 > response = urllib2.urlopen("http://www.google.com/") > html = response.read() > print html > > Now I know that all this does is print the source, but thats about all I > know. I know it may be a lot to ask to have someone show/help me, but I > really would appreciate it. This example is for google, of course using pygoogle is easier in this case, but this is a valid example for the general case : >>>[207]: import urllib, urllib2 You need to trick the server with an imaginary User-Agent. >>>[208]: def google_search(terms) : return urllib2.urlopen(urllib2.Request("http://www.google.com/search?" + urllib.urlencode({'hl':'fr', 'q':terms}), headers={'User-Agent':'MyNav 1.0 (compatible; MSIE 6.0; Linux'}) ).read() .....: >>>[212]: res = google_search("python & co") Now you got the whole html response, you'll have to parse it to recover datas, a quick & dirty try on google response page : >>>[213]: import re >>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

.*?

', res) ] ...[229]: ['Python Gallery', 'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des Monty ...', 'Re: os x, panther, python & co: msg#00041', 'Re: os x, panther, python & co: msg#00040', 'Cardiff Web Site Design, Professional web site design services ...', 'Python Properties', 'Frees < Programs < Python < Bin-Co', 'Torb: an interface between Tcl and CORBA', 'Royal Python Morphs', 'Python & Co'] -- _____________ Maric Michaud From bruno.42.desthuilliers at websiteburo.invalid Tue Jun 10 04:04:10 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 10 Jun 2008 10:04:10 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <4847d39d$0$7614$426a74cc@news.free.fr> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> <484cf5f6$0$15495$426a74cc@news.free.fr> <127975a3-b3d9-4799-9673-b292ec8d37e3@x19g2000prg.googlegroups.com> <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> Message-ID: <484e3526$0$30894$426a74cc@news.free.fr> Russ P. a ?crit : > On Jun 9, 2:10 pm, "bruno.desthuilli... at gmail.com" > wrote: > >> But if it takes 6 month to get the mentioned developer to release >> something I can use, I'm screwed up. Fine. > > I've lost track of how many times I've said this now, but my > suggestion for a "priv" keyword allowed for "indirect" access to > private data through some name-mangling scheme. And I've lost track of how many times I've said this now, but we already have this. While we're at it, why not a 'prot' keyword that would restrict name-mangling to the addition of a single leading underscore ? > That could be your > temporary fix while you are waiting for the developer to release a > corrected version. And even if that option were not available, you > could simply open up the relevant source file in the editor of your > choice and remove the offending "priv" declaration. Yes. And I can always edit the source code and add the methods I need etc. You probably never used monkeypatching, so I guess you just can't understand the difference between maintaining a monkeypatch and maintaining a fork. > I completely fail > to see how you are "screwed." > Sorry, but when I have to keep repeating the same basic points over > and over, I can't help but think I might be wasting my time. If you hope to get a general agreement here in favor of a useless keyword that don't bring anything to the language, then yes, I'm afraid you're wasting your time. From michael at stroeder.com Mon Jun 16 09:47:49 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Mon, 16 Jun 2008 15:47:49 +0200 Subject: Who is using python-ldap with Python 1.5.x and 2.0-2.2? Message-ID: <6h7ii5-l9m.ln1@nb2.stroeder.com> HI! I'd like to hear from the Python community whether support for Python version prior to 2.3 is still needed in python-ldap. Please tell me which Python version you're using and why it'd be important for you to have python-ldap updates still supporting it. BTW: Actually older Python versions are not tested with recent python-ldap since at least two years. But I'd like to clearly decide on that. Ciao, Michael. From cwitts at gmail.com Fri Jun 6 04:31:56 2008 From: cwitts at gmail.com (Chris) Date: Fri, 6 Jun 2008 01:31:56 -0700 (PDT) Subject: import cherrypy2 References: Message-ID: On Jun 6, 10:22?am, luca72 wrote: > Hello i can't import cherrypy2 but i don't know why this is the sys > path: > > '', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > setuptools-0.6c7-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg', '/home/pirataja/ > opo.net/python/lib/python2.5/site-packages/TurboKid-1.0.4-py2.5.egg', > '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > TurboJson-1.1.2-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > python2.5/site-packages/TurboCheetah-1.0-py2.5.egg', '/home/pirataja/ > opo.net/python/lib/python2.5/site-packages/simplejson-1.9.1-py2.5- > linux-i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site- > packages/RuleDispatch-0.5a0.dev_r2306-py2.5-linux-i686.egg', '/home/ > pirataja/opo.net/python/lib/python2.5/site-packages/PasteScript-1.6.2- > py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > FormEncode-1.0.1-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > python2.5/site-packages/DecoratorTools-1.7-py2.5.egg', '/home/pirataja/ > opo.net/python/lib/python2.5/site-packages/configobj-4.5.2-py2.5.egg', > '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > CherryPy-2.3.0-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > python2.5/site-packages/kid-0.9.6-py2.5.egg', '/home/pirataja/opo.net/ > python/lib/python2.5/site-packages/Cheetah-2.0.1-py2.5-linux- > i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > PyProtocols-1.0a0dev_r2302-py2.5-linux-i686.egg', '/home/pirataja/ > opo.net/python/lib/python2.5/site-packages/PasteDeploy-1.3.1- > py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > Paste-1.7-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > python25.zip', '/home/pirataja/pirata-jacopo.net/python/lib/ > python2.5', '/home/pirataja/opo.net/python/lib/python2.5/plat- > linux2', > '/home/pirataja/opo.net/python/lib/python2.5/lib-tk', > '/home/pirataja/opo.net/python/lib/python2.5/lib-dynload', '/home/ > pirataja/opo.net/python/lib/python2.5/site-packages'] > > For my is all ok but whe i do import cherrypy2 i get no mudule name > cherrypy2 > > Regards > > Luca because it's "import cherrypy" and not "import cherrypy2" From omer at no-log.org Sat Jun 21 11:46:33 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Sat, 21 Jun 2008 17:46:33 +0200 Subject: Way to unblock sys.stdin.readline() call In-Reply-To: <56b21108-45b4-4b9e-bda5-171c9ddc21ce@i76g2000hsf.googlegroups.com> References: <56b21108-45b4-4b9e-bda5-171c9ddc21ce@i76g2000hsf.googlegroups.com> Message-ID: <200806211746.33397.omer@no-log.org> Le Saturday 21 June 2008 15:26:53 joamag, vous avez ?crit?: > HI, > > Is there any possible way to unblock the sys.stdin.readline() call > from a different thread. > Something like sys.stdin.write() but that would actually work ... > something to put characters in the stdin... > Do you mean setting stdin in non-blocking mode ? On unix you can do it with the fcntl module (you'll find more infos in the libc docs) : fcntl.fcntl(sys.stdin, fcntl.F_SETFL, os.O_NONBLOCK) and catch IOErrors with errno = EAGAIN. But I don't know how to do it in a portable way, suggestions welcome :) -- C?dric Lucantis From termim at gmail.com Mon Jun 30 15:34:53 2008 From: termim at gmail.com (Mike) Date: Mon, 30 Jun 2008 12:34:53 -0700 (PDT) Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> Message-ID: On Jun 30, 1:49?pm, "bruno.desthuilli... at gmail.com" wrote: > > > Then what is so *good* about it, why embedding HTML into Python is not > > good? > > Who said embedding HTML in Python was bad ? Did you _carefully_ read > John's question ?-) > I should have say "why embedding HTML into Python is not good enough?" ;=) > wrt/ what's so good about it: web designers are usually better at > working with this approach (whatever scripting language embedded in > html) than they are writing Python code - either as plain strings or > using a more declarative syntax like the one provided by Stan or I keep reading this argument that some mythical 'web designers' are usually better at working with this abracadabra (TAL etc.). BTW, most of the times it is used by programmers :). Sorry, I can't believe it. Sure there are some people that enjoy reading Perl or JCL, but all of them? IMHO if 'web designer' is able to separate HTML syntax from 'embedded language' syntax, then he is perfectly able to understand clear and simple Python code. > equivalent html generators. ?But nothing prevents you from using > Mako's internals directly if you find it easier and more > maintainable !-) Yea, that is a perfect and universal advise - use whatever fits you best!;:=} From fc14301589 at icqmail.com Wed Jun 11 10:16:56 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Wed, 11 Jun 2008 22:16:56 +0800 Subject: My fight with classes :) Message-ID: <484fde63_1@news.tm.net.my> Hi, I'm very new with classes. I still reading something around ;) I got started to try a concatenation of 2 type of string, which have a particular property to start with A or D. My class here: """ Small class to join some strings according to the leading first letter""" def __init__(self): self.valueA= '' self.valueD= '' def __add__(self, value): if not isinstance(value, str): return if value.lower().startswith('a'): self.valueA += value if value.lower().startswith('d'): self.valueD += value return self.valueA ,self.valueD __call__= __add__ __iadd__= __add__ my test on the shell: >>> from utilities import StrJoin as zx >>> k= zx() >>> k >>> k +'aks' ('aks', '') >>> k +'daks' ('aks', 'daks') >>> k +'hdaks' ('aks', 'daks') >>> k +'dhks' ('aks', 'daksdhks') >>> j('boi') Traceback (most recent call last): File "", line 1, in NameError: name 'j' is not defined >>> k('boi') ('aks', 'daksdhks') >>> k('aboi') ('aksaboi', 'daksdhks') >>> k('duboi') ('aksaboi', 'daksdhksduboi') >>> k += 'liu' >>> k += 'aliu' Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate tuple (not "str") to tuple >>> k ('aksaboi', 'daksdhksduboi') Do I miss something? I'd rather like to avoid class, but a function won't allow me to store so easily data between several call. Mostly I'd expect to pass to the built instance in a more elaborated function. Then I mean call will be the primer goal. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From gh at ghaering.de Mon Jun 30 09:52:56 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 30 Jun 2008 15:52:56 +0200 Subject: List Performance In-Reply-To: <2eydnaP-saOZQfXVnZ2dnUVZ_qvinZ2d@comcast.com> References: <42358e0b-a351-4862-8f6a-1938eedeff6c@s21g2000prm.googlegroups.com> <2eydnaP-saOZQfXVnZ2dnUVZ_qvinZ2d@comcast.com> Message-ID: Larry Bates wrote: > [...] > So its actually faster to append to a long list than an empty one? That > certainly would not have been intuitively obvious now would it? Maybe not intuitively, but if you know how dynamically growing data structures are implemented, it's plausible. They overallocate, and the amount of overallocation is dependent on the current size. Relevant source snippet from Python 2.6: /* This over-allocates proportional to the list size, making room * for additional growth. The over-allocation is mild, but is * enough to give linear-time amortized behavior over a long * sequence of appends() in the presence of a poorly-performing * system realloc(). * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... */ new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6); If, on the other hand, we knew beforehand how big the list will get approximately, we could avoid all these reallocations. No problem with Python's C API: PyAPI_FUNC(PyObject *) PyList_New(Py_ssize_t size); But you can't do it directly from Python, unless you (ab)use ctypes. -- Gerhard From jarausch at igpm.rwth-aachen.de Fri Jun 13 03:39:22 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Fri, 13 Jun 2008 09:39:22 +0200 Subject: ANN: eGenix pyOpenSSL Distribution 0.7.0-0.9.8h-1 In-Reply-To: References: Message-ID: <4852242A.5000507@igpm.rwth-aachen.de> eGenix Team: M.-A. Lemburg wrote: > ________________________________________________________________________ > > ANNOUNCING > > eGenix.com pyOpenSSL Distribution > > Version 0.7.0-0.9.8h-1 > > > An easy to install and use repackaged distribution > of the pyOpenSSL Python interface for OpenSSL - > available on Windows and Unix platforms > > > This announcement is also available on our web-site for online reading: > http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.7.0-0.9.8h-1-GA.html Just to mention downloading the source doesn't work. Under requirements (to compile the source) there is mxbase version >= 3.0.1 which I couldn't find on your web server. Many thanks, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From M8R-yfto6h at mailinator.com Sat Jun 7 10:19:42 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Sat, 7 Jun 2008 07:19:42 -0700 Subject: Parsing a path to components References: <7d7dd66c-b2bb-4a9a-a2e4-589079cda97b@e39g2000hsf.googlegroups.com> <14bf5448-4677-4ced-9d79-b4eb0c048218@56g2000hsm.googlegroups.com> <6auuc5F38s3s9U1@mid.uni-berlin.de> Message-ID: <_rydnW6Tc6hjBdfVnZ2dnUVZ_oadnZ2d@comcast.com> "eliben" wrote in message news:e5fd542f-56d2-4ec0-a3a7-aa1ee106c624 at a70g2000hsh.googlegroups.com... > On Jun 7, 10:15 am, Marc 'BlackJack' Rintsch wrote: >> On Fri, 06 Jun 2008 23:57:03 -0700, s0suk3 wrote: >> > You can just split the path on `os.sep', which contains the path >> > separator of the platform on which Python is running: >> >> > components = pathString.split(os.sep) >> >> Won't work for platforms with more than one path separator and if a >> separator is repeated. For example r'\foo\\bar/baz//spam.py' or: >> >> In [140]: os.path.split('foo//bar') >> Out[140]: ('foo', 'bar') >> >> In [141]: 'foo//bar'.split(os.sep) >> Out[141]: ['foo', '', 'bar'] >> >> Ciao, >> Marc 'BlackJack' Rintsch > > Can you recommend a generic way to achieve this ? > Eli >>> import os >>> from os.path import normpath,abspath >>> x=r'\foo\\bar/baz//spam.py' >>> normpath(x) '\\foo\\bar\\baz\\spam.py' >>> normpath(abspath(x)) 'C:\\foo\\bar\\baz\\spam.py' >>> normpath(abspath(x)).split(os.sep) ['C:', 'foo', 'bar', 'baz', 'spam.py'] -Mark From shiningsandy at gmail.com Thu Jun 19 09:14:08 2008 From: shiningsandy at gmail.com (sandeep) Date: Thu, 19 Jun 2008 06:14:08 -0700 (PDT) Subject: python script for tortoise cvs Message-ID: hi we are using tortoise cvs and putty. i want to write a python script to whom i can provide a tag and module.now what this script will do is look for this specific tag and checks for whether its a individual tag or its inside a branch.if its inside a branch then find out what is the branch tag and then check out that branch for me else it checks out that module with that tag. Actually the thing is i am not able to find the way how i will do it and for where i have to look for the info.so any help will be appreciated. thanks and regards sandeep kumar sharma From lac at openend.se Thu Jun 5 14:26:58 2008 From: lac at openend.se (Laura Creighton) Date: Thu, 05 Jun 2008 20:26:58 +0200 Subject: ANN: Resolver One 1.1 released In-Reply-To: Your message of "Wed, 04 Jun 2008 11:01:44 PDT." References: Message-ID: <200806051826.m55IQwG6021897@theraft.openend.se> Hey, Congratulations! Laura Creighton From jacksingleton1 at gmail.com Sat Jun 28 21:12:35 2008 From: jacksingleton1 at gmail.com (c0mrade) Date: Sat, 28 Jun 2008 18:12:35 -0700 (PDT) Subject: Testing for Null? In-Reply-To: <268ac2770806281605n663670e9n29620f344ed66e4d@mail.gmail.com> References: <268ac2770806281605n663670e9n29620f344ed66e4d@mail.gmail.com> Message-ID: <18176481.post@talk.nabble.com> Try something like this... list = ['lkdfjsldk', None, '', '0', 'slfkjsdlfj', 'lsdgjdlfg', False, True] for n, it in enumerate(list): if not it: print 'Error on this definition' else: print '%d. %s' % (n+1, it) Results: 1. lkdfjsldk Error on this definition Error on this definition 4. 0 5. slfkjsdlfj 6. lsdgjdlfg Error on this definition 8. True Alexnb wrote: > > I am having a problem with a list value that is empty. I have a list of > definitions called mainList. the 5th value in the list doesn't have > anything > in it. In this case, the values are definitions; also, in this case just > the > word cheese is defined. Here is my output to the console: > > > 5. a sprawling,weedy plant having small lavender or white flowers and > round, flat, segmented fruits thought to resemble little wheels of cheese. > 6. > 7. an ingot or billet made into a convex, circular form by blows at the > ends. > > > I've made it so where the numbers, the period, and two spaces follow that, > then the definition. However, as you can see in 6, there is nothing. Here > is > the code to print all this: > > n=0 > > for x in mainList: > if mainList[n] == "": > print "Error on this definition" > else: > print str(n+1)+". "+str(mainList[n]) > n=n+1 > > Now the two "" is where I need to figure out if it is empty. What is up > right now doesn't work; or at least doesn't give the desired result. So I > need to know how to write the if statement to make it work. This should be > simple, but I just don't know how to do it, never had this problem before. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- View this message in context: http://www.nabble.com/Testing-for-Null--tp18175738p18176481.html Sent from the Python - python-list mailing list archive at Nabble.com. From hniksic at xemacs.org Thu Jun 5 17:59:58 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 05 Jun 2008 23:59:58 +0200 Subject: ClassName.attribute vs self.__class__.attribute References: <25e0de62-4c63-4545-8684-69a410639807@i76g2000hsf.googlegroups.com> Message-ID: <87hcc7zgo1.fsf@mulj.homelinux.net> "bruno.desthuilliers at gmail.com" writes: > On 5 juin, 17:40, Gabriel Rossetti > wrote: >> Hello everyone, >> >> I had read somewhere that it is preferred to use >> self.__class__.attribute over ClassName.attribute to access class (aka >> static) attributes. > > It's even prefered to use self.attribute, I was going to write exactly that, but it occurred to me that he might want to be *assigning* to self.__class__.attribute (or HisClass.attribute) from his methods, in which case self.attribute would be quite different. From mail at timgolden.me.uk Fri Jun 6 12:05:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 06 Jun 2008 17:05:03 +0100 Subject: How to remove read-only from a file In-Reply-To: <496954360806060846p4f96a00buc408720dcf9d95da@mail.gmail.com> References: <496954360806060846p4f96a00buc408720dcf9d95da@mail.gmail.com> Message-ID: <4849602F.6040403@timgolden.me.uk> Robert Dailey wrote: > Hi, > > Using Python 3.0, how can I remove a read-only property from a file in > Windows XP? Thanks. import os import stat os.chmod ("c:/temp/temp.txt", stat.S_IWRITE) (Haven't actually checked that on Python 3.0 but I don't believe it's changed...) TJG From bronger at physik.rwth-aachen.de Fri Jun 27 02:02:39 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 27 Jun 2008 08:02:39 +0200 Subject: Cyclic imports References: <1a5a1eb9-b4d1-4905-b60c-48fc93056e4d@k13g2000hse.googlegroups.com> <2588f7e0-ccbb-40cb-84da-d133349f5b72@u36g2000prf.googlegroups.com> Message-ID: <87fxqzo1og.fsf@physik.rwth-aachen.de> Hall?chen! James writes: >> # a.py >> import b >> # refer to b.b >> >> # b.py >> import a >> # refer to a.a > > Thanks Dan, but that still doesn't work for me I'm afraid... > > I renamed the modules avoid name overloading -- a.py is now: > import b > > class A(): > print('b.b_mod:', b.b_mod) Dan's hint is the way to go nevertheless. However, it is still not possible to actually use the module object on the top-level (i.e., while module a.py is read). So, you must delay any access to module b until everything is fully loaded -- for example, by wrapping the access in a function which is called from the main program. On the other hand, the above code was for debugging purposes I assume. So maybe there's no real problem anyway because all your uses of module b are wrapped in functions/methods anyway. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From eckhardt at satorlaser.com Thu Jun 5 05:16:43 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 05 Jun 2008 11:16:43 +0200 Subject: Image Processing (batch) References: <6akqd5F37rofnU1@mid.individual.net> Message-ID: Tim Roberts wrote: > Thomas Guettler wrote: >> >>I tried PIL for image batch processing. But somehow I don't like it >> - Font-Selection: You need to give the name of the font file. >> - Drawing on an image needs a different object that pasting and saving. >> - The handbook is from Dec. 2006. > > I have repeatedly seen the attitude in your last point, and I simply do > not understand it. What on Earth is wrong with having a product that > actually becomes stable? Nothing, and it is correct pointing that out. OTOH, there are billions of open source projects out there that started with an idea but never entered that finished state where they are useful, so-called abandonware. If the documentation is old, it is either stable or abandoned. Only a closer look can tell which of both, but statistically it is more likely that it is abandoned, sad as it is. Peace! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From bruno.42.desthuilliers at websiteburo.invalid Wed Jun 25 05:49:35 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 25 Jun 2008 11:49:35 +0200 Subject: IDE on the level of Eclipse or DEVc++? In-Reply-To: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> Message-ID: <486214ae$0$9742$426a34cc@news.free.fr> cirfu a ?crit : > is there an IDE for python of the same quality as Eclipse or DEVC++? > > I am currently using the editor that coems iwth python and it is all > fine but for bigger projects it would be nice to have some way to > easier browse the projectfiles for example. If you're into clickodroms, you may want to have a look at Eric too. As far as i'm concerned, I still wait for something that would be worth dropping emacs + python-mode + ecb. From jason.scheirer at gmail.com Thu Jun 26 17:56:56 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Thu, 26 Jun 2008 14:56:56 -0700 (PDT) Subject: Help me optimize my feed script. References: <184ee312-e54f-48bd-ac9f-1eb7e1737fc7@v26g2000prm.googlegroups.com> Message-ID: <5626bd7c-7386-494d-a24c-b46966bb2041@r37g2000prm.googlegroups.com> On Jun 26, 12:30?pm, bsag... at gmail.com wrote: > I wrote my own feed reader using feedparser.py but it takes about 14 > seconds to process 7 feeds (on a windows box), which seems slow on my > DSL line. Does anyone see how I can optimize the script below? Thanks > in advance, Bill > > # UTF-8 > import feedparser > > rss = [ > 'http://feeds.feedburner.com/typepad/alleyinsider/ > silicon_alley_insider', > 'http://www.techmeme.com/index.xml', > 'http://feeds.feedburner.com/slate-97504', > 'http://rss.cnn.com/rss/money_mostpopular.rss', > 'http://rss.news.yahoo.com/rss/tech', > 'http://www.aldaily.com/rss/rss.xml', > 'http://ezralevant.com/atom.xml' > ] > s = '\n\nC:/x/test.htm\n' > > s += '\n' > > s += '\n\n
\n' > > for url in rss: > ? ? ? ? d = feedparser.parse(url) > ? ? ? ? title = d.feed.title > ? ? ? ? link = d.feed.link > ? ? ? ? s += '\n

'+ title +'

\n' > ? ? ? ? # aldaily.com has weird feed > ? ? ? ? if link.find('aldaily.com') != -1: > ? ? ? ? ? ? ? ? description = d.entries[0].description > ? ? ? ? ? ? ? ? s += description + '\n' > ? ? ? ? for x in range(0,3): > ? ? ? ? ? ? ? ? if link.find('aldaily.com') != -1: > ? ? ? ? ? ? ? ? ? ? ? ? continue > ? ? ? ? ? ? ? ? title = d.entries[x].title > ? ? ? ? ? ? ? ? link = d.entries[x].link > ? ? ? ? ? ? ? ? s += ''+ title +'
\n' > > s += '

\n\n' > > f = open('c:/scripts/myFeeds.htm', 'w') > f.write(s) > f.close > > print > print 'myFeeds.htm written' I can 100% guarantee you that the extended run time is network I/O bound. Investigate using a thread pool to load the feeds in parallel. Some code you might be able to shim in: # Extra imports import threading import Queue # Function that fetches and pushes def parse_and_put(url, queue_): parsed_feed = feedparser.parse(url) queue_.put(parsed_feed) # Set up some variables my_queue = Queue.Queue() threads = [] # Set up a thread for fetching each URL for url in rss: url_thread = threading.Thread(target=parse_and_put, name=url, args=(url, my_queue)) threads.append(url_thread) url_thread.setDaemonic(False) url_thread.start() # Wait for threads to finish for thread in threads: thread.join() # Push the results into a list feeds_list = [] while not my_queue.empty(): feeds_list.append(my_queue.get()) # Do what you were doing before, replacing the for url in rss with for d in feedS_list for d in feeds_list: title = d.feed.title link = d.feed.link From basti.wiesner at gmx.net Sun Jun 22 05:40:12 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Sun, 22 Jun 2008 11:40:12 +0200 Subject: Fast and easy GUI prototyping with Python References: <9c349bf0-ef63-4463-bd4e-cdbe331b58c3@z66g2000hsc.googlegroups.com> Message-ID: Michael Torrie : > erokar at gmail.com wrote: >> 2) The Qt vs. .NET API. I have no experience with Qt's API and a >> rudimentary experience with the .NET API (seems powerfull but also big >> and complex). > > Qt's API is very very good. Easy to use and extremely powerful. Note > that in Python a number of Qt's APIs are not used in favor of Python > native apis for things like file and socket I/O, IPC, Threads, and so > forth. The support for signals and slots is imho a strong reason to prefer Qt apis over standard python apis, especially when it comes down to asynchronous programming (for instance, large network transfers like file downloads). > I've not used VS 2008's SWF gui designer, but of all the designers I've > seen so far, Qt's Designer is the best I've ever used. full ack. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From timr at probo.com Sat Jun 28 02:13:04 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 28 Jun 2008 06:13:04 GMT Subject: Working with the Windows Registry References: <49beca2a-9d6c-40a2-a7c3-bf1cf376df0a@l28g2000prd.googlegroups.com> Message-ID: <8alb6459djthkord5terdv6unfe4tscgjd@4ax.com> teh_sAbEr wrote: >Hi everybody. I'm trying to write a script that'll change desktop >wallpaper every time its run. Heres what I've gotten so far: > >#random wallpaper changer! >import _winreg >from os import walk >from os.path import exists >from random import randint > >#first grab a registry handle. >handle = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,'Control Panel >\Desktop',_winreg.KEY_SET_VALUE) > >def GenerateListOfWallpapers(): > targetDir = 'C:\Documents and Settings\Enrico Jr\My Documents\Jr >\'s Wallpapers' You are fortunate that your name is not "Tim" or "Ian" or "Nathan", because this would not have worked as you have written it. You either need to double the backslashes: ... 'C:\\Documents and Settings\\Enrico...' or use forward slashes: ... 'C:/Documents and Settings/Enrico...' or use the "r" modifier: ... r'C:\Documents and Settings\Enrico...' However, as a general practice, it's probably better to get the special directories from the environment: targetDir = os.environ['USERPROFILE'] + '\\My Documents\\Jr\'s Wallpapers' Remember that it's not called "Documents and Settings" on Vista... -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From zowtar at gmail.com Thu Jun 26 11:53:51 2008 From: zowtar at gmail.com (zowtar) Date: Thu, 26 Jun 2008 08:53:51 -0700 (PDT) Subject: url.encore/quote Message-ID: <889c0e25-c1e0-415b-b6db-f9e633a7eabb@d45g2000hsc.googlegroups.com> urlencode({'page': i, 'order': 'desc', 'style': 'flex power'}) return: page=1&order=desc&style=flex+power but I want: page=1&order=desc&style=flex%20power and url.quote don't put the &'s and ='s any idea guys? From dfh at forestfield.co.uk Sat Jun 14 05:23:18 2008 From: dfh at forestfield.co.uk (David Hughes) Date: Sat, 14 Jun 2008 02:23:18 -0700 (PDT) Subject: We are all consenting adults here Message-ID: <2cca4335-1162-4d61-b115-1f17d368721d@d1g2000hsg.googlegroups.com> Who coined this originally? I was reminded of it having just received a text message from mobile phone company Orange, in response to my request for them to review their policy of blocking access to this group (and, I suspect, all of Usenet). I quote: "Your request has been actioned and the content is confirmed as only suitable for customers over the age of 18. URL: http://groups/google.com/group/comp.lang.python" David From grante at visi.com Sat Jun 14 18:15:22 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 14 Jun 2008 17:15:22 -0500 Subject: Making wxPython a standard module? References: <6bidd7F3bg8usU1@mid.uni-berlin.de> <87fxrfx0h0.fsf@physik.rwth-aachen.de> <87wskrvhwd.fsf@physik.rwth-aachen.de> Message-ID: On 2008-06-14, Torsten Bronger wrote: >> [...] >> >> IMO, a few of the "un-Pythonic" things about wxPython are: >> >> 1) Window ID numbers. > > When I started to use wxPython, there was a newly-introduced > wx.ID_ANY that you could give instead of -1. My eyes filtered > it out after a couple of hours, just as they do with "self". Defining a new name for -1 is just painting the wart a different color. >> [...] >> >> 2) the "flags" parameter. > > Well, I like flags, and I don't see that they are unpythonic. I > find the code they produce very legible. You're saying that having the user or-together a bunch of bitmasks and pass the result as an integer is a common way for Python functions/object allow the user to turn optional features on and off? You must be using a different Python than I am. What I see used for that in the standard library modules are either named parameters with useful default values or individual object attributes. The only exceptions I can think are low level routines in the "os" and "socket" modules that allow direct access to things like Unix libc calls like open(), creat(), read(), write() and to the BSD sockets API. >> [...] >> >> 3) the parent/child tree > > See wx.ID_ANY. I don't see what the two have to do with each other, but maybe that's the root of all my problems. >> [...] >> >> 4) sizers > > Maybe because I come from TeX/LaTeX, i liked sizers > immediately. They worked well for me. I came from TeX/LaTeX also, and before wx, I spent a little time using Trestle GUI widgets which follow the TeX box-and-glue paradigm almost exactly. I guess I don't find wx sizers work much like TeX/LaTeX boxes. >> [...] >> >> 5) binding >> >> "What? you wanted a button that _did_ something when you >> clicked it?" > > You're right, this can be better. There's too much explicitness. > However, if you really hate the construct, you can define a > shortcut. I do. I sub-class wx.Button. Users should have to do that to get basic functionality that's required in 99.999% of the widget's use cases. Explicit is fine if it serves a purpose. I don't see the purpose of requiring a second line of code to bind a button to a callable. >> [...] >> >> 6) Thousands of wx.UPPER_CASE_INTEGER_HEX_CONSTANTS > > Thank you for the thorough explanations but in my opinion your > points are minor. They're minor in that they don't prevent you from writing programs that work, but they're not minor in that they unnecessarily increase the workload of the user without providing any benefit. They are sources of bugs. > Additionally, most of them are a matter of taste. I don't > think that because you didn't find sizers convenient, or some > parts too explicit, you can say that wxWidgets is un-Pythonic. Maybe a couple are just bad design decisions that weren't well thought out rather than being "un-Pythonic". OTOH, I consider that being well thoght out and well designed is one of the characteristics of Python, so things that aren't are un-Pythonic. > I rather have the impression that you like terseness, which is > totally okay but a different thing. I think that the most common use cases should be handled with a minimum of "extra" stuff having to be done by the user. It's just not Pythonic to require a user to specify default values for x,y,z when non-default valus for x,y,z are only used in 1 case out of 10000. In Python you use named parameters with default values. You don't use positional parameters and then tell the user "yes, I know this is useless almost all the time, so just pass a -1 if you want the default behavior. You shouldn't have to specifically ask for default behavior. You should only have to ask for non-default behavior. > I agree that changing the naming conventions and making use of > properties would increase pythonicness, but on an already high > level. I guess my views on what is "pythonic" are a lot different. I also don't think it's at all surprising that a C++ library like wxWidgets has an API that isn't very Pythonic. -- Grant Edwards grante Yow! I'm gliding over a at NUCLEAR WASTE DUMP near visi.com ATLANTA, Georgia!! From tjreedy at udel.edu Mon Jun 23 21:33:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Jun 2008 21:33:09 -0400 Subject: insertion sorts... In-Reply-To: <5f0111a3-c1b9-4864-bae3-32fa324c4e5e@j22g2000hsf.googlegroups.com> References: <06adb999-c7e2-4475-a49f-dbfbe042f4fd@r66g2000hsg.googlegroups.com> <5f0111a3-c1b9-4864-bae3-32fa324c4e5e@j22g2000hsf.googlegroups.com> Message-ID: Matimus wrote: > May I suggest you look into using `enumerate`: > >>>> for i, val in enumerate([4,5,6]): > ... print i, val > ... > 0 4 > 1 5 > 2 6 > > It allows you to get the index and the value at the same time, which > should eliminate the need for `aList.index`. I thought of suggesting that, but indirectly iterating over a list that is being modified with enumerate has the same problem as directly interating over the same changing list. From Lie.1296 at gmail.com Wed Jun 18 15:14:02 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 18 Jun 2008 12:14:02 -0700 (PDT) Subject: Does '!=' equivelent to 'is not' References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> <20080617120941.GE7349@dragontoe.org> Message-ID: <76aa0e1a-9242-4976-a1a2-9e7b258784c7@w4g2000prd.googlegroups.com> On Jun 18, 7:26?am, "Gabriel Genellina" wrote: > En Tue, 17 Jun 2008 09:09:41 -0300, Derek Martin ? > escribi?: > > > On Tue, Jun 17, 2008 at 04:33:03AM -0300, Gabriel Genellina wrote: > >> > Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)' > >> > and 'not(id(a) == id(b))' > > >> No. > > > Sure it is... he said "similar"... not identical. ?They are not the > > same, but they are similar. > > 'equality' and 'identity' are similar too, so the whole answer would make ? > no sense in that case. You can't explain identity based on things that ? > aren't identical. A fine grained question for a fine grained difference ? > requires a fine grained answer. In my defense, I admit I have the tendency to forget (purposefully) fine-grained differences if I thought that the difference was not significant enough in the context of speaking. The OP asked about != and 'is not', so I explained in terms of those being equality and identity testing respectively. To give a more concise and easy to understand example, I said that 'is not' is like using testing the 'id()' of the objects. Since (I think) the difference between != and 'is not' is much larger compared to the difference between 'is not' and 'id() test', I thought I could consider 'is not' and 'id() test' as "equivalent" in the context of this thread: 'Does != is equivalent to "is not"'. Either way, I'm sorry that I failed to put explicit notice that 'is not' and 'id() testing' isn't exactly the same either. > > Saying a flat "no" alone, without qualifying your statement is > > generally interpreted as rude in English... ?It's kind of like how you > > talk to children when they're too young to understand the explanation. > > Yucky. > > I didn't meant to be rude at all - and I apologize to Mr. Lie. I don't deserve the apology because the mistake is on me and I didn't feel offended, in fact I'm delighted someone could point out my mistake. > The ? > explanation for such strong "No" was in the paragraph below it (the idea ? > was to say: "No to this, yes to that") From duncan.booth at invalid.invalid Mon Jun 9 04:12:31 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jun 2008 08:12:31 GMT Subject: Parsing a path to components References: <7d7dd66c-b2bb-4a9a-a2e4-589079cda97b@e39g2000hsf.googlegroups.com> <14bf5448-4677-4ced-9d79-b4eb0c048218@56g2000hsm.googlegroups.com> <6auuc5F38s3s9U1@mid.uni-berlin.de> <_rydnW6Tc6hjBdfVnZ2dnUVZ_oadnZ2d@comcast.com> Message-ID: "Mark Tolonen" wrote: >> Can you recommend a generic way to achieve this ? >> Eli > >>>> import os >>>> from os.path import normpath,abspath >>>> x=r'\foo\\bar/baz//spam.py' >>>> normpath(x) > '\\foo\\bar\\baz\\spam.py' >>>> normpath(abspath(x)) > 'C:\\foo\\bar\\baz\\spam.py' >>>> normpath(abspath(x)).split(os.sep) > ['C:', 'foo', 'bar', 'baz', 'spam.py'] That gets a bit messy with UNC pathnames. With the OP's code the double backslah leadin is preserved (although arguably it has split one time too many, '\\\\frodo' would make more sense as the first element: >>> parse_path(r'\\frodo\foo\bar') ['\\\\', 'frodo', 'foo', 'bar'] With your code you just get two empty strings as the leadin: >>> normpath(abspath(r'\\frodo\foo\bar')).split(os.sep) ['', '', 'frodo', 'foo', 'bar'] -- Duncan Booth http://kupuguy.blogspot.com From piyush.subscription at gmail.com Tue Jun 24 15:29:33 2008 From: piyush.subscription at gmail.com (Piyush Anonymous) Date: Wed, 25 Jun 2008 00:59:33 +0530 Subject: sending executable data over network.. In-Reply-To: References: <19ac19520806232359r31f74c7bk9f5d47eb3540e457@mail.gmail.com> <200806241245.35047.omer@no-log.org> <19ac19520806240547m172941b2k52777e47b9a84711@mail.gmail.com> Message-ID: <19ac19520806241229i6bbc3f1dh21f1c4f9103b5f2e@mail.gmail.com> assuming security is not of concern at the moment, how can i add in update capability? please help me out or show some pointers to look into. i wish to change the way the method definition of a class at run time in a running server (actually i m planning to support many changes at run time). new code which is to be executed is provided by a client at different location. i am receiving the code as a string and compile it on server-side with the 'compile' builtin function or get compiled code using marshal. however i cannot link it to the running code in server? for example, i get a new method definition for a method in class and i wish to change it. client sent new definition, i compile it in server, getting a code object. how can i link it to old code? if it will running in same environment, i could simply write A.getdata=getdatanew # A is a class how should i do it here? should i change the way i am receiving the code? thanks for help -piyush On Wed, Jun 25, 2008 at 12:22 AM, Terry Reedy wrote: > > > Piyush Anonymous wrote: > >> any idea or pointer how i could link it to running code in server? >> for example, i get a new method definition for a method and i wish to >> change it. >> client sent new definition, i compile it in server. how can i link it to >> old code? >> > > Code to be hot-updated (while running) must have update capability builtin. > But please consider security. If a remote system can log in and *push* > code, an attacker can potentially do the same. Notice that self-updating > programs and systems generally log out to a hardwired location, ask if there > are updates, and *pull* the new code. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bob.martin at excite.com Fri Jun 6 02:58:45 2008 From: bob.martin at excite.com (Bob Martin) Date: Fri, 06 Jun 2008 06:58:45 GMT Subject: Books for learning how to write "big" programs References: <219c77ef-dd0c-464b-bb6a-e4f3bee89eae@x41g2000hsb.googlegroups.com> <304580c2-bdfb-4564-8507-d742d9eaf5a8@79g2000hsk.googlegroups.com> Message-ID: in 69148 20080605 140635 s0suk3 at gmail.com wrote: >On May 22, 12:49=A0pm, "Kurt Smith" wrote: >> On Thu, May 22, 2008 at 10:55 AM, duli wrote: >> > Hi: >> > I would like recommendations forbooks(in any language, not >> > necessarily C++, C, python) which have walkthroughs for developing >> > a big software project ? So starting from inception, problem >> > definition, design, coding and final delivery on a single theme >> > or application. >> >> The bigger the project, the more likely it is that you'll have >> documentation on how to use it (for a language or library, how to use >> the features in your program) but to take the time to write up a >> dead-tree book on the project's "inception, problem definition, >> design, coding and final delivery" is not likely well spent. =A0Anyone >> who has the expertise to write such a book would probably be spending >> his time working on the next phase of the project itself. >> >> Someone will probably respond with an amazon link to a book that does >> exactly what you're asking, in which case, I will stand corrected. >> But I'll be surprised. >> >> >> >> > Most of the code I have written andbooksthat I have read deal with >> > toy programs and I am looking for something a bit more >> > comprehensive. =A0For example, maybe a complete compiler written in C++ >> > for some language, or a complete web server or implementing >> > .net libraries in some language (just a few examples of the scale of >> > things I am interested in learning). >> >> It seems to me the reason toy programs are so prevalent is because >> they illustrate a (few) well defined ideas in a short amount of code. >> A big project, necessarily, brings together all kinds of stuff, much >> of which may not interest the author at all, and so doesn't motivate >> him to write a book about it. >> >> Compilers, web servers & .NET libraries are *widely* varying areas. >> You may have interest in them all, but to significantly contribute to >> any requires a fair amount of expertise and specialization. >> >> The best route I've found to learn how to organize & program large >> scale applications is this: find a cutting edge program that interests >> you and that is open source. =A0Download its source, and read the code. >> Diagram it. =A0Map it out. =A0Read the comments. =A0Join the mailing list >> (probably the developer's list), lurk for a while, and ask questions >> about why they organized things the way they did. =A0Get the overall big >> picture and learn from it. =A0Better yet, find out what pitfalls they >> found and avoided (or fell into). =A0Compare their approach & >> organization with another competing project. =A0This is the wonder of >> open source software -- you have access to everything, and can learn >> from all the expertise the developers put into their opus. >> >> You can learn the basics frombooks, but nothing beats analyzing a >> species in the wild. > >I think I have lately understood what you mean, thanks to Programming >Python 3rd Ed by Lutz. It doesn't teach Python itself -- the book aims >to teach Python programming at an application level, but I'm starting >to wonder whether that knowledge can be obtained from any book. The >book goes through over 1500 pages (!) giving small- and medium-sized >example programs and describing their details. Roughly after a couple >of hundred pages I started to feel like all that was trivial (isn't >looking at code and figuring their details what we do in our every-day >programmer lifes?), and then started to feel like it was really >useless. Maybe large-scale programming can only be self-thought in >every day life, am I right?. Of course. From dbpokorny at gmail.com Mon Jun 30 14:18:07 2008 From: dbpokorny at gmail.com (dbpokorny at gmail.com) Date: Mon, 30 Jun 2008 11:18:07 -0700 (PDT) Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> Message-ID: On Jun 27, 9:09 am, "John Salerno" wrote: > Of course, I suppose whether or not any of this matters depends on if you > are a web designer or a programmer, but am I missing something about > templates, or is it really the case that they, more or less by definition, > combine content and logic? This is a little anecdote about "separation of presentation, content, and logic." I used to work in a web application development environment that resembled Visual basic. The application presented its data through a java applet, and the server was written in lisp. If you were able to avoid the bugs (a bit like the fire swamps from The Princess Bride) then you could be fairly productive. The server took 45 seconds to start, took up a gigabyte of memory, and the applet took up 50 megabytes of memory in the browser and had sluggish performance. When I got a job as a LAMP, P = python developer, I first created a little program that would sift content in an "xhjp" file (which stood for "cross between html, javascript, and python.") The big idea was: you could write "dynamic elements" like so: {{{
Python code to render a chunk of XML ||| Javascript code to use the XML to do something interesting }}} There was a makefile that turned a single xhjp into a javascript file, and html file, and a python file. The hope was that you could think about the logic of elements in a single place. I thought this was a great idea and that it would be a big help in development, but it turned out to be a drag. Eventually I realized that I had to get my hands dirty and write a decent javascript framework to manage the page layout. This was somewhat painful, since among other things firefox doesn't report javascript exceptions that occur in response to an async http (commonly known as AJAX) request, but now swapping components in and out of the page is relatively easy. Currently the app gets its information with JSON (highly recommended), and tells the server what it wants with a "why" dict entry in the async http post (the information sent to the server is bundled in a dict). The server runs Django. To give you an idea of the current design, an async post scrapes a piece of information off of every dom element whose class is "context", bundles it with a "why", and provides a custom callback (this is far from ideal, something of a compromise). The vast majority of the dom elements are constructed with dhtml using information supplied by the server; this is possible because it is a intranet app. A public web app would do this with a template, before it hits the browser. BTW there is a good document design_philosophies.txt in the Django documentation. They have a section on why you *don't* want to put python code in your html. Cheers, David From cooperq at gmail.com Wed Jun 18 01:47:49 2008 From: cooperq at gmail.com (cooperq at gmail.com) Date: Tue, 17 Jun 2008 22:47:49 -0700 (PDT) Subject: Hrounding error Message-ID: Hi, I am new to python. I was messing around in the interperator checking out the floating point handling and I believe I may have found a rounding bug: >>> 234 - 23234.2345 -23000.234499999999 This is not correct by my calculations. I am using python 2.5.2 in ubuntu 8.04. I am wondering if this is a known bug, or if I am just not understanding some feature of python. Thanks for the help! -Cooper Quintin http://www.bitsamurai.net From cokofreedom at gmail.com Tue Jun 24 03:52:07 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 24 Jun 2008 00:52:07 -0700 (PDT) Subject: Python 3000 vs Perl 6 References: Message-ID: On Jun 24, 8:20 am, "Corey G." wrote: > If Perl 6 ever does get on its feet and get released, how does it > compare to Python 3000? Is Perl 6 more like Java now with Parrot? I > just want to make sure that Python is staying competitive. > > If this is the wrong mailing list, just let me know. Thanks! Do you mean in terms of speed (parrot is a JIT?). I believe Python 3k will (when out of beta) will have a speed similar to what it has currently in 2.5, possibly with speed ups in some locations. But competitive-wise I think the point is Python 3k tries to remove warts from the Python Language to make it even more friendly to readers and writers alike. In that way it should/will stay competitive. However towards overall usage, the general advice is to stay with the 2.x series for now, trying to ensure your code style is moving towards the Py3k style, and then make the jump to the 3.x series when it is finialised. Another point, is Perl 6 ever going to get released :P From mrmakent at cox.net Fri Jun 13 14:38:15 2008 From: mrmakent at cox.net (Mike Kent) Date: Fri, 13 Jun 2008 11:38:15 -0700 (PDT) Subject: Subclassing list, what special methods do this? Message-ID: <7ba7e964-2d34-4594-8cfc-79dbf904df18@f63g2000hsf.googlegroups.com> For Python 2.5 and new-style classes, what special method is called for mylist[2:4] = seq and for del mylist[2:4] (given that mylist is a list, and seq is some sequence)? I'm trying to subclass list, and I'm having trouble determining what special methods I have to override in my class for the above two operations. From my testing, it seems to be __setslice__ for both, but the docs say __setslice__ and brethren are deprecated. I would have thought that __setitem__ and __delitem__ would be what was called, but again, my testing says otherwise. From __peter__ at web.de Sun Jun 1 04:34:49 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 01 Jun 2008 10:34:49 +0200 Subject: Merging ordered lists References: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> Message-ID: etal wrote: > Here's an algorithm question: How should I efficiently merge a > collection of mostly similar lists, with different lengths and > arbitrary contents, while eliminating duplicates and preserving order > as much as possible? > > My code: > > def merge_to_unique(sources): > """Merge the unique elements from each list in sources into new > list. > > Using the longest input list as a reference, merges in the > elements from > each of the smaller or equal-length lists, and removes duplicates. > > @return: Combined list of elements. > """ > sources.sort(None, len, True) # Descending length > ref = sources[0] > for src in sources[1:]: > for i, s in enumerate(src): > if s and (ref[i] != s) and s not in ref: > ref.insert(ref.index(src[i-1])+1, s) > # Remove duplicates > return [r for i, r in enumerate(ref) if r and r not in ref[i+1:]] > > > This comes up with using the CSV module's DictWriter class to merge a > set (list, here) of not-quite-perfect CSV sources. The DictWriter > constructor needs a list of field names so that it can convert > dictionaries into rows of the CSV file it writes. Some of the input > CSV files are missing columns, some might have extras -- all of this > should be accepted, and the order of the columns in the merged file > should match the order of the input files as much as possible (not > alphabetical). All of the list elements are strings, in this case, but > it would be nice if the function didn't require it. > > Speed actually isn't a problem yet; it might matter some day, but for > now it's just an issue of conceptual aesthetics. Any suggestions? #untested import difflib def _merge(a, b): sm = difflib.SequenceMatcher(None, a, b) for op, a1, a2, b1, b2 in sm.get_opcodes(): if op == "insert": yield b[b1:b2] else: yield a[a1:a2] def merge(a, b): return sum(_merge(a, b), []) def merge_to_unique(sources): return reduce(merge, sorted(sources, key=len, reverse=True)) Peter From ralphzajac at sbcglobal.net Sun Jun 8 20:51:53 2008 From: ralphzajac at sbcglobal.net (ralphz) Date: Sun, 08 Jun 2008 17:51:53 -0700 Subject: How to close app after x seconds. Message-ID: Hi I have small app that I want to close tself after x seconds. Basically start show some message and close. I come up with something like this but it does not work. Can anyone help me with it? #!/usr/bin/env python import wx import time class MyFrame(wx.Frame): def __init__(self, title, pos, size): wx.Frame.__init__(self, None, -1, title, pos, size) self.CreateStatusBar() self.SetStatusText("Some message here") class MyApp(wx.App): def OnInit(self): self.frame = MyFrame('TITLE', (100, 100), (400,100)) self.frame.Show() self.SetTopWindow(self.frame) self.ID_Timer = wx.NewEventType() self.timer = wx.Timer(self, self.ID_Timer) self.timer.Start(5000, False) self.Bind(wx.EVT_TIMER, self.appclose, self.timer) # wx.EVT_TIMER(self, self.ID_Timer, self.appclose) return True def appclose(self, evt): self.frame.Destroy() if __name__ == '__main__': app = MyApp(0) app.MainLoop() Ralph http://TheOrangeIT.org From spectrumdt at gmail.com Wed Jun 4 12:01:52 2008 From: spectrumdt at gmail.com (spectrumdt at gmail.com) Date: Wed, 4 Jun 2008 09:01:52 -0700 (PDT) Subject: Trying to extend Python with C: undefined reference to `Py_BuildValue' References: <045458d3-771b-459d-b5ef-21d8f3c08659@2g2000hsn.googlegroups.com> Message-ID: On Jun 4, 4:13?pm, Ivan Illarionov wrote: > Hi! Your C code contains too many errors. I'm lazy to comment them all. > > 2. create 'buildme.py' file with this content: > Thanks for the replies. Maybe I should have read the rest of the guide to extending Python with C before whining here. I hadn't noticed the part where I was supposed to create a script to compile my C code rather than just call gcc. I fixed that, and now it works. Thanks. Yeah, my C code is probably full of bugs, too. I am a sucky C programmer. :P From deets at nospam.web.de Thu Jun 12 08:25:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 12 Jun 2008 14:25:08 +0200 Subject: Strange bug doesn't occur in Pydb References: <6bb01lF38u72tU1@mid.uni-berlin.de> Message-ID: <6bciubF3asvq1U1@mid.uni-berlin.de> kj wrote: > In <6bb01lF38u72tU1 at mid.uni-berlin.de> "Diez B. Roggisch" > writes: > >>kj schrieb: >>> I'm running into a strange seg fault with the module cjson. The >>> strange part is that it does not occur when I run the code under >>> Emacs' Pydb. >>> >>> Here's an example: >>> >>> >>> import sys, cjson >>> >>> d1 = {'a': 1, 'b': 2, 'c': 3} >>> print sys.version >>> j1 = cjson.encode(d1) >>> print j1 # should print the string '{"a": 1, "c": 3, "b": 2}' >>> >>> The code above runs fine under Pydb, but segfaults at the call to >>> cjson.encode when I run it from the command line in a standard >>> Linux shell interaction. In the printed version strings are >>> identical. >>> >>> I figure this must be a bug in cjson. I'd love to find a workaround >>> for it, and hope that this strange difference between Pydb and the >>> shell command line may be a clue to that. >>> >>> Any thoughts? > >>Are you sure you actually run the same interpreter in emacs as you do on >>the commandline? > > No, I'm not. All I know is that both Emacs and the commandline > are running on the same machine, and that the version string that > the program prints is the same in both conditions. How can I verify > that that the same interpreter is running in both cases? By e.g. import sys print sys.prefix Additionally, you should compare what sys.path contains and if it's the same - otherwise it might be that cjson is picked up from somewhere else. If all that's the case, I'd invoke python through gdb and see where the segfault happens. BTW: I've been using (and even patching) cjson - without any troubles whatsoever. Diez From gh at ghaering.de Mon Jun 9 09:36:53 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 09 Jun 2008 15:36:53 +0200 Subject: lists to save in a tuple In-Reply-To: <130e261e-1e1a-4657-b8db-8a7704fb083d@z66g2000hsc.googlegroups.com> References: <130e261e-1e1a-4657-b8db-8a7704fb083d@z66g2000hsc.googlegroups.com> Message-ID: Nader wrote: > Hello, > > I have two lists and would save them in a tuple. > > a = [1,2,3] > b = ['a','b','c'] > > with the next statement I can do that: > > t = [(x,y), for x in a for y in b] > > This gives the next list: > > [(1,'a'),(1,'b'),(1,'c'), (2,'a'),(2,'b'),(2,'c'), (3,'a'),(3,'b'), > (3,'c')] > > But I want the next list: > > [(1,'a'),(2,'b'),(3,'c')] > > Would somebody tell me how I can solve this problem? Use the zip() builtin. zip(a, b) -- Gerhard From Russ.Paielli at gmail.com Mon Jun 9 14:17:37 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 9 Jun 2008 11:17:37 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <484cf660$0$15495$426a74cc@news.free.fr> Message-ID: <6efd1deb-5e53-46d1-803a-f855a1f409be@a9g2000prl.googlegroups.com> On Jun 9, 2:23 am, Bruno Desthuilliers wrote: > Mark Wooding a ?crit : > > > > > Fuzzyman wrote: > > >> So, you are stating that no API programmer using Python *ever* has a > >> valid or genuine reason for wanting (even if he can't have it) genuine > >> 'hiding' of internal state or members from consumers of his (or > >> her...) API? > > > I don't want to speak for whoever you were responding to, but from my > > point of view... > > > Yes. > > > I understand the difference between the documented interface of a system > > and the details of its implementation. But sometimes it can be useful > > to take advantage of implementation details, particularly if the > > published interface is inadequate in some way. Whether or not I choose > > to make use of implementation details is a trade-off between immediate > > convenience and maintainability, but that's something I can make a > > rational decision about. > > > By enforcing your `data hiding', you're effectively telling me that I'm > > too stupid to make rational decisions of this sort. And that's actually > > extremely insulting. > > I couldn't state it better. +1QOTW btw. Please see my previous reply to that post. Being "insulted" by data hiding is the "QOTW"? I'd call that an insult to everyone else who has posted on this forum in the past week. Unless of course you mean "silliest QOTW." From larry at portcommodore.com Sun Jun 29 00:18:30 2008 From: larry at portcommodore.com (larry at portcommodore.com) Date: Sat, 28 Jun 2008 21:18:30 -0700 (PDT) Subject: help debugging noob code - converting binary data to images... Message-ID: <56955a42-155c-4c37-9bf6-5a99cadb5c79@l42g2000hsc.googlegroups.com> Ok I'm a Python noob, been doing OK so far, working on a data conversion program and want to create some character image files from an 8-bit ROM file. Creating the image I've got down, I open the file and use TK to draw the images... but 1) It does not seem to end (running in IDLE), I have to kill the process to retry it seems tkinter does not close(?) 2) Once I added the Image module open won't open my binary file (complains its not an image file, which is isnt.) I am sure I need to prefix open with something but I can't seem to find an example of how to word it, Below is the code (if it is lousy its because I've mainly been borrowing by examples as I go...) Any suggestions are gretly appreciated. #!/usr/local/bin/python from Tkinter import * from string import * from Image import * root = Tk() root.title('Canvas') #open commodore Cset rom cset = open("chargen","r") canvas = Canvas(width=16, height=16, bg='white') canvas.pack(expand=YES, fill=BOTH) # character size factor size = 2 # read all 512 characters from ROM for cchar in range(0, 511, 1): #draw line while charline < 8: position = 0 x = cset.read(1) ch = ord(x) # draw pixels while position < 8: if ch & ( 2 ** position ): xp = 1+(7-position)*size yp = 1+charline*size canvas.create_rectangle(xp,yp,xp+size,yp+size, fill='black', width=0) position += 1 charline += 1 #save character image outfile = "/home/mydir/work/char"+zfill(cchar,3)+".png" canvas.save(outfile,"png") #clear canvas for next char... canvas.create_rectangle(1,1,size*8,size*8, fill='white', width=0) root.mainloop() From beema.shafreen at gmail.com Fri Jun 13 02:45:15 2008 From: beema.shafreen at gmail.com (Beema shafreen) Date: Fri, 13 Jun 2008 12:15:15 +0530 Subject: e-value Message-ID: Hi all, I have file which includes the e_value i want to fetch the lines if the line with the e_value which is less than 0.01 so I have script but it doesn't work. can you please tell me is this the right way. The script does not end up with any error. It work if is give the condition evalue > 0.01 my script: >>> for line in fh: ... gi, seq, e_value = line.strip().split('\t') ... if e_value < 0.01: ... print e_value ... >>> sample data file: gi|7290649| IWHHTFYNELR 4.6e-02 gi|108883867| TITLEVEPSDTIENVK 7.8e-02 gi|157018218| LFEGGFDTLNK 2.2e-03 gi|34420406| YMVGPIEEVVEK 7.5e-04 gi|118791575| ATIKDEITHTGQFYEANDYR 9.4e-03 gi|78706974| LLSGVTIAQGGVLPNIQAVLLPK 5.2e-02 gi|157015257| VDDDVAVTDEK 1.0e-02 gi|28571691| QAGEVTYADAHK 2.2e-02 gi|89954247| VETGVLKPGTVVVFAPVNLTTEVK 4.4e-03 gi|78101790| LFEGGFDTLNK 2.2e-03 gi|157021047| LLSGVTIAQGGVLPNIQAVLLPK 7.3e-05 gi|157138410| LLSGVTIAQGGVLPNIQAVLLPK 5.2e-02 gi|27820013| LTDEEVDEMIR 2.6e-03 gi|56417572| TITLEVEPSDTIENVK 7.8e-02 gi|157020596| HPGSFEIVHVK 5.8e-02 can anybody help me reagrding this. -- Beema Shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From raoyitao at gmail.com Thu Jun 12 04:10:23 2008 From: raoyitao at gmail.com (Royt) Date: Thu, 12 Jun 2008 01:10:23 -0700 (PDT) Subject: Please recommend a blog program written using python-cgi Message-ID: <4f16f948-1082-4d3a-9276-cac97945c96b@x1g2000prh.googlegroups.com> Hi, I'm a newbie to Python, but I think it won't be too hard to learn. A few days ago I registered Google App Engine, it only support Python 2.5. I want to set my blog on it soon. But it's not easy for me to finish it in a short time since I'm not very familiar with Python, so I want find some codes available, throught reading the code, I can learn something from it. I know there are many frameworks for web development, but I just want the code using traditional CGI method, it's easy to use and it doesn't require any additional knowledge about framework. I need a simple example (support basic function of a weblog, easy to revise) but not a complicated huge monster (I don't think such a thing now exists). I find some online course, i.e. http://www.upriss.org.uk/python/PythonCourse.html & http://www.python.org/doc/essays/ppt/sd99east/index.htm but I didn't find the code needed, could anyone recommend it to me? thanks. From cokofreedom at gmail.com Fri Jun 6 02:53:22 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 5 Jun 2008 23:53:22 -0700 (PDT) Subject: Newb question: underscore References: <873anrl8p5.fsf@benfinney.id.au> <87y75jjeqo.fsf@benfinney.id.au> Message-ID: <601115a1-c788-4be7-b6b4-92cf159559bd@f36g2000hsa.googlegroups.com> > > My question is: Why would anyone decide to obfuscate something as easy > > to read as Python??? > > They didn't decide to obfuscate; they decided to follow a > strongly-expected convention for the name of that function by existing > users of the 'gettext' functionality, in contexts that predate the > appearance of that functionality in Python. > Well _ can also mean the previous output statement that wasn't null, so it has OTHER uses... From mccredie at gmail.com Thu Jun 19 19:23:57 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 19 Jun 2008 16:23:57 -0700 (PDT) Subject: python/ruby question.. References: <39801514-d2b8-4926-b56b-39856d79b0dd@d1g2000hsg.googlegroups.com> Message-ID: <1c699ba8-8a33-41e3-b1e7-82d28633f25a@z66g2000hsc.googlegroups.com> On Jun 19, 4:00?pm, Matimus wrote: > On Jun 18, 8:33?pm, "bruce" wrote: > > > > > hi... > > > can someone point me to where/how i would go about calling a ruby app from a > > python app, and having the python app being able to get a returned value > > from the ruby script. > > > something like > > > test.py > > ?a = os.exec(testruby.rb) > > > testruby.py > > ?foo = 9 > > ?return foo > > > i know this doesn't work... but i've been searching for hours on this with > > no luck.... (and yeah, i'm relatively new to both ruby/python!!) > > > thanks > > Both Ruby and Python appear to support XMLRPC. I haven't used XMLRPC > in Ruby, but in general you create a server and expose some functions. > On the client end (Python) you would do something like this (assuming > you are serving on port 8050): > > import xmlrpclib > > rubyserver = xmlrpclib.Server("http://localhost:8050") > x = rubyserver.foo(1,2,3) > > where 'foo' is a function served by the ruby server and x is its > return value. > > some links: > > http://www.ruby-doc.org/stdlib/libdoc/xmlrpc/rdoc/index.html > > Good python server and client examples on this page: > > http://docs.python.org/lib/simple-xmlrpc-servers.html > > I can't be of much help for ruby, and that link doesn't seem to help > much other than to say 1. it exists and 2. its easy. > > Matt Here is a more complete example. The ruby server code: require "xmlrpc/server" s = XMLRPC::Server.new(8080) s.add_handler("add") do |a,b| a + b end s.add_handler("div") do |a,b| if b == 0 raise XMLRPC::FaultException.new(1, "division by zero") else a / b end end s.set_default_handler do |name, *args| raise XMLRPC::FaultException.new(-99, "Method #{name} missing" + " or wrong number of parameters!") end s.serve I put the above code into a file xmlrpctest.rb and ran it at the command line. Then I opened the python interpreter in a separate window and did this: >>> s = xmlrpclib.Server("http://localhost:8080") >>> s.div(100,2.0) 50.0 >>> s.add(100000, 2) 100002 >>> In the long run you may still want to use the subprocess module to launch the ruby xmlrpc server, but once you do that communicating between the two processes should be pretty simple. Matt From Scott.Daniels at Acm.Org Tue Jun 10 08:55:12 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 10 Jun 2008 05:55:12 -0700 Subject: Parsing a path to components In-Reply-To: <7d7dd66c-b2bb-4a9a-a2e4-589079cda97b@e39g2000hsf.googlegroups.com> References: <7d7dd66c-b2bb-4a9a-a2e4-589079cda97b@e39g2000hsf.googlegroups.com> Message-ID: eliben wrote: ... a prety good try ... > def parse_path(path): > """...""" By the way, the comment is fine. I am going for brevity here. > lst = [] > while 1: > head, tail = os.path.split(path) > if tail == '': > if head != '': lst.insert(0, head) > break > else: > lst.insert(0, tail) > path = head > return lst > ---------------------------------- > > Did I miss something and there is a way to do this standardly ? Nope, the requirement is rare. > Is this function valid, or will there be cases that will confuse it ? parse_path('/a/b/c//d/') Try something like: def parse_path(path): '''...same comment...''' head, tail = os.path.split(path) result = [] if not tail: if head == path: return [head] # Perhaps result = [''] here to an indicate ends-in-sep head, tail = os.path.split(head) while head and tail: result.append(tail) head, tail = os.path.split(head) result.append(head or tail) result.reverse() return result --Scott David Daniels Scott.Daniels at Acm.Org From danb_83 at yahoo.com Sat Jun 14 00:03:09 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Fri, 13 Jun 2008 21:03:09 -0700 (PDT) Subject: numpy: handling float('NaN') different in XP vs. Linux References: Message-ID: <369beb8f-986e-4112-b232-eeed01d7ddb7@w34g2000prm.googlegroups.com> On Jun 13, 10:45?pm, "John [H2O]" wrote: > I have a script: > > from numpy import float > OutD=[] > v=['3','43','23.4','NaN','43'] > OutD.append([float(i) for i in v[1]]) > > On linux: > Python 2.5.1 (r251:54863, Mar ?7 2008, 04:10:12) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > [john at andLinux analysis]$ python jnk.py > [[3.0, 43.0, 23.399999999999999, nan, 43.0]] > > On XP: > Python 2.5 (r25:51908, Mar ?9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > C:\analysis>C:\Python25\python.exe jnk.py > Traceback (most recent call last): > ? File "jnk.py", line 4, in > ? ? OutD.append([float(i) for i in v]) > ValueError: invalid literal for float(): NaN Python just uses the atof() function from the underlying C library. Some of them handle NaN's, and some of them don't. If you want to get NaN on a platform where float('NaN') doesn't work, try 1e1000 / 1e1000. Or failing that, struct.unpack('d', struct.pack('Q', 0xfff8000000000000))[0] From leoncamel at gmail.com Sun Jun 1 10:32:39 2008 From: leoncamel at gmail.com (Leon zhang) Date: Sun, 1 Jun 2008 07:32:39 -0700 (PDT) Subject: the pipe reading in Thread dose not work. Message-ID: <80750570-0a03-4006-99f4-23943aa56177@u6g2000prc.googlegroups.com> #!/usr/bin/env python # -*- coding: utf-8 -*- import string, sys from threading import Thread import os import time class test_pipe(Thread): def __init__(self, fd): Thread.__init__(self) self.testfd = fd def run(self): print "started thread begin -----" while True: buf = self.testfd.read() print "receive %s" % (buf) time.sleep(1) #print "hoho" if __name__ == "__main__": stdin_r, stdin_w = os.pipe() #stdout_r, stdout_w = pipe() f_w = os.fdopen(stdin_w, "w", 0) thrd = test_pipe(os.fdopen(stdin_r, "r", 0)) thrd.start() time.sleep(1) while True: f_w.write("help\r\n") time.sleep(1) thrd.join() -------------------------------------------- well, I want the following small test about pipe() in thread(). OK, I write to the pipe in the main thread, and I created a new thread for reading from the pipe, then it will print what it received from the pipe(). But, it seems it block at the "self.testfd.read()". So, is there and suggestion and explaination about it? Thanks in advance. From news at prodata.co.uk Tue Jun 17 13:23:20 2008 From: news at prodata.co.uk (John Dann) Date: Tue, 17 Jun 2008 18:23:20 +0100 Subject: Numeric type conversions References: Message-ID: On Tue, 17 Jun 2008 08:58:11 -0700 (PDT), MRAB wrote: >[snip] >Please note that in slicing the start position is included and the end >position is excluded, so that should be ByteStream[12:14]. Yes, I just tripped over that, in fact, hence the error in my original post. I suppose there must be some logic in including the start position but excluding the end position, though it does escape me for now. I can understand making a range inclusive or exclusive but not a mixture of the two. Suppose it's just something you have to get used to with Python and, no doubt, much commented on in the past. JGD From barry at python.org Thu Jun 19 07:53:10 2008 From: barry at python.org (Barry Warsaw) Date: Thu, 19 Jun 2008 07:53:10 -0400 Subject: [Python-3000] RELEASED Python 2.6b1 and 3.0b1 In-Reply-To: <79990c6b0806190143n58e51a22ubafd3fe343291dfb@mail.gmail.com> References: <1972109D-735D-4485-82F4-9BC8F2984967@python.org> <79990c6b0806190143n58e51a22ubafd3fe343291dfb@mail.gmail.com> Message-ID: <5A74EFE6-0915-4EF9-9096-3CE75F32F00E@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Jun 19, 2008, at 4:43 AM, Paul Moore wrote: > On 19/06/2008, Barry Warsaw wrote: >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> On behalf of the Python development team and the Python community, >> I am >> happy to announce the first beta releases of Python 2.6 and Python >> 3.0. > > Any ETA for Windows builds? The web pages still point to the alphas. > (I'd like to see the Windows builds more closely integrated with the > releases now we're in beta stage...) Martin usually fills these in pretty quickly. I think the current situation works fine for the betas but we'll make sure the final release (and candidates) are better coordinated. - -Barry -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQCVAwUBSFpIpnEjvBPtnXfVAQJyWQP9FSH8Ipg93UDM3nmH3UtN+i61YGsQPd0O ypHlnz4yHpxeRkJm1zkppHHI0hKMou6JOeUf05QCnPzrAdsG/mkuv5aoBrBt3dDd UncHLoQOvXEhGrrPzexmHKv3ehxUXPQOzkiWBWVv9e69GYH4e4HcqV6s2Ya2733T zC/EyOgkyMg= =5wM5 -----END PGP SIGNATURE----- From sri_annauni at yahoo.co.in Fri Jun 13 12:29:06 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Fri, 13 Jun 2008 21:59:06 +0530 (IST) Subject: Python Socket programming Message-ID: <655455.29695.qm@web7907.mail.in.yahoo.com> Hi, I am going to do some socket related programming in Python. Before that, I wish to know the Gotchas of Python Scoket Programming. Can anyone send me any link that satisfies my needs?? Thanks, Srini Explore your hobbies and interests. Go to http://in.promos.yahoo.com/groups/ From chradcliffe at gmail.com Thu Jun 26 17:58:26 2008 From: chradcliffe at gmail.com (Craig Radcliffe) Date: Thu, 26 Jun 2008 17:58:26 -0400 Subject: Help me on Backspace please In-Reply-To: <6fe75aa0-721e-42a1-83e4-ceee24853000@w7g2000hsa.googlegroups.com> References: <6fe75aa0-721e-42a1-83e4-ceee24853000@w7g2000hsa.googlegroups.com> Message-ID: Something like this might do the trick: import re f = open("file.txt") old_text = f.readlines() f.close() new_text = [re.sub(r'.\b', '', i) for i in old_text] f = open("file_modified.txt", "w") f.writelines(new_text) I don't know how necessary the separate read and writes are, but it'll be good for a start. At any rate, you'll want to look at the remodule. On Thu, Jun 26, 2008 at 16:32, wrote: > Hi > I am a beginner on Python and have a problem.. > > I have text file and reading it line by line and there are backspace > characters in it like '\b' or anything you want like "#". I want to > replace these chars. with Backspace action. I mean deleting the > previous char. and the \b char also. and writing all cleaned text to a > file again. > > How can I do that. > > Thanks.. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gerard.blais at gmail.com Thu Jun 12 07:33:28 2008 From: gerard.blais at gmail.com (Gerry) Date: Thu, 12 Jun 2008 04:33:28 -0700 (PDT) Subject: Converting a simple python script to a simple windows executable References: Message-ID: On Jun 12, 4:04?am, William McBrine wrote: > On Wed, 11 Jun 2008 12:25:29 -0700, geoffbache wrote: > > (1) py2exe. This is really for when python isn't installed on the remote > > user's machine, so it requires you to distribute a large amount of DLLs > > etc which are part of the python installation. A bit silly when I know > > that the remote user has python anyway. > > If you know the target user has Python installed, why don't you just > distribute the .pyw file? (Use ".pyw" instead of ".py" to avoid the extra > console window.) > > -- > 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on I really like cx_freeze: http://python.net/crew/atuining/cx_Freeze/ From george.sakkis at gmail.com Tue Jun 10 22:15:16 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 10 Jun 2008 19:15:16 -0700 (PDT) Subject: Confusion with weakref, __del__ and threading Message-ID: I'm baffled with a situation that involves: 1) an instance of some class that defines __del__, 2) a thread which is created, started and referenced by that instance, and 3) a weakref proxy to the instance that is passed to the thread instead of 'self', to prevent a cyclic reference. This probably sounds like gibberish so here's a simplified example: ========================================== import time import weakref import threading num_main = num_other = 0 main_thread = threading.currentThread() class Mystery(object): def __init__(self): proxy = weakref.proxy(self) self._thread = threading.Thread(target=target, args=(proxy,)) self._thread.start() def __del__(self): global num_main, num_other if threading.currentThread() is main_thread: num_main += 1 else: num_other += 1 def sleep(self, t): time.sleep(t) def target(proxy): try: proxy.sleep(0.01) except weakref.ReferenceError: pass if __name__ == '__main__': for i in xrange(1000): Mystery() time.sleep(0.1) print '%d __del__ from main thread' % num_main print '%d __del__ from other threads' % num_other ========================================== When I run it, I get around 950 __del__ from the main thread and the rest from non-main threads. I discovered this accidentally when I noticed some ignored AssertionErrors caused by a __del__ that was doing "self._thread.join()", assuming that the current thread is not self._thread, but as it turns out that's not always the case. So what is happening here for these ~50 minority cases ? Is __del__ invoked through the proxy ? George From iainking at gmail.com Thu Jun 5 10:30:21 2008 From: iainking at gmail.com (Iain King) Date: Thu, 5 Jun 2008 07:30:21 -0700 (PDT) Subject: Creating A Tuple From A List, Adding To Tuple As You Do References: Message-ID: <63b264bd-20a3-4ab0-9298-dca338cdf2b4@25g2000hsx.googlegroups.com> On Jun 5, 1:41 pm, Jeff Nyman wrote: > Greetings all. > > The subject line of this thread is probably one of the worst ever. I > was trying to encapsulate what I am doing. Based on my new-found > knowledge from another thread, I'm able to get a list of directories > and they come to me in the form of a list. Here is an example: > > from glob import glob > DC_List = glob('\\\\vcdcflx006\\Flex\\Sites\\*\\') > DC_List = ['Baltimore', 'Birmingham', 'Cincinnati', 'Cleveland', > LosAngeles'] > > (Each element in the DC_List is actually a full directory path, but I > shortened that in the interest of clarity.) > > The problem is that I need to pass this list to a list control in a > wxWidgets application. In order to do that, I need to pass in a list > like this: > > [ ('Baltimore', ''), ('Birmingham', ''), ('Cincinnati', ''), > ('Cleveland', ''), ('LosAngeles', '') ] > > In other words, each element in the list is a tuple that has an empty > second string. The problem I'm having is in converting my list above > to be of this type. I can't do append because that (logically) puts > everything at the end. I did try this: > > for count in range(0, len(DC_List)): > DC_List.insert(count, '') > > Here I was thinking I could insert a '' into the right place after > each entry in the list. That doesn't quite work. Does anyone have an > idea of a good approach here? (I did search on tuples and lists and > while I found a lot of information about both, I couldn't find a > solution that did what I'm discussing above.) > > - Jeff I know a ton of people have already replied with list comprehensions, but I figured I'd chime in with one that also strips out the path of your folders for you (since I'm not sure how you are managing that just now) cities = [(os.path.basename(x), '') for x in glob('\\\\vcdcflx006\\Flex \\Sites\\*\\')] I tend to use / instead of \\ as a folder seperator, it should work for you (I think): cities = [(os.path.basename(x), '') for x in glob('//vcdcflx006/Flex/ Sites/*')] Iain From gagsl-py2 at yahoo.com.ar Thu Jun 19 01:52:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 19 Jun 2008 02:52:19 -0300 Subject: =?iso-8859-15?Q?Regular_expressions_for_accents_like_=F3?= =?iso-8859-15?Q?_character_in_python?= References: Message-ID: En Thu, 19 Jun 2008 02:08:38 -0300, Sallu escribi?: > i want to restrict to user to not enter accents character. si i need > to make an Regular expressions for accents like ? character You may enumerate all the allowed characters: py> allowed_re = re.compile(r"^[A-Za-z0-9 ]*$") py> input = "hello world" py> allowed_re.match(input) <_sre.SRE_Match object at 0x00A3C1E0> py> input = "c?digo inv?lido" py> allowed_re.match(input) py> print allowed_re.match(input) None -- Gabriel Genellina From seandavi at gmail.com Wed Jun 11 09:17:33 2008 From: seandavi at gmail.com (Sean Davis) Date: Wed, 11 Jun 2008 06:17:33 -0700 (PDT) Subject: Numpy array to gzip file Message-ID: I have a set of numpy arrays which I would like to save to a gzip file. Here is an example without gzip: b=numpy.ones(1000000,dtype=numpy.uint8) a=numpy.zeros(1000000,dtype=numpy.uint8) fd = file('test.dat','wb') a.tofile(fd) b.tofile(fd) fd.close() This works fine. However, this does not: fd = gzip.open('test.dat','wb') a.tofile(fd) Traceback (most recent call last): File "", line 1, in IOError: first argument must be a string or open file In the bigger picture, I want to be able to write multiple numpy arrays with some metadata to a binary file for very fast reading, and these arrays are pretty compressible (strings of small integers), so I can probably benefit in speed and file size by gzipping. Thanks, Sean From exarkun at divmod.com Sun Jun 15 12:16:16 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 15 Jun 2008 12:16:16 -0400 Subject: The best way to package a Python module? In-Reply-To: Message-ID: <20080615161616.4714.1519820848.divmod.quotient.9372@ohm> On Mon, 16 Jun 2008 01:01:47 +0900, js wrote: >Hi list, > >I'm trying to build a package for python modules. >When I just wanted to have a package for Python2.5, this is an easy task, >but in most cases, it's not enough. >Sometimes I need python2.4, 2.5, 2.6 or 3.0 etc. > >The problem is coming from the fact that python installs its modules >into version-independent place as follow. > >$prefix/lib/python2.4/site-package/ >$prefix/lib/python2.5/site-package/ > >For this, I have to create a package for each version. >Let's say if I need a module called "spam" and installed spam with python2.5. >The files would be installed in $prefix/lib/python2.5/site-package/. >It only usable from python2.5. > >When I need it for python2.4, I have to prepare the same package for python2.4, >the only difference is the place it installed. > >This is the problem I'm having now. >How can I avoid this redundant work? >Any advice, suggestions would be greatly appreciated. > >Thanks! What do you mean, "package"? If you use distutils, then none of the questions you asked make very much sense. >-- >http://mail.python.org/mailman/listinfo/python-list > From matthieu.brucher at gmail.com Thu Jun 26 06:16:11 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Thu, 26 Jun 2008 12:16:11 +0200 Subject: Threads, GIL and re.match() performance In-Reply-To: <207312b70806260020j6a4c5d4dt3af0625c27ec3cc2@mail.gmail.com> References: <25be11e7-157c-4af0-be3a-fa7a6c9c3acc@m3g2000hsc.googlegroups.com> <207312b70806260020j6a4c5d4dt3af0625c27ec3cc2@mail.gmail.com> Message-ID: Hi, The C-API uses references counts as well, so it is not threadsafe. Matthieu 2008/6/26 Pau Freixes : > But Python C-API[1] it's the main base for extent python with C/c++, and > this is not not threadsafe.? I dont understand > > [1] http://docs.python.org/api/api.html > > On Thu, Jun 26, 2008 at 4:49 AM, Benjamin > wrote: >> >> On Jun 25, 9:05 am, Mirko Dziadzka wrote: >> > >> > 1) Is there a reason for this? >> >> I think it is because the Python re library uses the Python C-API >> which is not threadsafe. >> > 2) Is the regex library not thread-safe? >> > 3) Is it possible, to release the GIL in re.match() to >> > get more performance? >> >> -- >> http://mail.python.org/mailman/listinfo/python-list > > > > -- > Pau Freixes > Linux GNU/User > -- > http://mail.python.org/mailman/listinfo/python-list > -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher From exarkun at divmod.com Sun Jun 1 13:19:13 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 1 Jun 2008 13:19:13 -0400 Subject: the pipe reading in Thread dose not work. In-Reply-To: <80750570-0a03-4006-99f4-23943aa56177@u6g2000prc.googlegroups.com> Message-ID: <20080601171913.4714.1079010110.divmod.quotient.4409@ohm> On Sun, 1 Jun 2008 07:32:39 -0700 (PDT), Leon zhang wrote: > >#!/usr/bin/env python ># -*- coding: utf-8 -*- > >import string, sys >from threading import Thread >import os >import time > >class test_pipe(Thread): > def __init__(self, fd): > Thread.__init__(self) > self.testfd = fd > > def run(self): > print "started thread begin -----" > while True: > buf = self.testfd.read() > print "receive %s" % (buf) > time.sleep(1) > #print "hoho" > >if __name__ == "__main__": > > stdin_r, stdin_w = os.pipe() > #stdout_r, stdout_w = pipe() > > f_w = os.fdopen(stdin_w, "w", 0) > > thrd = test_pipe(os.fdopen(stdin_r, "r", 0)) > thrd.start() > > time.sleep(1) > > while True: > f_w.write("help\r\n") > time.sleep(1) > > thrd.join() >-------------------------------------------- >well, I want the following small test about pipe() in thread(). >OK, I write to the pipe in the main thread, and I created a new thread >for reading from the pipe, then it will print what it received from >the pipe(). > >But, it seems it block at the "self.testfd.read()". > >So, is there and suggestion and explaination about it? file.read() reads the entire contents of the file. Your code never closes the write end of the pipe, so the read can never succeed - there is always more for it to read. Jean-Paul From tdelaney at avaya.com Wed Jun 4 19:10:55 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 5 Jun 2008 07:10:55 +0800 Subject: multiprocessing module (PEP 371) In-Reply-To: <48471D42.20808@cheimes.de> Message-ID: Christian Heimes wrote: > Can you provide a C implementation that compiles under VS 2008? Python > 2.6 and 3.0 are using my new VS 2008 build system and we have dropped > support for 9x, ME and NT4. If you can provide us with an > implementation we *might* consider using it. You'd have to at least consider whether to consider using it ;) BTW, something like adding a windows fork() that is not publically exposed might be considered a bug/performance fix only (and thus suitable for 3.0.1) if you don't get it into 3.0 (to be exposed to Python code in 3.1) - but check first whether it would be accepted as such. Definitely best to try to get it into 3.0. Tim Delaney From celoserpa at gmail.com Tue Jun 24 12:31:27 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Tue, 24 Jun 2008 13:31:27 -0300 Subject: Accounting and financial system In-Reply-To: <1e5bcefd0806240924t74c7b4ax48d1267e508e516b@mail.gmail.com> References: <1e5bcefd0806240924t74c7b4ax48d1267e508e516b@mail.gmail.com> Message-ID: <1e5bcefd0806240931g38f11c47se1670c0238f9f2d2@mail.gmail.com> Btw, sorry it is [OT], I forgot to add the prefix, it is really not a post tied to the language itself. On Tue, Jun 24, 2008 at 1:24 PM, Marcelo de Moraes Serpa < celoserpa at gmail.com> wrote: > Hello list, > > In a next project of mine, I will need to implement some accounting and > financial control. It is not a full ERP, only the basic functions for > finances and accounting control. However, I have little to no experience in > this business domain (accounting and finances) but I really do need to > understand the basic machinery behind it, even if it will take a significant > amount of time. What I would like to know is where I could look (besides > getting a degree :P) for sample code and documentation for these subjects? > Do you think I would need to read some books before I get into code? If so, > which ones? For sample code, I was thinking about OpenERP, since I've heard > it is a complete ERP solution and it is written in python ;) > > Really, I'm committed to understand the basiscs of the said business > domains, I really need this project to succeed :) > > Thanks in advance! > > Marceo. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sspatz at kcnet.com Thu Jun 26 21:56:30 2008 From: sspatz at kcnet.com (Saul Spatz) Date: Thu, 26 Jun 2008 20:56:30 -0500 Subject: recursion in Class-methods? In-Reply-To: References: <975b0368-10fe-419c-82ef-50277d4ecd54@l42g2000hsc.googlegroups.com> <48635bfb$0$6862$426a74cc@news.free.fr> Message-ID: <562dnYb_KN1J1fnVnZ2dnUVZ_vninZ2d@posted.kcnet> defn noob wrote: >>> if start == end: >>> return path >>> if not self.dictionary.has_key(start): >> if start not in self.dictionnary: >> >>> return None >>> for node in self.dictionary[start]: >>> if node not in path: >>> newpath = find_path(self.dictionary, node, end, path) >> newpath = self.find_path(...) >> >> (snip remaining code - same problems, same solutions...) > > it is to incoherent fo follow what you mean here(not meaning to sound > rude i appreciate the help). I modified your code as shown below, and it seems to work fine. (I didn't test the shortest path part, just the example you gave.) class Graph(object): def __init__(self, dictionary): self.dictionary = dictionary def find_path(self, start, end, path=None): if not path: path = [] path = path + [start] if start == end: return path if not self.dictionary.has_key(start): return None for node in self.dictionary[start]: if node not in path: newpath = self.find_path(node, end, path) if newpath: return newpath return None def find_all_paths(self, start, end, path=None): if not path: path = [] path = path + [start] if start == end: return [path] if not self.dictionary.has_key(start): return [] paths = [] for node in self.dictionary[start]: if node not in path: newpaths = self.find_all_paths(node, end, path) for newpath in newpaths: paths.append(newpath) return paths def find_shortest_path(self, start, end, path=None): if not path: path = [] path = path + [start] if start == end: return path if not self.dictionary.has_key(start): return None shortest = None for node in self.dictionary[start]: if node not in path: newpath = self.find_shortest_path(node, end, path) if newpath: if not shortest or len(newpath) < len(shortest): shortest = newpath return shortest g = Graph({'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C']}) print g.find_all_paths('A', 'C') Output: [['A', 'B', 'C'], ['A', 'B', 'D', 'C'], ['A', 'C']] Here are the changes I made. 1) Inherit from object. (Anticipation of 3.0) 2) Changed calls such as find_path(self.dictionary, node, end, path) to self.find_path(node, end, path). In python, an objects methods have no special privileges in calling its other methods. They call it like self.otherMethod(...). Also, the first parameter is supposed to be a Graph object. I'm not sure what the effect of calling it with a dictionary would be. BTW, "dictionary" seems like an uninformative name. Why not call it "adjacent" or "neighbor", or "successor"? 3) Changed the default value of path to None, as suggested by Bruno Desthuilliers. What he's telling you is that the default object is created only once; when the method is defined. If it's an int or a string, that doesn't matter. You can't change it, and so you will always have the same default value if you need it. If it's a mutable object, like a list, when your method changes it, as with path = path + [start] it changes the global default object; the next time you need it, it won't be [] but whatever you last changed it to. This last is a tricky point. I hope I've been clear. Saul From kurdayon at yahoo.com Fri Jun 27 18:41:22 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Fri, 27 Jun 2008 15:41:22 -0700 (PDT) Subject: Do I need "self" and "other"? References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> Message-ID: <04e2afb7-b96c-446a-816a-ffac0ea81d5b@p25g2000hsf.googlegroups.com> On Jun 27, 6:32 pm, Hans Nowak wrote: > Kurda Yon wrote: > > Hi, > > > I found one example which defines the addition of two vectors as a > > method of a class. It looks like that: > > > class Vector: > > def __add__(self, other): > > data = [] > > for j in range(len(self.data)): > > data.append(self.data[j] + other.data[j]) > > return Vector(data) > > > In this example one uses "self" and "other". Does one really need to > > use this words? And, if yes, why? I have replaced "self" by "x" and > > "other" by "y" and everything looks OK. Is it really OK or I can have > > some problem in some cases? > > You can use whichever (valid) names you want, but in general 'self' and 'other' > are used for clarity. In this case, they indicate the vector that is operated > on ("self") and another vector ("other"). Using 'x' and 'y' would be less clear > here. > > -- > Hans Nowak (zephyrfalcon at gmail dot com)http://4.flowsnake.org/ OK, I see. In the given example "self" is just a name which can be replace by whichever (valid) name. Is that always like that? I mean, does "slef" have a special meaning in some cases or it is always "just a name like any other"? I am asking that because "self" is highlighted in my text editor, so I assume that it can have a special meaning. I also heard that "self" refers to a object and I am not sure what that "refers" means. From Russ.Paielli at gmail.com Mon Jun 9 14:43:19 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 9 Jun 2008 11:43:19 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <4847d39d$0$7614$426a74cc@news.free.fr> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> <484cf5f6$0$15495$426a74cc@news.free.fr> Message-ID: <127975a3-b3d9-4799-9673-b292ec8d37e3@x19g2000prg.googlegroups.com> On Jun 9, 2:22 am, Bruno Desthuilliers wrote: > > Does > > anyone object to not having access from outside a function to local > > variables within the function? I doubt it. The other thing is that the > > vast majority of Python software, I would guess, is provided with > > source code. How many Python applications or libraries are provided > > without source code? If you have the source code, you can obviously > > just delete the "priv" keyword anywhere or everywhere it appears. > Yes, fine. And then have to maintain a fork of the source code, and > distribute it with the application. Honking great idea. doh :-( A client who wishes to bypass access restrictions need not maintain any "fork." If you have access to the source code, removing my proposed "priv" keyword from an entire library or application is a one- liner in sed. If you wish to remove only specific instances of its occurrences, that is also a trivial matter, and all that needs to be maintained by the client is a record of which instances were removed. In fact, the client doesn't even need to do that, because when the next version comes out they will be reminded very quickly of where they removed "priv." But such a client would be a real fool for depending on private data and/or methods, of course, because those are not part of the public API and are not guaranteed to remain unchanged. The whole reason for private data and methods is that they give the developers freedom to change the implementation without changing the interface. How about some common sense here. If you, the client, are convinced that something declared private should really be public, then perhaps you should contact the developer and explain your reasoning. If the developer agrees, then the problem is solved. If not, then perhaps it is *you*, the client who does not understand the proper usage of the code. I don't have time to reply to all or your claims, but my lack of a reply to any particular point should not be construed as implicit agreement. From michael at stroeder.com Mon Jun 2 11:15:29 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Mon, 02 Jun 2008 17:15:29 +0200 Subject: ThreadPoolingMixIn In-Reply-To: References: <3d9dac72-ce4d-4ce5-9213-4bb17aff2f9e@r66g2000hsg.googlegroups.com> <1c4d113e-b375-471d-9d54-1401c8844352@t12g2000prg.googlegroups.com> Message-ID: pavel.uvarov at gmail.com wrote: > To benchmark this I used a simple tcp server which writes a small > (16k) > string to the client and closes the connection. Just a general note: When benchmarking such a network service it would be valuable to see benchmark results for several data sizes. I'd expect better numbers for a ThreadPoolingMixIn when there are more requests with smaller data size. Ciao, Michael. From sasa.bistrovic at ck.t-com.hr Thu Jun 12 14:31:46 2008 From: sasa.bistrovic at ck.t-com.hr (Saąa Bistrović) Date: Thu, 12 Jun 2008 20:31:46 +0200 Subject: Exception : Unknown Run-Time error : 210 References: Message-ID: "Sa?a Bistrovi?" wrote in message news:g2rftn$ghv$1 at ss408.t-com.hr... > Sa?a Bistrovi? > Antuna Mihanvi?a 13 > 40000 ?akovec > Croatia > sasa.bistrovic at ck.t-com.hr > > FPC: Exception : Unknown Run-Time error : 210 > > Hi, I'm Sa?a from Croatia. > > And I have : > > Windows XP PRO SP3. > Pentium II MMX 400MHz. > 256 MB of RAM. > > I tried to compile fp.pas. > > But I get this error message : > > 'Running "c:\fpc\fpcbuild-2.2.0\fpcsrc\ide\fp.exe "' > 'Starting value of ConsoleMode is $0000001F' > 'Compiler Verison f p c b u i l d - 2 . 2 . 0 \ f p c s r c \ i d e \ f p > . e x e ' + same unknown exe characters as for GBD Verison > 'GBD Verison f p c b u i l d - 2 . 2 . 0 \ f p c s r c \ i d e \ f p . e > x e ' + same unknown exe characters as for Compiler Verison > 'Cygwin "C:\FPC\222A5D~1.0\BIN\I386-W~1\cygwin1.dll" version 1005.18.0.0' > 'An unhandled exception occurred at $004A74E6' > 'Exception : Unknown Run-Time error : 210' > ' $004A74E6 TSWITCHES__ADDBOOLEANITEM, line 602 of > c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/FPSwitch.pas' > ' $004A92F4 INITSWITCHES, line 1150 of > c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/FPSwitch.pas' > ' $004020DF main, line 382 of c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/fp.pas' > What is right newsgroup for Free Pascal Compiler ? Please HELP ! ! ! ! ! From Scott.Daniels at Acm.Org Sun Jun 8 20:02:54 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 08 Jun 2008 17:02:54 -0700 Subject: Q re documentation Python style In-Reply-To: References: Message-ID: kj wrote: > ... I want to document a function that takes a dictionary as argument, > and this dictionary is expected to have 5 keys. When the number of mandatory > arguments gets above 4, I find that it's too difficult to remember > their order, so I resort to using a dictionary as the single argument. Do you know you can call a function with mandatory args as keyword args? def f(value, scale, metrics, color, age, validity): print 'f', value, scale, metrics, color, age, validity ... f(23, age=6, scale=2.5, metrics=2, validity='strong', color='red') You can even use your arg dictionaries in transitional code: call_dict = {'value': 23, 'age': 6, 'scale': 2.5, 'metrics': 2, 'validity': 'strong', 'color': 'red'} f(**call_dict) --Scott David Daniels Scott.Daniels at Acm.Org From arslanburney at gmail.com Mon Jun 16 01:09:44 2008 From: arslanburney at gmail.com (arslanburney at gmail.com) Date: Sun, 15 Jun 2008 22:09:44 -0700 (PDT) Subject: Extrapolation In Gnuplot Message-ID: <1d05b0fd-612d-431d-89cf-c7c788651458@d1g2000hsg.googlegroups.com> How would u extrapolate/ extend a given line in gnu plot? From jarausch at igpm.rwth-aachen.de Thu Jun 5 05:58:14 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Thu, 05 Jun 2008 11:58:14 +0200 Subject: Python and Harry Potter? Message-ID: <6aprloF38p4l7U1@mid.dfncis.de> Hi, just to let you know ... Today I've got an email from Amazon recommending me Harry Potter and the Deathly Hallows and they told me why they recommended this book, because I've bought Core PYTHON Programming Didn't know, Harry Potter is a Python fan. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From timr at probo.com Thu Jun 5 03:17:31 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 05 Jun 2008 07:17:31 GMT Subject: line continuation for lines ending in "and" or "or" References: <90ee8b5d-1509-4463-aaab-f712f7e72d4b@j33g2000pri.googlegroups.com> Message-ID: <0n4f44tttul6kq9sogqnvtuvnvcn7us5cp@4ax.com> Dan Bishop wrote: >On Jun 4, 10:09?pm, "Russ P." wrote: >> I've always appreciated Python's lack of requirement for a semi-colon >> at the end of each line. I also appreciate its rules for automatic >> line continuation. If a statement ends with a "+", for example, Python >> recognizes that the statement obviously must continue. >> >> I've noticed, however, that the same rule does not apply when a line >> ends with "and," "or," or "not." Yes, it's a minor point, but >> shouldn't the same rule apply? >> >> Seems like it would be easy to add. >... >Implicit line continuation only happens if you have an unmatched '('. > >>>> x = (2 + >... 2 >... ) >>>> x >4 ... or an unmatched [ or an unmatched {. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gabriel.rossetti at arimaz.com Thu Jun 12 02:52:25 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Thu, 12 Jun 2008 08:52:25 +0200 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> References: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> Message-ID: <4850C7A9.9010108@arimaz.com> Mike Orr wrote: > On Jun 5, 8:40 am, Gabriel Rossetti > wrote: > >> Hello everyone, >> >> I had read somewhere that it is preferred to use >> self.__class__.attribute over ClassName.attribute to access class (aka >> static) attributes. I had done this and it seamed to work, until I >> subclassed a class using this technique and from there on things started >> screwing up. I finally tracked it down to self.__class__.attribute! What >> was happening is that the child classes each over-rode the class >> attribute at their level, and the parent's was never set, >> > > That's a misunderstanding of classes vs instances. If you have an > instance of MyClass(Superclass), there is one instance but several > classes. The instance is of MyClass; there is no instance of > Superclass. 'self' has a .__class__ attribute because it's an > instance, but MyClass and Superclass do not because they're already > classes. > > Yes, I know that > Going further, self.a retrieves the instance attribute if it exists, > or or MyClass.a if it doesn't, or Superclass.a if that doesn't. But > assigning to self.a always assigns to an instance attribute. To > assign a class attribute you must use .__class__ or TheClass. > Likewise, to retrieve a class attribute that has been overridden by a > subclass or instance, you must use .__class__ or TheClass. > > There's a very good reason to use self.__class__: it makes it possible > to subclass your class. In Jason Orendorff's path.py, some path > methods return new path objects. He uses 'path()' rather than > self.__class__ to construct these. So if you subclass 'path' to > extend it, these methods return path objects rather than your subclass > objects. In my Unipath package which was written later, I use > self.__class__ in these cases to allow users to extend my class. > > Ok, I see a use for that now, I also tried a minimal example of my problem and it worked as I expected, and thus I am unable to reproduce my problem outside of my code. It may be linked to the fact that I am using Zope interfaces and Tisted's plugin mechanism, as this problem was born in that context ; it's possible that something happens in the background that makes it behave strangely. Basically, I the base class for the plugins create a class attribute of an object that is a mutex and each subclass solicited it for access to the I/O. The class attribute was created only once in it's __init__ (using a conditional test). After running it though a debugger, I saw that in reality, every Child instantiated it, so every child had it's own mutex, thus they could each access the I/O even if it was "supposed" to be locked. I had been using "self.__class__.myMutex" everywhere, so I changed it to "MyClass.myMutex" and the code behaved correctly. This is what prompted me to write this thread. As i said before, I tried reproducing the problem out of context, with just regular classes, no interfaces & plugin mechanism, and it works as I had expected (originally). > It's a little annoying that if you want to print a class's name in > some unknown object, you have to use obj.__class__.__name__ if it's an > instance, and obj.__name__ if it's a class. I sometimes wish classes > had a .__class__ attribute that's the class itself, but I can see how > that would cause its own confusion (and recursion). > > Yes :-) > -- Mike Orr > -- > http://mail.python.org/mailman/listinfo/python-list > > > Gabriel From john.gerald.mason at gmail.com Sun Jun 1 17:52:32 2008 From: john.gerald.mason at gmail.com (Mason) Date: Sun, 1 Jun 2008 14:52:32 -0700 (PDT) Subject: convert binary to float References: <0c15e8e1-948b-4bd6-a312-b1e055da859e@t54g2000hsg.googlegroups.com> <829b1e8f-baac-4ff4-909b-b39df97a436c@d45g2000hsc.googlegroups.com> Message-ID: On Jun 1, 5:12 pm, George Sakkis wrote: > On Jun 1, 3:55 pm, Mason wrote: > > > > > I have tried and tried... > > > I'd like to read in a binary file, convert it's 4 byte values into > > floats, and then save as a .txt file. > > > This works from the command line (import struct); > > > In [1]: f = open("test2.pc0", "rb") > > In [2]: tagData = f.read(4) > > In [3]: tagData > > Out[3]: '\x00\x00\xc0@' > > > I can then do the following in order to convert it to a float: > > > In [4]: struct.unpack("f", "\x00\x00\xc0@") > > Out[4]: (6.0,) > > > But when I run the same code from my .py file: > > > f = open("test2.pc0", "rb") > > tagData = f.read(4) > > print tagData > > > I get this (ASCII??): > > ?@ > > Remembering to put that struct.unpack() call in your module might > help ;-) > > George Wow ... I did have it in there, but I forgot include it in my post. Anyway, this works just fine: f = open("test2.pc0", "rb") tagData = f.read(4) print struct.unpack("f", tagData) Thanks for waking me up George! From zaikenv at gmail.com Fri Jun 27 10:51:07 2008 From: zaikenv at gmail.com (Joel Corbin) Date: Fri, 27 Jun 2008 10:51:07 -0400 Subject: Use of the "is" statement Message-ID: Hello, I'm trying to clarify what exactly the behaviour of the is statement is (or should be). Naturally, this has been nearly impossible to google for, even using quotations... It is my impression that the is statement should be equivalent to "==", at least on some level. However, this equivalency seems to be inconsistent for reasons I can't decipher. Out of the following 3 cases, only 2 return True. What is the difference (and why is there one) in the third case? Python 2.5.2 >>> 'string' is 'string' #simple assignment works True >>> s = 'string' >>> s is 'string' True >>> def make_string(): return 'test' #but function behaviour varies >>> def arg_to_str(arg): return str(arg) >>> make_string() is 'test' True >>> arg_to_string('works') is 'works' # this works True >>> arg_to_string(15) is '15' # but this doesnt >>> arg_to_string(15) is arg_to_string(15) # nor this! >>> arg_to_string(15) '15' >>> arg_to_string(15) == arg_to_string(15) True This became a problem when I was using file.tell() and again when using a custom function. If I am using is in the wrong context, what is the right one? Joel -------------- next part -------------- An HTML attachment was scrubbed... URL: From jaywgraves at gmail.com Fri Jun 6 11:35:32 2008 From: jaywgraves at gmail.com (jay graves) Date: Fri, 6 Jun 2008 08:35:32 -0700 (PDT) Subject: File-writing not working in Windows? References: <80a7b951-591b-41a2-b76c-f97d75db0dad@25g2000hsx.googlegroups.com> Message-ID: <08442be2-13c0-44fc-add4-4907c1202f96@r66g2000hsg.googlegroups.com> On Jun 6, 10:18 am, tda... at gmail.com wrote: > This code works PERFECTLY in Linux. Where I have a match in the file > I'm processing, it gets cut out from the start of the match until the > end of the match, and written to the temporary file in tempdir. > It does not work in Windows. It does not create or write to the > temporary file AT ALL. It creates the tempdir directory with no > problem. In general, I don't use string concatenation when building paths. Especially on scripts that are meant to run on multiple platforms. > Here's the kicker: it works perfectly in Windows if Windows is running > in VMware on a Linux host! (I assume that that's because VMware is > passing some call to the host.) probably a red herring. > Can anyone tell me what it is that I'm missing which would prevent the > file from being created on Windows natively? Get rid of the 'posix' check and use os.path.join to create 'tempfileName' and see if it works. HTH. ... Jay Graves From rurpy at yahoo.com Tue Jun 24 21:51:22 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Tue, 24 Jun 2008 18:51:22 -0700 (PDT) Subject: how to convert '8868' to u'\u8868' References: <5268385d-04c7-4726-ab55-0f729ce8d883@a9g2000prl.googlegroups.com> Message-ID: On Jun 24, 7:30?pm, CodeHunter wrote: > a = '8868' > b = u'\u8868' > > I want to convert a to b > > who can help me ? > > thank you very much! >>> a='8868' >>> unichr(int(a,16)) u'\u8868' From workitharder at gmail.com Sat Jun 14 14:25:54 2008 From: workitharder at gmail.com (bukzor) Date: Sat, 14 Jun 2008 11:25:54 -0700 (PDT) Subject: Python + RDBM framework? References: <9PGdnQYEHsf_nsnVnZ2dnUVZ_t3inZ2d@comcast.com> Message-ID: <18e0d9e9-72f7-4745-8293-db3c504452ba@t12g2000prg.googlegroups.com> On Jun 14, 10:43?am, Larry Bates wrote: > bukzor wrote: > > It seems that whenever I have an application that uses a database > > (MySQL) I end up writing a database framework from scratch. Is there > > some accepted pre-existing project that has done this? > > > I see Django, but that seems to have a lot of web-framework that I > > don't (necessarily) need. I just want to have my objects go in and out > > of the database in a consistent manner without writing a ton of code. > > Can you just use the database part without making a full-blow web app? > > > I see Zope, but that doesn't use MySQL (as far as I can tell), which > > I've invested a lot of time learning to use and optimize. Also, my > > manager wants to be able to log into a MySQL prompt and be able to > > look at the data. > > > --Buck > > Zope definitely has MySQL interface, but if you think Django is a lot then Zope > is even more. ?If I'm understanding your correctly what you want is ORM/ ?These > links should help: > > http://pythonnotes.blogspot.com/2004/09/python-orm-tools.htmlhttp://www.sqlalchemy.org/http://www.sqlobject.org/ > > -Larry Both of those would work. I have a lot of data-integrity checks to make that would be impossible at the MySQL level and hard at the python/MySQLdb level. This will help a lot. I'll probably use the SQLAlchemy. Thanks so much! --Buck From deets at nospam.web.de Thu Jun 12 10:31:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 12 Jun 2008 16:31:47 +0200 Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <6bcokhF3b2mo7U1@mid.uni-berlin.de> Message-ID: <6bcqbpF3a3ubdU1@mid.uni-berlin.de> > To be honest I'm relatively new to Python, so I don't know too much > about how all the loop constructs work and how they differ to other > languages. I'm building an app in Django and this data is coming out > of a database and it looks like what I put up there! > > This was my (failed) attempt: > > predictions = Prediction.objects.all() > scores = [] > for prediction in predictions: > i = [prediction.predictor.id, 0] > if prediction.predictionscore: > i[1] += int(prediction.predictionscore) > scores.append(i) > > I did have another loop in there (I'm fairly sure I need one) but that > didn't work either. I don't imagine that snippet is very helpful, > sorry! It is helpful because it tells us what your actual data looks like. What you need is to get a list of (predictor, score)-pairs. These you should be able to get like this: l = [(p.predictor.id, p.predictionscore) for p in predictions] Now you need to sort this list - because in the next step, we will aggregate the values for each predictor. result = [] current_predictor = None total_sum = 0 for predictor, score in l: if predictor != current_predictor: # only if we really have a current_predictor, # the non-existent first one doesn't count if current_predictor is not None: result.append((predictor, total_sum)) total_sum = 0 current_predictor = predictor total_sum += score That should be roughly it. Diez From vasudevram at gmail.com Tue Jun 10 16:47:00 2008 From: vasudevram at gmail.com (vasudevram) Date: Tue, 10 Jun 2008 13:47:00 -0700 (PDT) Subject: Books for programmers References: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> <32791EDC-1033-4B65-BFB5-DF1CF71EF20D@comhem.se> Message-ID: <4639400c-ef38-4835-82cf-380d58800319@l42g2000hsc.googlegroups.com> On Jun 5, 3:09 am, goldw... at slu.edu (Michael H. Goldwasser) wrote: > Dick Moores writes: > > Do not neglect the 2008 book, "Object-Oriented Programming in Python", > > by Goldwasser and Letscher. > > > > > > > Dick Moores > > I'll note that our book is designed as a "CS1" text, and thus intended > primarly for beginners. So its probably not a match for the original > poster who wants a more advanced Python book. That said, I think its > a great book for those with less experience. > > +----------------------------------------------- > | Michael Goldwasser > | Associate Professor > | Dept. Mathematics and Computer Science > | Saint Louis University > | 220 North Grand Blvd. > | St. Louis, MO 63103-2007 Yes, "Python in a Nutshell" (also by Alex Martelli) and "Programming Python" (by Mark Lutz) are also quite good, as others have said above. - Vasudev Ram http://www.dancingbison.com From duncan.booth at invalid.invalid Thu Jun 12 08:23:03 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jun 2008 12:23:03 GMT Subject: get keys with the same values References: Message-ID: Nader wrote: > I have a dictionary and will get all keys which have the same values. > > d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} > > I will something as : > > d.keys(where their values are the same) > > With this statement I can get two lists for this example: > l1= ['a','e'] > l2=['b','d'] > > Would somebody tell me how I can do it? Here's one way: >>> import itertools, functools, operator >>> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} >>> get = functools.partial(operator.getitem, d) >>> for (k,v) in itertools.groupby(sorted(d, key=get), key=get): print k, list(v) 1 ['a', 'e'] 2 ['c'] 3 ['b', 'd'] 4 ['f'] or if you want a dictionary: >>> dict((k,list(v)) for (k,v) in itertools.groupby(sorted(d, key=get), key=get)) {1: ['a', 'e'], 2: ['c'], 3: ['b', 'd'], 4: ['f']} -- Duncan Booth http://kupuguy.blogspot.com From news at prodata.co.uk Fri Jun 20 07:19:32 2008 From: news at prodata.co.uk (John Dann) Date: Fri, 20 Jun 2008 12:19:32 +0100 Subject: Simple Python class questions References: Message-ID: Many thanks for the further comments: On Thu, 19 Jun 2008 21:24:31 -0400, Terry Reedy wrote: >> def __init__(self): >> Try >> Import serial # the pyserial library >The import should be at module level. You only want to do it once, not >for every link. And if the import fails, you should find out right >away. Yes I was wondering about that, but I wasn't clear about when 'body' code (ie not contained within a def block) in the module might run under Python. So it seemed to be safer to place the import statement inside the 'constructor' to get the earliest warning of non-visibility of pyserial. But you seem to be implying that the body code will run when the class is instantiated - have I understood that right? It surely doesn't run when the module containing the class is imported into the main module - does it?? It would certainly make life easier to place the import in the body of the module. I think that some of the other points hinge on the this one, so let me get my understanding straight on that first! > >I guess you learned by now why cut/paste/edit-down is superior to >re-typing ;-) Well I know what you mean, but actually in this instance my Python environment is a non-networked laptop , so no easy way to cut and paste to a networked PC! (Actually the laptop does have an Ethernet chip in but bizarrely the driver somehow manages to kill my ADSL connection at the exchange or ISP, which takes hours to reset so I take care not to use this option. But learning Linux/Python is a useful role for this otherwise defunct PC) JGD From jeffnyman at gmail.com Thu Jun 5 08:41:28 2008 From: jeffnyman at gmail.com (Jeff Nyman) Date: Thu, 5 Jun 2008 05:41:28 -0700 (PDT) Subject: Creating A Tuple From A List, Adding To Tuple As You Do Message-ID: Greetings all. The subject line of this thread is probably one of the worst ever. I was trying to encapsulate what I am doing. Based on my new-found knowledge from another thread, I'm able to get a list of directories and they come to me in the form of a list. Here is an example: from glob import glob DC_List = glob('\\\\vcdcflx006\\Flex\\Sites\\*\\') DC_List = ['Baltimore', 'Birmingham', 'Cincinnati', 'Cleveland', LosAngeles'] (Each element in the DC_List is actually a full directory path, but I shortened that in the interest of clarity.) The problem is that I need to pass this list to a list control in a wxWidgets application. In order to do that, I need to pass in a list like this: [ ('Baltimore', ''), ('Birmingham', ''), ('Cincinnati', ''), ('Cleveland', ''), ('LosAngeles', '') ] In other words, each element in the list is a tuple that has an empty second string. The problem I'm having is in converting my list above to be of this type. I can't do append because that (logically) puts everything at the end. I did try this: for count in range(0, len(DC_List)): DC_List.insert(count, '') Here I was thinking I could insert a '' into the right place after each entry in the list. That doesn't quite work. Does anyone have an idea of a good approach here? (I did search on tuples and lists and while I found a lot of information about both, I couldn't find a solution that did what I'm discussing above.) - Jeff From gherron at islandtraining.com Fri Jun 20 15:14:15 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 20 Jun 2008 12:14:15 -0700 Subject: Python "is" behavior In-Reply-To: <7578bd5a-c46c-4b29-a792-5b82513d68c7@s21g2000prm.googlegroups.com> References: <7578bd5a-c46c-4b29-a792-5b82513d68c7@s21g2000prm.googlegroups.com> Message-ID: <485C0187.9000503@islandtraining.com> michalis.avraam at gmail.com wrote: > On Jun 20, 9:38 am, Jean-Paul Calderone wrote: > >> On Fri, 20 Jun 2008 09:31:57 -0700 (PDT), michalis.avr... at gmail.com wrote: >> >>> I am not certain why this is the case, but... >>> >>>>>> a = 256 >>>>>> b = 256 >>>>>> a is b >>>>>> >>> True >>> >>>>>> a = 257 >>>>>> b = 257 >>>>>> a is b >>>>>> >>> False >>> >>> Can anyone explain this further? Why does it happen? 8-bit integer >>> differences? >>> >> http://mail.python.org/pipermail/python-list/2001-November/113994.html >> >> Jean-Paul >> > > Thank you for this Jean-Paul. I did know about the identity of > objects, but my curiosity is based on the 256 number. Are the 2^8 > integers cached due to the internal loops, or is there any other > specific reason? Is this something that can be controlled? > Python provides no way to change that number, but of course you can always fiddle with the source code and recompile. The actual value is a trade off (like any caching scheme) of cache-space versus efficiency gains. The value has changed at least once in recent versions of Python. Gary Herron > -- > http://mail.python.org/mailman/listinfo/python-list > From nagle at animats.com Mon Jun 2 12:40:52 2008 From: nagle at animats.com (John Nagle) Date: Mon, 02 Jun 2008 09:40:52 -0700 Subject: robotparser behavior on 403 (Forbidden) robot.txt files Message-ID: <48441f05$0$17181$742ec2ed@news.sonic.net> I just discovered that the "robotparser" module interprets a 403 ("Forbidden") status on a "robots.txt" file as meaning "all access disallowed". That's unexpected behavior. A major site ("http://www.aplus.net/robot.txt") has their "robots.txt" file set up that way. There's no real "robots.txt" standard, unfortunately. So it's not definitively a bug. John Nagle SiteTruth From deets at nospam.web.de Mon Jun 2 18:12:01 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 03 Jun 2008 00:12:01 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> Message-ID: <6aj9hiF2sturnU1@mid.uni-berlin.de> > > Well that's nice: you're accusing me of missing the point after having > quoted something I wrote as if it represented by own views, even > though I footnoted it and said I was only doing it for the sake of > argument. Perhaps, outside this discussion, I am totally getting "the > point". > > I can't tell, though, because I read your post twice and I have no > idea what you consider "the point" to be. > > Best as I can tell you are claiming that data hiding isn't important, > but then you go on to imply Python is blemished because it doesn't > hide data. It really makes no sense: perhaps you can help us out by > giving us an example of something that illustrates what you're saying? > > > (FWIW, my actual view on the matter is I don't give a lick about data > hiding or marking internals.) Do yourself a favor and google antoon's previous posts in this group. He sure is a clever guy & I wouldn't call him a troll - but a bit trollish.. Diez From dusan.smitran at gmail.com Tue Jun 10 04:03:56 2008 From: dusan.smitran at gmail.com (dusans) Date: Tue, 10 Jun 2008 01:03:56 -0700 (PDT) Subject: eric4 wont start Message-ID: <06c79177-25ee-464a-9387-ce016975cf90@t54g2000hsg.googlegroups.com> Hi i took a look at eric4, its nice, cuz u have the script output and console in the same window, which is why i love pyscripter. Then i upgradet eric4 to newest version: eric4-4.0.4, it doesnt start, even when i installed the old version: The error massage is: Warning: translation file 'qt_en_US'could not be loaded. Using default. Warning: translation file 'eric4_en_US'could not be loaded. Using default. Warning: translation file 'qscintilla_en_US'could not be loaded. Using default. It just stopes and doesnt go on. Anyone got an idea how to solve this, cuz i really like eric4 From aweraw at gmail.com Tue Jun 10 21:20:48 2008 From: aweraw at gmail.com (Aidan) Date: Wed, 11 Jun 2008 11:20:48 +1000 Subject: Dynamic HTML from Python Script In-Reply-To: <484f24e9$0$5020$607ed4bc@cv.net> References: <484f151c$0$5009$607ed4bc@cv.net> <484f21aa$1@dnews.tpgi.com.au> <484f24e9$0$5020$607ed4bc@cv.net> Message-ID: <484f2870$1@dnews.tpgi.com.au> asdf wrote: >> Well, there's a few ways you could approach it. >> >> You could create a cgi program from your script - this is probably the >> solution you're looking for. >> > > Output from the script does come up very often. There is a new output > every 10 secs and it's possible that the script might be run indefinitely. > Basically I want all that output displayed in a web browser Well, in that case you could simply append the new output to a static file every 10 seconds, or whenever there is new output. That way, you just need to refresh the static file in your browser to see updates... Given what I understand of your situation, that's how I'd do it. A constantly running CGI app is probably not the best idea, given timeouts and other such constraints you might run into. >> You could have the script run periodically and create a static html file >> in the webroot... this would be acceptable, maybe preferable, if the >> output from your script doesn't change frequently. >> From jaraco at jaraco.com Fri Jun 13 11:17:29 2008 From: jaraco at jaraco.com (Jason R. Coombs) Date: Fri, 13 Jun 2008 08:17:29 -0700 (PDT) Subject: namedtuple suggestions Message-ID: <318037bd-e126-4c41-ac65-c2afb9fd768d@w7g2000hsa.googlegroups.com> I see a new function in (python 2.6) lib/collections called namedtuple. This is a great function. I can see many places in my code where this will be immensely useful. I have a couple of suggestions. My first suggestion is to use self.__class__.__name__ instead of the hard-coded typename in __repr__, so that subclasses don't have to override these methods just to use the correct name. def __repr__(self): return self.__class__.__name__ + '(%(reprtxt)s)' %% self \n My other suggestion, which is perhaps more intrusive, would be to implement the underlying class as a metaclass, rather than constructing and exec'ing a string. This would make the code more readable (as there wouldn't be format string substitions in the class definition, and the code could be interpreted by editors for syntax highlighting, indentation support, etc). I'm willing to take up the latter effort if there's agreement this could be included in the release. Regards, Jason R. Coombs From mrmakent at cox.net Sat Jun 14 14:04:23 2008 From: mrmakent at cox.net (Mike Kent) Date: Sat, 14 Jun 2008 11:04:23 -0700 (PDT) Subject: Subclassing list, what special methods do this? References: <7ba7e964-2d34-4594-8cfc-79dbf904df18@f63g2000hsf.googlegroups.com> <20149773-a485-4762-b3d0-f5be948df1b0@27g2000hsf.googlegroups.com> Message-ID: <41293e17-69ab-4d4b-b7b1-cdd45764cec1@d77g2000hsb.googlegroups.com> On Jun 13, 8:43?pm, Matimus wrote: ...chop... > So, it looks like as long as you want to subclass list, you are stuck > implementing both __*slice__ and __*item__ methods. > > Matt Thanks. That was clear and concise, just what I needed. From eckhardt at satorlaser.com Tue Jun 3 10:22:35 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 03 Jun 2008 16:22:35 +0200 Subject: Image Processing (batch) References: <6akqd5F37rofnU1@mid.individual.net> Message-ID: Thomas Guettler wrote: > I tried PIL for image batch processing. But somehow I don't like it > - Font-Selection: You need to give the name of the font file. > - Drawing on an image needs a different object that pasting and saving. > - The handbook is from Dec. 2006. > > What image libraries do you suggest? I haven't looked at it yet, but I was thrilled to hear that GIMP (www.gimp.org) had the ability to be extended via Python scripts. Maybe that would help? Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From dullrich at sprynet.com Thu Jun 12 10:30:58 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 12 Jun 2008 09:30:58 -0500 Subject: regex for balanced parentheses? References: <7a054807-4b96-4acb-a21d-7970fd621715@8g2000hse.googlegroups.com> Message-ID: On Thu, 12 Jun 2008 06:38:16 -0700 (PDT), Paul McGuire wrote: >On Jun 12, 6:06?am, David C. Ullrich wrote: >> There's no regex that detects balanced parentheses, >> or is there? >> >> [...] > >Pyparsing includes several helper methods for building common >expression patterns, such as delimitedList, oneOf, operatorPrecedence, >countedArray - and a fairly recent addition, nestedExpr. nestedExpr >creates an expression for matching nested text within opening and >closing delimiters, such as ()'s, []'s, {}'s, etc. Keen. Howdya know I wanted that? Thanks. TeX is one of the amazing things about free software. Knuth is great in many ways. He totally blew it in one detail, unfortunately one that comes up a lot: '$' is an opening delimiter, for which the corresponding closing delimiter is also '$'. Then better yet, '$$' is another double-duty delimiter... what I've done with that is first split on '$$', taking the odd-numbered bits to be the parts enclosed in $$..$$, and then taking the remining parts and splitting on $. Not hard but it gives me a creepy feeling. Hence the question: Can pyparsing tell the difference between '$' and '$'? (heh-heh). > The default >delimiters are ()'s. You can also specify a content expression, so >that pyparsing will look for and construct meaningful results. The >default is to return any text nested within the delimiters, broken up >by whitespace. > >Here is your sample string parsed using the default nestedExpr: >>>> from pyparsing import nestedExpr >>>> for e in nestedExpr().searchString('and so ((x+y)+z) = (x+(y+z))'): >... print e[0] >... >[['x+y'], '+z'] >['x+', ['y+z']] > >Pyparsing found 2 matches in your input string. Note that the parens >are gone from the results - nestedExpr returns a nested list >structure, with nesting corresponding to the ()'s found in the >original string. > >Pyparsing supports parse-time callbacks, called 'parse actions', and >it comes with several commonly used methods, such as removeQuotes, >upcaseTokens, and keepOriginalText. The purpose of keepOriginalText >is to revert any structuring or parsing an expression or other parse >actions might do, and just return the originally matched text. > >Here is how keepOriginalText gives you back just the nested >parenthetical expressions, without any additional processing or >grouping: >>>> from pyparsing import keepOriginalText >>>> matchedParens = nestedExpr().setParseAction(keepOriginalText) >>>> for e in matchedParens.searchString('and so ((x+y)+z) = (x+(y+z))'): >... print e[0] >... >((x+y)+z) >(x+(y+z)) > >-- Paul David C. Ullrich From Chris8Boyd at gmail.com Fri Jun 6 14:25:08 2008 From: Chris8Boyd at gmail.com (Chris8Boyd at gmail.com) Date: Fri, 6 Jun 2008 11:25:08 -0700 (PDT) Subject: Cannot use Winpdb (or PyDev) to trace embedded Python script in MSVC++ application - ImportError: No module named _socket References: <8a739206-1f72-47ee-8a9f-50ec2c91bde2@j33g2000pri.googlegroups.com> <82989ee9-f9ce-4a88-84b8-c5a0fa2e784e@t12g2000prg.googlegroups.com> Message-ID: <12599118-73c9-45af-94fc-5a791713445d@v1g2000pra.googlegroups.com> On Jun 6, 1:13 am, Nir wrote: > You seem to be having a problem with the import path of the embedded > interpreter. I suppose the embedded interpreter includes some modules > in a particular folder and _socket is not one of them. For the sake of > debugging try adding the c:\python25\lib path to the sys.path variable > of the interpreter before attempting to import rpdb2. > > Does this work? > > Nir > > On Jun 5, 2:52 pm, Chris8B... at gmail.com wrote: > > > I am embedding Python in a MSVC++ (2005) application. The application > > creates some environment and then launches a Python script that will > > call some functions exported from the MSVC++ application. > > > I want to be able to debug the Python script by using a debug server, > > likeWinpdb(winpdb.org). > > > I use ActivePython 2.5.2.2, Microsoft Visual Studio 2005, andWinpdb > > 1.3.8. > > > When I launch a script like "e:>python test.py" everything is O'K and > > I can useWinpdbto trace/debug. > > > When I run the same script from the MSVC++ application, there is > > always a complain "ImportError: No module named _socket". > > > Here is the basic test script I use: > > > def Process( something ): > > print "\n\nStarted debugging\n=================\n" > > #pydevd.settrace() > > import rpdb2; rpdb2.start_embedded_debugger("1") > > print "\n\nStopped debugging\n=================\n" > > > if __name__ == '__main__': > > Process( "test" ) > > <<< > > > In the MSVC++ application I tried many approaches, as suggested by > > many people, and all of them work to launch the script, but none of > > them works withWinpdb(or PyDev for Eclipse - same problem). Just for > > completeness - here is one: > > > PyRun_SimpleString("import sys"); > > PyRun_SimpleString("import os"); > > PyRun_SimpleString( "fullpath = os.path.abspath(\"E:/Test.py\")" ); > > PyRun_SimpleString( "g = globals().copy()" ); > > PyRun_SimpleString( "g['__file__'] = fullpath"); > > PyRun_SimpleString( "execfile(fullpath, g) "); > > <<< > > > If I use pdb (import pdb + pdb.runcall(something) ) everything works > > fine, but I need the performance and convinience ofWinpdb. > > > What am I doing wrong? > > > Your help is highly appreciated! > > > Best regards, > > Chris Nir, > Does this work? Unfortunately, not. I did some experiments to check the sys.path hypothesis: - In my MSVC++ application I did PyRun_SimpleString("import cgi"); - it complained about missing _socket. - Did PyRun_SimpleString("print sys.path") to get the sys.path as seen from within the application environment (that does not find _socket) - Did the same in "test.py" and ran ...>Python test.py to get the sys.path for the environment that _does_ find _socket - Compared the two - the working environment had two more paths: C:\\WINDOWS\\system32\\python25.zip C:\\Python25\\lib\\plat-win - Added the missing path to the embedded environment: PyRun_SimpleString("import sys"); PyRun_SimpleString("import os"); PyRun_SimpleString("sys.path.append(\"C:\\WINDOWS\\system32\ \python25.zip\")"); PyRun_SimpleString("sys.path.append(\"C:\\Python25\\lib\\plat-win \")"); PyRun_SimpleString("print sys.path"); PyRun_SimpleString("import cgi"); Not all paths that are in the working environment are present in the embedded environment, but still there is a problem: Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\cgi.py", line 40, in import urllib File "c:\Python25\lib\urllib.py", line 26, in import socket File "c:\Python25\lib\socket.py", line 45, in import _socket ImportError: No module named _socket Chris From rhamph at gmail.com Fri Jun 20 13:50:59 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Fri, 20 Jun 2008 10:50:59 -0700 (PDT) Subject: How do i : Python Threads + KeyboardInterrupt exception References: <089f56d2-5e44-4161-b580-84881717bd05@w4g2000prd.googlegroups.com> <6cfbfaa2-293f-41d3-b544-fd47f05d0d36@j33g2000pri.googlegroups.com> <93eb3402-1dde-4ad3-b91f-d4b091048ac0@g16g2000pri.googlegroups.com> Message-ID: On Jun 19, 11:09?pm, Brendon Costa wrote: > > If only the main thread can receive KeyboardInterrupt, is there any > > reason why you couldn't move the functionality of the Read thread into > > the main thread? It looks like it's not doing any work, just waiting > > for the Proc thread to finish. > > > You could start the Proc thread, do the current Read thread > > functionality until the interrupt occurs, put the apporpriate message > > in the queue, and then wait for the Proc thread to finish. > > It is already doing that. You will notice that the Proc() function is > called by a threading.Thread instance so Proc() is running in a > thread, but the Read() function is being called by the main thread > right after this. It DOES work with the Ctrl + C, but i can find no > way at all of closing down the script from within the Proc() thread. > > The relevant bit of code is: > t = MyThread(Proc, queue, sys.stderr, None) > Read(queue, sys.stdin, sys.stderr) > > In the end, the problem is that i am trying to multiplex IO and other > operations. In UNIX i would use select with the input file descriptor > and an anonymous pipe for the extra commands to achieve this without > any threads, but this script needs to run primarily on a windows box > and i would like to use it on UNIX too. I thought i could use threads > to achieve the IO Multiplexing in python, but it seems not or at least > not simply. > > How do people usually manage IO multiplexing (not just using sockets) > cross platform in python? > > I only need to multiplex two sources really: > * Input file or stdin > * A input event queue > ? ?This will have messages injected from various locations: timers, > the processing thread itself, and possibly from a single GUI thread at > a later point in time. > > Though i can foresee that at some point in the future i may also need > to multiplex those two above and some sockets (For a server with a few > clients). > > I was thinking of looking at some asynchronous IO libraries for python > on Windows + UNIX, any suggestions (Must include more than just > sockets)? They either use an event-driven library.. or they use a timeout of around 1 second. 1 second will definitely waste power on laptops (and desktops), but it *works*. python-safethread has this fixed - any lowlevel trickery needed is done for you - but it's not ported to windows yet. From subhabrata.iisc at hotmail.com Fri Jun 13 03:12:47 2008 From: subhabrata.iisc at hotmail.com (subhabrata.iisc at hotmail.com) Date: Fri, 13 Jun 2008 00:12:47 -0700 (PDT) Subject: HTML FORM AND PYTHON Message-ID: Dear Members of the group, I have a small question, if you can help me to find the answer. I have one function: def add_string(n): print ?Print Two strings? print ?Print the First String? a1=raw_input(?PRINT THE FIRST STRING?) a2=raw_input(?PRINT THE SECOND STRING?) print ?CONCATENATING THE TWO GIVEN STRINGS? a3=a1+a2 print ?THE RESULT IS? print a3 Now, I have designed one HTML form which has two input fields for text and an output field for the result. I like to bind the python program into HTML form. i) Is there any way I can keep both my existing python code and HTML code and bind them? If any one can suggest with example. ii) Do I have to write the whole code in a way in python so that it would work the function as well as generate HTML form I am looking for? If any one can suggest with example. iii) Is there any other way? Best Regards, Subhabrata. From lajam at caramail.com Fri Jun 27 09:36:47 2008 From: lajam at caramail.com (lajam at caramail.com) Date: Fri, 27 Jun 2008 06:36:47 -0700 (PDT) Subject: where is the error? References: <8f8e1bf7-78b0-4292-9d56-396527b9dfb1@z66g2000hsc.googlegroups.com> <15ea1cb1-76a3-4fd3-8e4c-521b9aefcca2@m3g2000hsc.googlegroups.com> Message-ID: <19295372-0910-4d79-9ceb-52ca88d04729@y38g2000hsy.googlegroups.com> > > I think that you mean that diff_temp will be an array of the numberS > (plural) of the lines (rows?) in values array that met the -2 < x < 2 > criterion. Now you want to be able to use diff_temp to get the > corresponding subset of some other array. Am I getting close? I think that you're getting close. I want to get the lines that met the criterion. Diff_temp is an array containing the values of the lines. So bascially, > Now you want to be able to use diff_temp to get the corresponding > subset of some other array. Am I getting close? yes > Perhaps you need something like other_array.take(diff_temp) ? And my problem was that the commands worked on windows but not on linux. > By the way, shouldn't you be using numpy? I thought numarray was going > away by mid-2008 i.e. now. I know, but i'm not sure that it's the problem. Thanks Cedric From thermate2 at india.com Tue Jun 3 00:22:46 2008 From: thermate2 at india.com (thermate2 at india.com) Date: Mon, 2 Jun 2008 21:22:46 -0700 (PDT) Subject: Errata competion for the LaTeX Graphics Companion, Second edition --- first winner References: Message-ID: It is not difficult to predict that your book will soon be scanned and appear on the khazar site http://betah.co.il Even if does not appear there, the khazar site, namely books.google.com will get it scanned. Now what gives google the right to scan a book and store it on their computers ? Why cant we do it ? Why cant we employ every single argument that google will concoct to justify this action ? The fact is that the Israeli hackers are the leaders in all the copyright violations and have recruited PATSIES from other races and nationalities to take the crumbs in the more open forums, while Israeli hackers work in the hiding. But since this enmasse intellectual property theft (or potential theft) which is a RTN away, ie one command, not even a screw away as is alleged for IRAN nuclear crap, The whole world in implementing SELECTIVE copyright will be CUTTING their OWN FEET with their OWN HANDS. There is no way to send US army into Israeli houses and buildings to check every place and dig every floor for hard disks containing the intellectual property on google-israel. The RUBICON has been crossed. The JINNI is out of the bottle. I am just bringing the argument to the forefront. Nothing can be done now. Either live with a super race of all intellectual property in Israel and cut your own feet. In either case its loss - loss. On Jun 2, 6:08 am, Frank Mittelbach wrote: > I'm pleased to announce that we have a first winner: > > Milan Vujtek > > Congratulation to a free book from A-W. > > The number of misprints found so far is rather low, so either we got better > with this book (my hope :-) but I don't really believe this) or people are > not sending me the errors they have found. Please do, it helps everybody > and it might earn you the next prize which will be due in about a year. > > Details of the contest and the current list of errata entries can be found > at > > http://www.latex-project.org/guides/books.html > > There you can also find excerpts from all (or most of all) chapters to give > you an impression of the books content. > > http://www.latex-project.org/guides/lgc2-excerpts.pdf (2.9 mb!) > > thanks for participating in the contest (sending in errors benefits all > readers) and good luck > > frank > > ps there are no plans to translate the book to German, which is why I > cross-posted to the German de.comp.text.tex rather than announcing a German > competion From paddy3118 at googlemail.com Thu Jun 12 14:07:43 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 12 Jun 2008 11:07:43 -0700 (PDT) Subject: Counting things fast - was Re: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> Message-ID: <20049a04-37cd-4c2c-a9e8-67360706ea77@a1g2000hsb.googlegroups.com> On Jun 12, 4:14 pm, Gerhard H?ring wrote: > Aidan wrote: > > does this work for you? > > > users = [1,1,1,2,2,3,4,4,4] > > score = [0,1,5,3,1,2,3,3,2] > > > d = dict() > > > for u,s in zip(users,score): > > if d.has_key(u): > > d[u] += s > > else: > > d[u] = s > > > for key in d.keys(): > > print 'user: %d\nscore: %d\n' % (key,d[key]) > > I've recently had the very same problem and needed to optimize for the > best solution. I've tried quite a few, including: > > 1) using a dictionary with a default value > > d = collections.defaultdict(lambda: 0) > d[key] += value > <> > -- Gerhard This might be faster, by avoiding the lambda: d = collections.defaultdict(int) d[key] += value - Paddy. From sjmachin at lexicon.net Tue Jun 17 08:07:55 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 17 Jun 2008 05:07:55 -0700 (PDT) Subject: Numeric type conversions References: Message-ID: <23739f6d-d48a-46ec-be88-2092c68f4124@j33g2000pri.googlegroups.com> On Jun 17, 9:28 pm, John Dann wrote: > I'm new to Python and can't readily find the appropriate function for > the following situation: > > I'm reading in a byte stream from a serial port (which I've got > working OK with pyserial) and which contains numeric data in a packed > binary format. Much of the data content occurs as integers encoded as > 2 consecutive bytes, ie a 2-byte integer. > > I'm guess that there should be a function available whereby I can say > something like: > > My2ByteInt = ConvertToInt(ByteStream[12:13]) > > to take a random example of the 2 bytes occurring at positions 12 and > 13 in the byte stream. > > Can anyone point me in the right direction towards a suitable function > please? > > NB I don't know without further checking exactly how the bytes are > encoded, but I'm just transcribing some code across from a Windows > VB.Net program and these same bytes could be read straight into a > standard 2-byte signed short int, so I can be confident that it's a > fairly standard Windows-compatible encoding. You need the unpack function of the struct module. Supposing you have a four-byte string containing two such short ints, first + 1 then -1 then this will work: >>> import struct >>> two_shorts = '\x01\x00\xff\xff' >>> struct.unpack('>> In the format string, '<' means little-endian (almost universal on PCs running Windows), and 'h' means a signed 'half-word'. See the struct manual section for more options. You can write a function called convert_to_int (take a hint on naming conventions) and use it a slice at a time, or you can use struct.unpack to grab a whole record at once. Here's a real live example of that: ( f.height, option_flags, f.colour_index, f.weight, f.escapement_type, f.underline_type, f.family, f.character_set, ) = unpack(' <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> Message-ID: <6b367e4a-9d8a-493e-91b6-0661efa48e0a@c58g2000hsc.googlegroups.com> On Jun 2, 8:14 am, Carl Banks wrote: > Fair enough, but I don't see anything in your example that suggests a > way to discriminate between access from within the class and access > from outside the class, which is the crucial aspect of data hiding. And, if you want an example of something that does that, how about this metaclass. It creates a class that checks the stack frame to see if the caller was defined in the same class. Issues: Classes are prevented from defining their own __setattr__ and __getattribute__. Classes and subclasses should not use the same names for their private variables. Private attribute access is pretty slow, but that's obvious. Pretty easy to thwart. #---------------------------------- import sys import itertools class PrivateAccessError(Exception): pass class PrivateDataMetaclass(type): def __new__(metacls,name,bases,dct): function = type(lambda x:x) privates = set(dct.get('__private__',())) codes = set() for val in dct.itervalues(): if isinstance(val,function): codes.add(val.func_code) getframe = sys._getframe count = itertools.count def __getattribute__(self,attr): if attr in privates: for i in count(1): code = getframe(i).f_code if code in codes: break if code.co_name != '__getattribute__': raise PrivateAccessError( "attribute '%s' is private" % attr) return super(cls,self).__getattribute__(attr) def __setattr__(self,attr,val): if attr in privates: for i in count(1): code = getframe(i).f_code if code in codes: break if code.co_name != '__setattr__': raise PrivateAccessError( "attribute '%s' is private" % attr) return super(cls,self).__setattr__(attr,val) dct['__getattribute__'] = __getattribute__ dct['__setattr__'] = __setattr__ cls = type.__new__(metacls,name,bases,dct) return cls #---------------------------------- import traceback class A(object): __metaclass__ = PrivateDataMetaclass __private__ = ['internal'] def __init__(self,n): self.internal = n def inc(self): self.internal += 1 def res(self): return self.internal class B(A): __private__ = ['internal2'] def __init__(self,n,m): super(B,self).__init__(n) self.internal2 = m def inc(self): super(B,self).inc() self.internal2 += 2 def res(self): return self.internal2 + super(B,self).res() def bad(self): return self.internal2 + self.internal a = A(1) a.inc() print "Should print 2:" print a.res() print print "Should raise PrivateAccessError:" try: print a.internal except PrivateAccessError: traceback.print_exc() print b = B(1,1) b.inc() print "Should print 5:" print b.res() print print "Should raise PrivateAccessError:" try: print b.internal2 except PrivateAccessError: traceback.print_exc() print print "Should raise PrivateAccessError:" try: print b.bad() except PrivateAccessError: traceback.print_exc() print #---------------------------------- Carl Banks From nick at craig-wood.com Sat Jun 7 06:30:21 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 07 Jun 2008 05:30:21 -0500 Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> Message-ID: David wrote: > Would it be possible for a 3rd-party threading library to an > 'interruptible' version of Queue? > > The same methods as the normal Queue, but when you call a new .kill() > method on the queue, all the threads locking on the queue get a > "QueueKilled" exception thrown. > > It might be as simple as a Queue wrapper where .kill() adds a speciall > Killed value to the queue, and the .get() wrapper throws a QueueKilled > exception (after re-putting Killed) when it reads Killed. There seem to me to be 2 basic types of threads - I'll call them client threads and server threads. A client thread listens on a Queue for its instructions and replies via a different Queue, or via Queues passed in in its instructions. That kind of thread can easily have an instruction which means quit. When it isn't processing instructions there is a nice clean moment for it to quit. However if the processing takes a long time then there will be a long wait for the thread to die. This is the scenario described above. The server type thread is processing all the time. Every now and again it sends its results via a Queue. An example of this type of thread might be one listening on a socket. This type of thread has no nice moment to listen for instructions to quit as it might well be blocked on something else (eg listening to a socket). To make this type of thread kill nicely you have to go back to breaking up your work into chunks (eg polling the socket asynchronously) and polling the command queue to wait for your quit instruction which is wastefull of CPU resources. So it seems to me that there isn't a good solution to killing python threads of either type, other than coding them carefully and checking for quit instructions regularly. You can kill them using the internal python API and ctypes, but you run the risk of leaving things in an inconsistent state which is why that API isn't exposed. Here is an attempt at a killable thread http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496960 and http://sebulba.wikispaces.com/recipe+thread2 Read the caveats! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From cricket.keith at gmail.com Wed Jun 11 12:40:51 2008 From: cricket.keith at gmail.com (Keith Nation) Date: Wed, 11 Jun 2008 11:40:51 -0500 Subject: Reading info from an active file Message-ID: <21935b370806110940y3c4f4a33l8fd06ad679fb6863@mail.gmail.com> I have a program that writes a log file as it is running to give status of the job. I would like to read that file, pull certain lines of text from it, and write to a new file. Because I am such a novice user, I was hoping someone had covered this before and could let me know of your methods. If I open and close the file repeatedly to get refreshed information, I assume it would slow the system down. Any thoughts? Keith Nation -------------- next part -------------- An HTML attachment was scrubbed... URL: From szrRE at szromanMO.comVE Mon Jun 2 01:24:42 2008 From: szrRE at szromanMO.comVE (szr) Date: Sun, 1 Jun 2008 22:24:42 -0700 Subject: Python's doc problems: sort References: <929d5ce9-9063-4e6c-98aa-89526f89fba3@y18g2000pre.googlegroups.com> Message-ID: szr wrote: > J?rgen Exner wrote: >> "Andrew Koenig" wrote: >>> wrote in message >> >> [Subject: Python's doc problems: sort] >>>> I want to emphasize a point here, as i have done quite emphatically >>>> in the past. The Python documentation, is the world's worst >>>> technical >> >> And WTF does Python documentation have to do with Perl of Lisp? >> >> szr, do you still have any doubts about the nature of xahlee? > > I wasn't involved in this thread, but no, after that statement > comparing Perl's and Python's docs, I no doubts. * should have been, ", I have no doubts." -- szr From asdf at asdf.com Tue Jun 10 22:16:20 2008 From: asdf at asdf.com (asdf) Date: 11 Jun 2008 02:16:20 GMT Subject: Dynamic HTML from Python Script References: <484f151c$0$5009$607ed4bc@cv.net> <484f21aa$1@dnews.tpgi.com.au> <484f24e9$0$5020$607ed4bc@cv.net> <484f2870$1@dnews.tpgi.com.au> Message-ID: <484f3574$0$4998$607ed4bc@cv.net> On Wed, 11 Jun 2008 11:20:48 +1000, Aidan wrote: > asdf wrote: >>> Well, there's a few ways you could approach it. >>> >>> You could create a cgi program from your script - this is probably the >>> solution you're looking for. >>> >>> >> Output from the script does come up very often. There is a new output >> every 10 secs and it's possible that the script might be run >> indefinitely. Basically I want all that output displayed in a web >> browser > > Well, in that case you could simply append the new output to a static > file every 10 seconds, or whenever there is new output. That way, you > just need to refresh the static file in your browser to see updates... > Given what I understand of your situation, that's how I'd do it. > The problem with this is that browser would have to be refreshed manually every 10 seconds. Unless there is a way to set this in the script itself. > A constantly running CGI app is probably not the best idea, given > timeouts and other such constraints you might run into. > > >>> You could have the script run periodically and create a static html >>> file in the webroot... this would be acceptable, maybe preferable, if >>> the output from your script doesn't change frequently. >>> From precisionreplicas at gmail.com Wed Jun 4 12:18:44 2008 From: precisionreplicas at gmail.com (Best Replica Watches) Date: Thu, 5 Jun 2008 00:18:44 +0800 Subject: perfect replica watches for sale Message-ID: perfect replica watches for sale I wanted to purchase a new Rolex, but couldn't afford it. I looked for high quality replica watches for sale online and finaly found Precision Replicas(URL: http://www.precisionreplicas.com) I was impressed that they show the picture of the replica watch you get. I recommend them. From hniksic at xemacs.org Thu Jun 19 07:04:29 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 19 Jun 2008 13:04:29 +0200 Subject: python string comparison oddity References: <3ebd170e-8686-4bb4-9e47-0fba2179feb3@p39g2000prm.googlegroups.com> Message-ID: <87iqw5heiq.fsf@mulj.homelinux.net> Faheem Mitha writes: > Yes, but why is '-' and 'foo' cached, and not '--'? Do you know what > the basis of the choice is? Caches such as intern dictionary/set and one-character cache are specific to the implementation (and also to its version version, etc.). In this case '-' is a 1-character string, all of which are cached. Python also interns strings that show up in Python source as literals that can be interpreted as identifiers. It also reuses string literals within a single expression. None of this should be relied on, but it's interesting to get insight into the implementation by examining the different cases: >>> '--' is '--' True # string repeated within an expression is simply reused >>> a = '--' >>> b = '--' >>> a is b False # not cached >>> a = '-' >>> b = '-' >>> a is b False # all 1-character strings are cached >>> a = 'flobozz' >>> b = 'flobozz' >>> a is b True # flobozz is a valid identifier, so it's cached >>> a = 'flo-bozz' >>> b = 'flo-bozz' >>> a is b False From miller.paul.w at gmail.com Mon Jun 2 17:24:21 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Mon, 2 Jun 2008 14:24:21 -0700 (PDT) Subject: Checking each item in m.group()? References: Message-ID: <2d1b2ac1-3fa1-41c7-a2c2-560c8322b6fb@z72g2000hsb.googlegroups.com> On Jun 2, 5:06?pm, Peter Otten <__pete... at web.de> wrote: > You are taking the wrong approach here. > > Don't build SQL statements as strings; you are enabling the next SQL > injection attack. Pass parameters using the DB API instead. > > Don't use regular expressions to parse a CSV file. Python's csv module is > more likely to deal correctly with the quirks of that standard. > I'd like to second both these statements. Regardless of whether these CSV files are from a trusted source or not, it's a virtual truism of programming that eventually, any application will be used in ways it was not intended. Since using a parameterized query is a simple way to avoid a common security hole, even if such a thing could never be exploited by the app in its current configuration, you should do things the Right Way. That way, even if your code is twisted to some other use in the future, it's less likely to cause problems. From M8R-yfto6h at mailinator.com Mon Jun 23 23:31:10 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Mon, 23 Jun 2008 20:31:10 -0700 Subject: Question: How do I format printing in python References: Message-ID: <_76dnUf30a3n9_3VnZ2dnUVZ_omdnZ2d@comcast.com> wrote in message news:c6e1cfa9-207a-461b-babe-2a14cdd1b25a at y21g2000hsf.googlegroups.com... > Hi All, > > How do I format printed data in python? > I could not find this in the Python Reference Manual: > http://docs.python.org/ref/print.html > Nor could I find it in Matloff's great tutorial: > http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf > > > For example, how do I turn this: > > 512 Jun 5 2004 X11r6 > 22 Jan 17 2005 a2p > 22 Jan 17 2005 acctcom > 5374 Sep 15 2002 acledit > 5664 May 13 2004 aclget > 12020 May 13 2004 aclput > 115734 Jun 2 2004 adb > 46518 Jun 4 2004 admin > 66750 Sep 16 2002 ali > 1453 Sep 15 2002 alias > 28150 Jun 4 2004 alog > 15 May 12 2005 alstat > > into this: > > 512 Jun 5 2004 X11r6 > 22 Jan 17 2005 a2p > 22 Jan 17 2005 acctcom > 5374 Sep 15 2002 acledit > 5664 May 13 2004 aclget > 12020 May 13 2004 aclput > 115734 Jun 2 2004 adb > 46518 Jun 4 2004 admin > 66750 Sep 16 2002 ali > 1453 Sep 15 2002 alias > 28150 Jun 4 2004 alog > 15 May 12 2005 alstat > > Thank you data = '''\ 512 Jun 5 2004 X11r6 22 Jan 17 2005 a2p 22 Jan 17 2005 acctcom 5374 Sep 15 2002 acledit 5664 May 13 2004 aclget 12020 May 13 2004 aclput 115734 Jun 2 2004 adb 46518 Jun 4 2004 admin 66750 Sep 16 2002 ali 1453 Sep 15 2002 alias 28150 Jun 4 2004 alog 15 May 12 2005 alstat '''.split('\n') for line in data: elements = line.split() print '%-11s%-6s%-4s%-8s%s' % tuple(elements) -Mark From roy at panix.com Fri Jun 27 22:15:21 2008 From: roy at panix.com (Roy Smith) Date: Fri, 27 Jun 2008 22:15:21 -0400 Subject: Do I need "self" and "other"? References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> Message-ID: In article <68566b52-100d-40ee-a0c6-bde20df9ecd4 at a70g2000hsh.googlegroups.com>, Kurda Yon wrote: > Hi, > > I found one example which defines the addition of two vectors as a > method of a class. It looks like that: > > class Vector: > def __add__(self, other): > data = [] > for j in range(len(self.data)): > data.append(self.data[j] + other.data[j]) > return Vector(data) > > In this example one uses "self" and "other". Does one really need to > use this words? And, if yes, why? I have replaced "self" by "x" and > "other" by "y" and everything looks OK. Is it really OK or I can have > some problem in some cases? Technically, Python doesn't care what you call them. You could write: def __add__(luxury_yacht, throat_warbler_mangrove): etc, etc, etc and it would run exactly the same. That being said, don't do that. The use of "self" and "other" are pretty much de rigueur. Experienced Python programers will instantly understand what they mean. If you use anything else, they will have to spend more time trying to understand your code. From deets at nospam.web.de Mon Jun 16 17:16:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 16 Jun 2008 23:16:54 +0200 Subject: How to request data from a lazily-created tree structure ? In-Reply-To: References: Message-ID: <6bo3ifF3dj7dmU1@mid.uni-berlin.de> m?choui schrieb: > Problem: > > - You have tree structure (XML-like) that you don't want to create > 100% in memory, because it just takes too long (for instance, you need > a http request to request the information from a slow distant site). > - But you want to be able to request data from it, such has "give me > all nodes that are under a "//foo/bar" tree, and have a child with an > "baz" attribute of value "zzz". > > Question : > > Do you have any other idea to request data from a lazily-created tree > structure ? > > And does it make sense to create a DOM-like structure and to use a > generic XPath engine to request the tree ? (and does this generic > XPath engine exist ?) > > The idea is to have the tree structure created on the fly (we are in > python), only when the XPath engine requests the data. Hopefully the > XPath engine will not request all the data from the tree (if the > request is smart enough and does not contain **, for instance). Generic XPath works only with a DOM(like) structure. How else would you e.g. evaluate an expression like foo[last()]? So if you really need lazy evaluation, you will need to specifically analyze the query of interest and see if it can be coded in a way that allows to forget as much of the tree as possible, or even better not query it. Diez From sniipe at gmail.com Tue Jun 24 06:11:03 2008 From: sniipe at gmail.com (sniipe at gmail.com) Date: Tue, 24 Jun 2008 03:11:03 -0700 (PDT) Subject: Difference between two dates Message-ID: Hi! I am new in Python, so I count for your help. I need to get difference in months between two dates. How to do it in python? I am substracting two dates, for example date1 - date2 and I got result in days, how to change it? Best regards From chris.ortner at googlemail.com Mon Jun 23 04:22:04 2008 From: chris.ortner at googlemail.com (Chris Ortner) Date: Mon, 23 Jun 2008 01:22:04 -0700 (PDT) Subject: Python module for working with a sudden motion sensor on Linux Message-ID: Hi everyone, I am looking for a python module or something similar which makes use of the capabilities of the kernel module applesmc to provide support for the sudden motion sensor in Apple hardware. It should be something like this: http://pypi.python.org/pypi/PyAppleSMS/1.0 Would it make sense to look for a generic accelerometer module or do I have to use something specific? Thanks for your help in advance! Chris From salmoni at gmail.com Mon Jun 16 07:17:40 2008 From: salmoni at gmail.com (Alan J. Salmoni) Date: Mon, 16 Jun 2008 04:17:40 -0700 (PDT) Subject: Notify of change to list References: <8b34cc2b-aa3a-4788-b849-1f926284c7ca@m36g2000hse.googlegroups.com> <90336d65-1537-46a5-92e1-9a8712d56e88@8g2000hse.googlegroups.com> Message-ID: Paul - thank you very much for your help, it was much appreciated. I thought that this was the kind of thing I had to do. I also messed around with properties to try and solve this problem, but noticed a similar thing (ie, that changing a mutable attribute's element is different to rebinding it): when a "propertied" attribute is rebound, the set method is called as expected. However, when setting an element of a mutable like a list, the get method is called and the set is not. This seems to be a bit of a gotcha. I'm sure that calling the get method is justified in the terms of Python internals, but as a user it seems a little counter-intuitive. Without being an expert on language design, my first thought was that changing an element was a "set" operation. Here's a toy: class tobj(object): def __init__(self): self._x = [0,1,2,3,4,5,6] def setx(self, x): print "At setx" self._x = x def getx(self): print "At getx" return self._x d = property(getx, setx) a = tobj() print "setting one element only" a.d[1] = 3 print "rebinding the attribute" a.d = 99 which comes up with: setting one element only At getx rebinding the attribute At setx Does anyone know why it works like this? I would guess that to "set" one element, the attribute needs to be retrieved which means the get method is called. I also guess that only rebinding calls the set method which is why it isn't called here. Alan On Jun 13, 11:19 am, Paul Hankin wrote: > On Jun 13, 12:00 pm, "Alan J.Salmoni" wrote: > > > My question is how can my program be notified of a change to a class > > attribute that is a list? > > You can't. But you can replace lists inside your class with a list > that notifies changes. > > Something like this: > > class NotifyingList(list): > def __setitem__(self, i, v): > print 'setting', i, 'to', v > list.__setitem__(self, i, v) > > [[You'll likely need to redefine __setslice__, __delitem__, > __delslice__, append and extend as well]]. > > >>> x = NotifyingList([1, 2, 3]) > >>> x[1] = 4 > setting 1 to 4 > >>> x > > [1, 4, 3] > > If users of your class are allowed to replace attributes with their > own lists, you'll have to catch these and convert to NotifyingLists; > and it may be somewhat messy. > > I hope this is useful to you. > > -- > Paul Hankin From duncan.booth at invalid.invalid Fri Jun 20 03:38:08 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Jun 2008 07:38:08 GMT Subject: Regular expression References: <42396af0-29aa-45ea-8588-186b0ccbab58@z16g2000prn.googlegroups.com> Message-ID: Sallu wrote: > string = 'rich?' ... > unicode(string)).encode('ASCII', 'ignore') ... > > Output : > > sys:1: DeprecationWarning: Non-ASCII character '\xc3' in file regu.py > on line 4, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details > rich? > Traceback (most recent call last): > File "regu.py", line 13, in ? > msg=strip_accents(string) > File "regu.py", line 10, in strip_accents > return unicodedata.normalize('NFKD', > unicode(string)).encode('ASCII', 'ignore') > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position > 4: ordinal not in range(128) > > The problem is the expression: unicode(string) which is equivalent to saying string.decode('ascii') The string contains a non-ascii character so the decode fails. You should specify whatever encoding you used for the source file. From the error message it looks like you used utf-8, so "string.decode('utf-8')" should give you a unicode string to work with. -- Duncan Booth http://kupuguy.blogspot.com From altricial at gmail.com Mon Jun 30 19:28:49 2008 From: altricial at gmail.com (vumensurvey) Date: Mon, 30 Jun 2008 16:28:49 -0700 (PDT) Subject: Male participants needed for body image research Message-ID: <68357e45-a61e-41b4-9a19-b2b635284992@q27g2000prf.googlegroups.com> Dear all, You are invited to participate in an online research on male body image. (If you are female, please pass this on to your male friends.) An Internet Study: The relationships between men's self-reported physical attributes, body image, self-esteem and internet dating. http://men.questionpro.com/ There has been quite a lot of research conducted on women's body image and we have a reasonable understanding of the types of factors that impact on women's body image and that ultimately lead to disorders like Anorexia and Bulimia Nervosa. However, we know very little about men's body image and the factors that impinge on the way males think about their bodies. Consequently we also know very little about how this impacts on men's health. Do you want to do something about it? If so, you are invited to take part in a research project that will focus exclusively on men's body image. Previous research has highlighted the impact of men's physical attributes on body image and how men perceive their own body. The purpose of this study is to further explore the relationship between physical qualities of men, their body image and self-esteem, using an Internet sample. All men above the age of 18, who have at least basic literacy in English, are invited to participate in this study. If possible, please have a tape measure ready. The questionnaire consists of 62 mostly multiple-choice questions and should take approximately 15 minutes to complete. Your responses will remain anonymous and no identifying information will be collected. You are free to withdraw from this study at any time. If you understand the information stated above and would like to participate in this study, please click on the link below: http://men.questionpro.com/ Thank you in advance for your time and input. Regards, Victoria University From Lie.1296 at gmail.com Wed Jun 11 08:14:35 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 11 Jun 2008 05:14:35 -0700 (PDT) Subject: can't assign to literal References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> <1a244dc4-4d10-491d-8ec7-224f3a1f0df5@m73g2000hsh.googlegroups.com> Message-ID: <12040996-7018-457d-93f8-253f0fbe5ba2@i18g2000prn.googlegroups.com> On Jun 11, 3:32?pm, MRAB wrote: > On Jun 10, 10:57 pm, "Steven Clark" wrote: > > > > for 1 in oids, vals head_oids: > > > SyntaxError: can't assign to literal > > > -- > > > 1 is a literal, you can't assign it to something. Are you trying to > > use it as a variable name? > > Slightly OT, but is there an editor that can display digits in a > different colour to letters? Most programmer oriented editors could, some even have full syntax coloring, they would color keywords (like def, class, etc), literals (1, 'hello', etc), and commonly used built-in function (int, ord, iter, etc). It really helped if you have to read/write lots of codes From bryancchan at gmail.com Thu Jun 19 15:46:47 2008 From: bryancchan at gmail.com (Chanman) Date: Thu, 19 Jun 2008 12:46:47 -0700 (PDT) Subject: [xlwt] Changing Cell Background Color Message-ID: I've posted this on the python-excel group, but perhaps people here know what to do. How does one change the cell background color using the xlwt module? I've looked at several tutorials but none show how to change the background color. I've tried the following: badBG = xlwt.Pattern() badBG.SOLID_PATTERN = 0x34 badBG.NO_PATTERN = 0x34 badBG.pattern_fore_colour = 0x34 badBG.pattern_back_colour = 0x34 badFontStyle = xlwt.XFStyle() badFontStyle.Pattern = badBG sheet1.write(1,1,'hello world', badFontStyle) However, the background cell color still remains white. Any help appreciated. From stephan.diehl at gmx.net Mon Jun 9 11:22:33 2008 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Mon, 09 Jun 2008 17:22:33 +0200 Subject: money data type Message-ID: Hi lazyweb, I'm wondering, if there is a usable money data type for python available. A quick search in pypi and google didn't convey anything, even though the decimal data type seemed to be planned as a money data type originaly. Thanks for any pointers Stephan From gagsl-py2 at yahoo.com.ar Tue Jun 17 02:42:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 17 Jun 2008 03:42:19 -0300 Subject: Buffer size when receiving data through a socket? References: <20080616202135.41c407de.johnjsal@NOSPAMgmail.com> Message-ID: En Mon, 16 Jun 2008 21:21:35 -0300, John Salerno escribi?: > I wrote some pretty basic socket programming again, but I'm still confused about what's happening with the buffer_size variable. Here are the server and client programs: > > -------------- > > from socket import * > > host = '' > port = 51567 > address = (host, port) > buffer_size = 1024 > > server_socket = socket(AF_INET, SOCK_STREAM) > server_socket.bind(address) > server_socket.listen(5) > > while True: > print 'waiting for connection...' > client_socket, client_address = server_socket.accept() > print '...connected from:', client_address > > while True: > data = client_socket.recv(buffer_size) > if not data: > break > client_socket.send('%s %s' % ('You typed:', data)) > > client_socket.close() > > server_socket.close() > > ------------ > > from socket import * > > host = 'localhost' > port = 51567 > address = (host, port) > buffer_size = 1024 > > client_socket = socket(AF_INET, SOCK_STREAM) > client_socket.connect(address) > > while True: > data = raw_input('> ') > if not data: > break > client_socket.send(data) > data = client_socket.recv(buffer_size) > if not data: > break > print data > > client_socket.close() > > --------------- > > I tried changing buffer_size to 10 and I got this output: > > john at john-laptop:~$ python myclient.py >> hello > You typed: >> something > hello >> this is a long string > You typed: >> why doesn't this work right > something >> > john at john-laptop:~$ > > My first question is, isn't buffer_size the number of bytes being sent at one time? If so, why doesn't 'hello' get printed after the server returns the data to the client? Isn't 'hello' just 5 bytes? Both programs say recv(buffer_size) - buffer_size is the maximum number of bytes to be RECEIVED, that is, READ. recv will return at most buffer_size bytes. It may return less than that, even if the other side sent the data in a single operation. Note that most of the time you want to use the sendall() method, because send() doesn't guarantee that all the data was actually sent. > Secondly, how is it working that once I type in a new string (e.g. 'something') and then the server returns data to the client, it prints the *previous* string, (i.e. 'hello')? Wouldn't the data variable get overwritten with the value, or is the value being stored somewhere else at this point? Yes, it is stored in an intermediate buffer until you read it. You typed "hello" and sent it, the server replied with the string "You typed: hello"; the OS stores it. You read only 10 bytes "You typed:", the remaining are still in the buffer. Next round: you type something, the server replies, you read the remaining bytes from the original reply, and so on... (Note that in this particular configuration, the client will fill its buffer at some time: because the server sends at least 11 bytes each round, but the client reads at most 10 bytes, so the client is always behind the server...) -- Gabriel Genellina From john.dohn.john at gmail.com Fri Jun 6 09:16:05 2008 From: john.dohn.john at gmail.com (John Dohn) Date: Sat, 7 Jun 2008 01:16:05 +1200 Subject: Python CGI Upload from Server Status In-Reply-To: <9999810b0806060550w5a7297dbm8ba5cc902cad6f8b@mail.gmail.com> References: <9999810b0806060550w5a7297dbm8ba5cc902cad6f8b@mail.gmail.com> Message-ID: <608040960806060616ja7fbc89ya9c5f92c881b14d@mail.gmail.com> On Sat, Jun 7, 2008 at 12:50 AM, Derek Tracy wrote: > I am trying to create a simple python cgi app that allows the user to kick > off an ftp from the server the cgi is on to another server; I have that > piece working using ftplib but since the files in question are usually very > large (500mb to 2gb) in size I want to be able to display some sort of > status to the user, preferrably a progress bar of some sort. You'll need some AJAX progress bar (hint: google for this term ;-) that will be getting updates from the server or request an update every second or so. The question is if your upload code can provide progress tracking? If it's just a call to some xyz.upload("/here/is/my-500M-file.bin") that only returns after several minutes of uploading without giving you any updates on how fast things go you're probably out of luck. OTOH if it can do e.g.callbacks for progress reporting or if it can run in a separate thread that you could query somehow you can hook that to that AJAX thing of your choice. JDJ -------------- next part -------------- An HTML attachment was scrubbed... URL: From jhenRemoveThis at talk21.com Sun Jun 29 22:52:47 2008 From: jhenRemoveThis at talk21.com (John Henderson) Date: Mon, 30 Jun 2008 12:52:47 +1000 Subject: How to invoke the Python idle References: <08484763-05df-49ee-b308-2dd64b7e2379@e39g2000hsf.googlegroups.com> Message-ID: <6cr040F3ihfodU1@mid.individual.net> Only-Trouble wrote: > Hi all > I am running openSUSE 10.3 > I am learning python on my own, it seems like the system has > already installed a python IDLE > The question is how to invoke it? If it's anything like my Red Hat system, I had to find the command first. In my case, at: /usr/lib/python2.2/site-packages/idle/idle I copied that file to somewhere where it was available on my $PATH variable. John From gagsl-py2 at yahoo.com.ar Thu Jun 19 02:56:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 19 Jun 2008 03:56:01 -0300 Subject: Doc tests in Python References: <7d08373e-7b52-4c6a-a77f-29d3f9fc5672@59g2000hsb.googlegroups.com> Message-ID: En Thu, 19 Jun 2008 02:46:15 -0300, J-Burns escribi?: > Hello. Im new to using doctests in python. Could some1 tel me how to > use doctests if i have a constructor in my code? Just construct the desired objects inside the doctest. See the difflib module for a couple examples. If it's hard/undesirable/annoying to construct the objects for every test, you may use the "globs" or "extraglobs" argument to doctest.testmod. Something like this: class SomeClass: def __init__(self, a, lot, of arguments, are, required): ... def some_method(self, arg): """Does this and that... In the test below, obj refers to the already created instance (below, in _test) >>> obj.some_method(self, 123) True >>> obj.some_method(self, "hi") False """ ... def _test(): import doctest obj = SomeClass(create, the instance, using, a, lot, of, arguments) doctest.testmod(extraglobs={'obj': obj}) if __name__=='__main__': _test() But I prefer to keep the doctests self-contained whenever possible. -- Gabriel Genellina From google at mrabarnett.plus.com Thu Jun 19 09:58:42 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 19 Jun 2008 06:58:42 -0700 (PDT) Subject: Simple Python implementation of bag/multiset Message-ID: <9ddb3f88-f326-4015-906f-3fd242ae2d88@34g2000hsh.googlegroups.com> While another thread is talking about an ordered dict, I thought I'd try a simple implementation of a bag/multiset in Python. Comments/ suggestions welcome, etc. class bag(object): def __add__(self, other): result = self.copy() for item, count in other.iteritems(): result._items[item] = result._items.get(item, 0) + count return result def __and__(self, other): result = bag() for item, count in other.iteritems(): new_count = min(self._items.get(item, 0), count) if new_count > 0: result._items[item] = new_count return result def __contains__(self, item): return item in self._items def __eq__(self, other): return self._items == other._items def __getitem__(self, item): return self._items[item] def __iadd__(self, other): self._items = self.__add__(other)._items return self def __iand__(self, other): self._items = self.__and__(other)._items return self def __init__(self, iterable=None): self._items = {} if iterable is not None: for item in iterable: self._items[item] = self._items.get(item, 0) + 1 def __ior__(self, other): self._items = self.__or__(other)._items return self def __isub__(self, other): self._items = self.__sub__(other)._items return self def __iter__(self): for item, count in self.iteritems(): for counter in xrange(count): yield item def __ixor__(self, other): self._items = self.__xor__(other)._items return self def __len__(self): return sum(self._items.itervalues()) def __ne__(self, other): return self._items != other._items def __or__(self, other): result = self.copy() for item, count in other.iteritems(): result._items[item] = max(result._items.get(item, 0), count) return result def __repr__(self): result = [] for item, count in self.iteritems(): result += [repr(item)] * count return 'bag([%s])' % ', '.join(result) def __setitem__(self, item, count): if not isinstance(count, int) or count < 0: raise ValueError if count > 0: self._items[item] = count elif item in self._items: del self._items[item] def __sub__(self, other): result = bag() for item, count in self.iteritems(): new_count = count - other._items.get(item, 0) if new_count > 0: result._items[item] = new_count return result def __xor__(self, other): result = self.copy() for item, count in other.iteritems(): new_count = abs(result._items.get(item, 0) - count) if new_count > 0: result._items[item] = new_count elif item in result._item: del result._items[item] return result def add(self, item): self._items[item] = self._items.get(item, 0) + 1 def discard(self, item): new_count = self._items.get(item, 0) - 1 if new_count > 0: self._items[item] = new_count elif new_count == 0: del self._items[item] def clear(self): self._items = {} def copy(self): result = bag() result._items = self._items.copy() return result def difference(self, other): return self.__sub__(other) def difference_update(self, other): self._items = self.__sub__(other)._items def get(self, item, default=0): return self._items.get(item, default) def intersection(self, other): return self.__and__(other) def intersection_update(self, other): self.__iand__(other) def items(self): return self._items.items() def iteritems(self): return self._items.iteritems() def iterkeys(self): return self._items.iterkeys() def itervalues(self): return self._items.itervalues() def keys(self): return self._items.keys() def pop(self): item = self._items.keys()[0] self._items[item] -= 1 if self._items[item] == 0: del self._items[item] return item def remove(self, item): new_count = self._items[item] - 1 if new_count > 0: self._items[item] = new_count else: del self._items[item] def symmetric_difference(self, other): return self.__xor__(other) def symmetric_difference_update(self, other): self.__ixor__(other) def union(self, other): return self.__or__(other) def update(self, other): self.__ior__(other) def values(self): return self._items.values() From deets at nospam.web.de Mon Jun 9 11:35:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 09 Jun 2008 17:35:52 +0200 Subject: How to find the first space? References: <7a91cc8f-2e93-46e9-8360-a01da9170187@m44g2000hsc.googlegroups.com> Message-ID: <6b5100F3a49r4U2@mid.uni-berlin.de> Russell Blau wrote: > "Johny" wrote in message > news:7a91cc8f-2e93-46e9-8360-a01da9170187 at m44g2000hsc.googlegroups.com... >> How can I find the first space using regex? >> >> For example I have text >> Text=' This is a sample ' > > Why do you need to use a regex? > > text = text.replace(" ", "") You are aware that this is producing nonsense given the OP's requirements? >>> print Text.replace(" ", "") Thisisasample Instead, the OP wants >>> print Text.strip() This is a sample Diez From alexnbryan at gmail.com Wed Jun 11 17:04:37 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 11 Jun 2008 14:04:37 -0700 (PDT) Subject: problems with opening files due to file's path In-Reply-To: <__W3k.6394$ZE5.2948@nlpi061.nbdc.sbc.com> References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> <77acc29a-fffa-44d6-b07b-6bcf8b5bdd74@h1g2000prh.googlegroups.com> <__W3k.6394$ZE5.2948@nlpi061.nbdc.sbc.com> Message-ID: <17787228.post@talk.nabble.com> Haha, okay well sorry that I was being so stupid, but I get it now and I apoligize for causing you all the frustration. But I did get it to work finally. Carsten Haese-2 wrote: > > Alexnb wrote: >> I don't get why yall are being so rude about this. > > We're frustrated with your apparent inability to understand anything > we're saying. > >> My problem is this; the >> path, as a variable conflicts with other characters in the path, creating >> escape characters I don't want, so I need a way to send the string to the >> os.startfile() in raw, or, with all the backslashes doubled. > > No, no, no, no, NO! That is not your problem! You are drawing unfounded > conclusions from the fact that you had to double up backslashes when the > filename came from a string literal. The situation is entirely different > when the filename comes from user input. No doubling up of backslashes > is necessary when the filename comes from user input. TRUST ME! > > For simplicity, start with this code to convince yourself: > > import os > filename = raw_input("Please enter a filename: ") > os.startfile(filename) > > Once you get that to work, replace raw_input with a function that gets > the filename from your GUI. > > Hope this helps, > > -- > Carsten Haese > http://informixdb.sourceforge.net > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17787228.html Sent from the Python - python-list mailing list archive at Nabble.com. From lists at cheimes.de Sun Jun 15 10:05:22 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 15 Jun 2008 16:05:22 +0200 Subject: 32 bit or 64 bit? In-Reply-To: References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> Message-ID: ram.rachum at gmail.com wrote: > Does it mean that even now it does arithmetic in 64 bit? > I'm not getting enough precision. Is there any way to increase it? Buy a good book about numerics or take a course. ;) Seriously, computers and IEEE 754 floating point numbers have a lot of pit falls. If you chose the wrong algorithm you *will* get wrong results. With floats a*b*c and a*c*b can give you a different result. The decimal module is not an option if you need speed. From gagsl-py2 at yahoo.com.ar Tue Jun 17 03:46:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 17 Jun 2008 04:46:38 -0300 Subject: print problem References: <2MWdnYXqCY3yy8rVnZ2dnUVZ_sbinZ2d@posted.internode> <48576371.7000209@gmail.com> Message-ID: En Tue, 17 Jun 2008 04:10:41 -0300, Rich Healey escribi?: > Gabriel Genellina wrote: >> En Tue, 17 Jun 2008 03:15:11 -0300, pirata escribi?: >> >>> I was trying to print a dot on console every second to indicates >>> running process, so I wrote, for example: >>> >>> for i in xrange(10): >>> print ".", >>> time.sleep(1) >>> >>> Idealy, a dot will be printed out each second. But there is nothing >>> print out until after 10 seconds, all 10 dots come out together. >>> >>> I've tried lose the comma in the print statement, and it works. >>> >>> Is that because of the print statement buffer the characters until >>> there is a new line character? >> >> Very probably, altough I can't reproduce it on Windows. Try invoking the script with python -u (unbuffered input/output): >> >> python -u your_script.py >> > Or just write to sys.stdout without the print wrapper.. I think the output is still buffered, even if you write directly to sys.stdout, but I don't have a Linux box to test right now. -- Gabriel Genellina From nick at craig-wood.com Thu Jun 12 15:31:05 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 12 Jun 2008 14:31:05 -0500 Subject: get keys with the same values References: <3fdafa74-2043-4052-bdec-843f69d9e5fa@e39g2000hsf.googlegroups.com> Message-ID: Paul McGuire wrote: > Instead of all that try/except noise, just use the new defaultdict: > > >>> from collections import defaultdict > >>> > >>> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} > >>> > >>> dd = defaultdict(list) > >>> for key, value in d.items(): > ... dd[value].append(key) > ... > >>> for k,v in dd.items(): > ... print k,':',v > ... > 1 : ['a', 'e'] > 2 : ['c'] > 3 : ['b', 'd'] > 4 : ['f'] > Or use the little understood dict.setdefault method which has been with us from time immemorial... >>> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} >>> dd = {} >>> for k, v in d.items(): ... dd.setdefault(v, []).append(k) ... >>> dd {1: ['a', 'e'], 2: ['c'], 3: ['b', 'd'], 4: ['f']} >>> -- Nick Craig-Wood -- http://www.craig-wood.com/nick From nospam at nospam.com Sun Jun 1 09:17:44 2008 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 01 Jun 2008 15:17:44 +0200 Subject: [Business apps for Windows] Good grid + calendar, etc.? References: Message-ID: <888544pf6jfdb2bj537dpqpfa7vn5n7u98@4ax.com> On Sun, 1 Jun 2008 21:59:29 +0900, "Ryan Ginstrom" wrote: >wxPython can be made to look pretty nice. Check out Chandler for an example. >http://chandlerproject.org/ Yup, they developped some nice-looking widgets, but it doesn't seem like there's an ecosystem around wxWidgets. I, for one, wouldn't mind paying for widgets missing from the stock version. >If you don't mind being Windows-only, there's another approach that I've >been working on. Thanks for the idea, but I don't have the skills for something like that :-) Besides, the reason for Python is to make it faster/easier to write apps, so WTL + browser + COM seems too hard for me. From bruno.desthuilliers at gmail.com Mon Jun 30 16:53:32 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 30 Jun 2008 13:53:32 -0700 (PDT) Subject: list extension ? References: <4868b0ba$0$17063$426a34cc@news.free.fr> Message-ID: On 30 juin, 21:05, Stef Mientki wrote: > thanks guys, > > >> def __init__ ( self, value = [] ) : > > > Gotcha : default argument values are eval'd only once. Also, it would > > make more sense IMHO to follow the parent's class initializer's > > behaviour: Ah hem.... Sorry, should have double-checked: > > def __init__(self, *args) > > >> list.__init__ ( self, value ) > > > list.__init__(self, *args) > > that's even better, except the call must be > list.__init__ ( self, args ) Indeed. Which makes my whole comment about "following parent's class behaviour" totally off-tracks. Should have shut up here :( From hancock.robert at gmail.com Mon Jun 16 13:59:30 2008 From: hancock.robert at gmail.com (milan_sanremo) Date: Mon, 16 Jun 2008 10:59:30 -0700 (PDT) Subject: sqlite3 and Python 2.5.1 Message-ID: <612ed26a-c6cf-4133-af6c-f256484e3928@x41g2000hsb.googlegroups.com> I have sqlite installed, but when I try to import sqlite3 I receive: Python 2.5.1 (r251:54863, Nov 3 2007, 02:54:36) [C] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 Traceback (most recent call last): File "", line 1, in ImportError: No module named sqlite3 >>> Yet: # find /usr/local/python -name "sqlite*" -print /usr/local/python/lib/python2.5/sqlite3 # /opt/csw/bin/sqlite3 SQLite version 3.2.2 Enter ".help" for instructions sqlite> What is missing? From stdenton at sbcglobal.net Sat Jun 7 17:38:19 2008 From: stdenton at sbcglobal.net (Sam Denton) Date: Sat, 07 Jun 2008 16:38:19 -0500 Subject: simple question on list manipulation from a newbie In-Reply-To: <76ccc0a8-90de-4717-9e6f-06836827b1e1@i18g2000prn.googlegroups.com> References: <76ccc0a8-90de-4717-9e6f-06836827b1e1@i18g2000prn.googlegroups.com> Message-ID: <6hD2k.4836$co7.3109@nlpi066.nbdc.sbc.com> Sengly wrote: > Dear all, > > I am working with wordnet and I am a python newbie. I'd like to know > how can I transfer a list below > > In [69]: dog > Out[69]: > [{noun: dog, domestic_dog, Canis_familiaris}, > {noun: frump, dog}, > {noun: dog}, > {noun: cad, bounder, blackguard, dog, hound, heel}, > {noun: frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, > weenie}, > {noun: pawl, detent, click, dog}, > {noun: andiron, firedog, dog, dog-iron}] > > to a list like this with python: > > [dog, domestic_dog, Canis_familiaris, > frump, dog, > dog, > cad, bounder, blackguard, dog, hound, heel, > frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, > weenie}, > pawl, detent, click, dog}, > andiron, firedog, dog, dog-iron] I can't help you with the formatting, but here's a solution using Python data structures: >>> alist = [ {'noun': ('dog', 'domestic_dog', 'Canis_familiaris')}, {'noun': ('frump', 'dog')}, {'noun': ('dog',)}, {'noun': ('cad', 'bounder', 'blackguard', 'dog', 'hound', 'heel')}, {'noun': ('frank', 'frankfurter', 'hotdog', 'hot_dog', 'dog', 'wiener', 'wienerwurst', 'weenie')}, {'noun': ('pawl', 'detent', 'click', 'dog')}, {'noun': ('andiron', 'firedog', 'dog', 'dog-iron')}, ] >>> merged = {} >>> for d in alist: for key, value in d.iteritems(): merged.setdefault(key, []).extend(value) >>> merged {'noun': ['dog', 'domestic_dog', 'Canis_familiaris', 'frump', 'dog', 'dog', 'cad', 'bounder', 'blackguard', 'dog', 'hound', 'heel', 'frank', 'frankfurter', 'hotdog', 'hot_dog', 'dog', 'wiener', 'wienerwurst', 'weenie', 'pawl', 'detent', 'click', 'dog', 'andiron', 'firedog', 'dog', 'dog-iron']} From exarkun at divmod.com Mon Jun 16 13:09:16 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 16 Jun 2008 13:09:16 -0400 Subject: String Concatenation O(n^2) (was: Re: Explaining Implementing a Binary Search Tree.) In-Reply-To: <3fc761710806160941q3c1a93b5p7761fbe148718585@mail.gmail.com> Message-ID: <20080616170916.4714.1881297769.divmod.quotient.9773@ohm> On Mon, 16 Jun 2008 10:41:05 -0600, Ian Kelly wrote: >On Mon, Jun 16, 2008 at 4:34 AM, Bart Kastermans wrote: >> This is interesting. I had never attempted to verify a big O >> statement >> before, and decided that it would be worth trying. So I wrote some >> code to >> collect data, and I can't find that it goes quadratic. I have the >> graph >> at >> >> http://kasterma.wordpress.com/2008/06/16/complexity-of-string-concatenation/ >> >> It looks piecewise linear to me. > >I don't think there's any question that it's quadratic. Just look at >the C code, and you'll see that every time you concatenate the entire >string has to be copied. It will depend what version of Python you're using and the *exact* details of the code in question. An optimization was introduced where, if the string being concatenated to is not referred to anywhere else, it will be re-sized in place. This means you'll probably see sub-quadratic behavior, but only with a version of Python where this optimization exists and only if the code can manage to trigger it. Jean-Paul From casey.mcginty at gmail.com Fri Jun 6 16:43:15 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Fri, 6 Jun 2008 10:43:15 -1000 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: References: <484808F7.5040203@arimaz.com> Message-ID: On Thu, Jun 5, 2008 at 11:39 AM, Terry Reedy wrote: > > If you want to access the attribute of a particular class, to read or > write, use that class. > SomeClass.attr > Note that no instance is required or relevant. > > If you want to read the attrubute of the class of an instance (or the first > superclass with the attribute, whatever that class might be, use self.attr > or self.__class__.attr. (Use the latter if the instance has (or might > have) an attribute of the same name). > > For setting an attribute, self.attr = x sets it on the instance while > self.__class__.attr = x sets it on its class. > > So the key here is that obj.__class__.attr will only access the immediate child class name space, but SuperClass.attr will guarantee your are access the first super class namespace? If that is true, then the bug makes sense. -------------- next part -------------- An HTML attachment was scrubbed... URL: From remy.blank at pobox.com Wed Jun 4 16:23:06 2008 From: remy.blank at pobox.com (Remy Blank) Date: Wed, 04 Jun 2008 22:23:06 +0200 Subject: Exit from os.chroot() In-Reply-To: References: Message-ID: Thomas Bellman wrote: > That might not be the best idea... Suddenly the chroot:ed > program has access to the real /usr/bin; and since it likely is > running as root (it was allowed to call chroot()), it can do bad > things to the things in /usr/bin. If a chrooted process is running as root, it can very easily break out of the chroot anyway. So... > Also remember, a chroot:ing process should permanently relinquish > its privileges as soon as possible after chroot:ing. There are > way too many fun things a root-running process can do even when > chroot:ed, like creating device files or setuid binaries. ...this is imperative. > All this is of course assuming that the chroot is done for > security reasons. But here's something that might be interesting: http://kerneltrap.org/Linux/Abusing_chroot Short story: chroot is not and never has been a security tool. -- Remy From mccredie at gmail.com Mon Jun 30 18:49:34 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 30 Jun 2008 15:49:34 -0700 (PDT) Subject: raw_input into Tkinter ? References: <634e2b50-45ba-4b93-89b4-0afd739adaf3@z66g2000hsc.googlegroups.com> Message-ID: <9571b5b0-7b18-4045-a912-6635a6e86500@l42g2000hsc.googlegroups.com> On Jun 30, 9:55?am, jamitwi... at gmail.com wrote: > Is there any way to type into a Tkinter frame window? > I want to use raw_input() within a Tkinter frame. `raw_input(prompt)` just calls `sys.stdout.write(prompt)` and returns `sys.stdin.readline()`. So, you can just create file-like objects to replace stdout and stdin that are aware of your Tkinter gui. Alternatively, you could just replace __builtins__.raw_input with your own version. Actual implementation left as an exercise for the user. Matt From bmilliron at gmail.com Wed Jun 11 15:34:36 2008 From: bmilliron at gmail.com (Ben) Date: Wed, 11 Jun 2008 12:34:36 -0700 (PDT) Subject: *** Massive Copyright Violation by the US Government *** References: <06c58239-b892-4e16-b4dc-5a2d9f528946@j22g2000hsf.googlegroups.com> Message-ID: On Jun 11, 3:06 pm, lemnit... at india.com wrote: > Printing dollar is a copyright violation > ---------------------------------------------------- > > I recently heard that the USA government or the unfederal reserve is > printing dollars. Is this a copyright violation ? > > Is this also a theft ? > > Is there a scheme to print dollars in such a way to selectively > deflate the dollars owned by non-US entities while unaffecting the > wealth or wealth ratio of the native population ? Is there a scheme to > give people the difference by this method ? Are there any grants or > subsidies to implement this scheme/scam ? > > Lyman L. Lemnitzer > Master schemer of Operation Northwoods > > please look at my favorite websites:http://iamthewitness.com > > Also look at > Painful Deceptions by Alex Jones and Eric Hufschmidt. > > Do you know if war on terror was genuine, the anthrax mailer would > have been caught first ? This group is to answer questions about the Python programming language. Please respect that and start your own group for political theory/speculation. From jeffnyman at gmail.com Thu Jun 5 08:58:47 2008 From: jeffnyman at gmail.com (Jeff Nyman) Date: Thu, 5 Jun 2008 05:58:47 -0700 (PDT) Subject: Creating A Tuple From A List, Adding To Tuple As You Do References: Message-ID: <84ce4c88-ff69-413e-961f-ffbb17ed5a95@t54g2000hsg.googlegroups.com> Thanks to everyone who responded! Yes, those solutions all work and do what I need. I'm also getting much more familiar with how flexible Python is in terms of its language. I think that's been the hardest challenge for me. I'm usually finding I try to "overdo it" when coming up with solutions. Once again, many thanks. - Jeff From gnewsg at gmail.com Fri Jun 13 14:36:07 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Fri, 13 Jun 2008 11:36:07 -0700 (PDT) Subject: best way to create a timer References: Message-ID: On 13 Giu, 07:42, Alexnb wrote: > I am wondering what is the best way to create a timer, like an alarm, once it > reaches a time, it triggers an event. I have a way of doing this but it > seems like it isn't good at all. If it helps at all I am using a Tkinter, > but that probably doesn't mean much. The way I was doing it was using a > while loop, and just saying while current time is not = to trigger time, do > nothing, and when it is, do event. > -- > View this message in context:http://www.nabble.com/best-way-to-create-a-timer-tp17815502p17815502.... > Sent from the Python - python-list mailing list archive at Nabble.com. I think that threading.Timer could be what you're searching for. --- Giampaolo http://code.google.com/p/pyftpdlib/ From reckoner at gmail.com Mon Jun 9 21:57:22 2008 From: reckoner at gmail.com (Reckoner) Date: Mon, 9 Jun 2008 18:57:22 -0700 (PDT) Subject: access variables from one Python session to another on the same machine? References: <6ea6b084-3897-43f9-b8e0-dff52b47f1a0@w1g2000prd.googlegroups.com> Message-ID: On Jun 9, 5:23 pm, "Daniel Fetchinson" wrote: > > Suppose I have two different command windows going on the same > > machine, each running their own Python interpreters. > > > Is it possible to access the variables in one of the interpreter- > > sessions from the other? > > > It turns out I have limited control over one of the sessions (i.e. > > cannot control all the code that is run from there), but complete > > control over the other. > > > I get the feeling this has been asked before, but I'm not sure how to > > pose the question in such a way that it would show up on a search. > > It's confusing. > > Depending on what 'limited control' means, the simplest choice would > be writing stuff to a plain text file from the master and reading it > from the slave. This may or may not work depending on your environment > though. > > Cheers, > Daniel > -- > Psss, psss, put it down! -http://www.cafepress.com/putitdown This disk-writing approach seems to be simplest & less intrusive. Thanks! I'll try it. From fetchinson at googlemail.com Sat Jun 21 21:17:01 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 21 Jun 2008 18:17:01 -0700 Subject: Connecting a Desktop App to a Web App In-Reply-To: References: Message-ID: > Okay, this is my first post to this mailing list, so first off if I > shouldn't be sending something here, PLEASE correct me. Okay, so I > want to create an app that has a GUI (most likely Tkinter) and will > prompt the user to choose files and such and then will upload those > files, either regularly or one time, whatever. But I don't know how to > go abou doing such a thing, that is creating a app that will > automatically upload to a back-up website(online storage). So if > anyone can help me out or point me in the right direction that would > be great. Thanks! There are two cases: (1) you are in control of the web app (2) you are not in control of the web app. (1) So you need to make the web app yourself too. There are several options for this the most popular ones are django and turbogears. For more see http://wiki.python.org/moin/WebFrameworks Once you have your web app up and running you can connect to it using some modules in the stdlib: http://docs.python.org/lib/module-urllib2.html http://docs.python.org/lib/module-httplib.html Basically you just create http requests in your desktop app and send those just as a browser would do. (2) You need to figure out the API of the web app you want to connect to. Once you have that use the stdlib modules to create the appropriate http requests just as above. HTH, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From karsten.heymann at blue-cable.net Fri Jun 13 11:55:44 2008 From: karsten.heymann at blue-cable.net (Karsten Heymann) Date: Fri, 13 Jun 2008 17:55:44 +0200 Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <878wx9leiv.fsf@ara.blue-cable.net> Message-ID: <873anhtjlr.fsf@ara.blue-cable.net> Hi Maric, Maric Michaud writes: > So, writing C in python, which has dictionnary as builtin type, > should be considered "more elegant" ? IMO that's a bit harsh. > You are comparing apples with lemons, there is no such a difference > between list index access and dictionnary key access in Python. [...] > If you know in advance the number and names of users, what prevent > you to initialize completelly the target dictionnary ? > > The following code compare the same algorithm, once with list and > the second time with dict : [...] > The result is pretty close now : > > maric at redflag1 17:04:36:~$ ./test.py > with list 1.40726399422 > with dict 1.63094091415 > > So why use list where the obvious and natural data structure is a > dictionnary ? I'd never argue that using a dictionary is the obvious and natural data structure for this case. But is it the best? Honestly, as your very nice example shows, we have two solutions that are equally fast, equally complex to code and equally robust, but one needs approximately the double amount of memory compared to the other. So, as much as i like dictionaries, what's the gain you get from using it in this corner case? Yours, Karsten From basti.wiesner at gmx.net Mon Jun 9 14:05:50 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Mon, 09 Jun 2008 20:05:50 +0200 Subject: Separators inside a var name References: Message-ID: Rainy at Montag 09 Juni 2008 19:29: > I have a stylistic question. In most languages words in var. name are > separated by underscores or cap letters, resulting in var names like > var_name, VarName and varName. I don't like that very much because all > 3 ways of naming look bad and/or hard to type. Then you better get used to such names, as they are common for many widely spread languages including C, C++, C#, Java, Python, Ruby, Perl and many more ;) You may like these or dislike these names, but you won't come around them ;) > From what I understand, scheme can have variables like var-name. I'm > curious about reasons that python chose to disallow this. "-" is an operator in Python. How should the parser know, whether "var-name" means "the object bound to var_dash_name" or "subtract the object bound to name from the object bound to var"? Scheme can allows such names, because its a functional programming language. Subtracting in this language is not done through operators, but through functions. Therefore there is a clear difference between referencing a name or subtracting two ones: var-name vs (- var name). > Another question I have is what other languages allow this naming scheme? Other lisp dialects do, due to the same reasons as scheme. > Were there any languages that allowed space as a separator? None that I know of. Probably one could use unicode characters, that look like a space in languages, which allow unicode characters in identifiers (as Java or C#, iirc), but I doubt this. Anyway, even if allowed, this would be silly, since it obscures code to the eyes of the reader. > What would be a practical way to separate variables from keywords in that > case? "some long variable name", 'just a string', or maybe using 2 spaces: > one var + other var + third var ? I can't image a practical way to allow a space as character in names, while still maintaining it syntactic element for separation of names. Quotes are normally used for string or characters literals and a double space is hard to distinguish from a single space, and things like ${a name with spaces} is a lot nastier than names with underscores (which aren't bad at all, imho). > I think being able to easy have very long names for vars that are easy to > type would be a fairly significant advantage. Names shouldn't be long, they should be expressive. If you can't give an object a _short_, but _expressive_ name, your object is too complicated ;) Btw, I don't really understand your refusal of underscores. In my opinion such names are harder to read than underscores, which look more like a real space, because the leave a space in the middle of a line, that you look at. If they are too hard for you to type, whats the point in swapping the dash and the underscore in your keyboard layout? -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From sjmachin at lexicon.net Mon Jun 2 20:48:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 2 Jun 2008 17:48:28 -0700 (PDT) Subject: Importing xlrd References: Message-ID: On Jun 3, 8:23 am, Chanman wrote: > This is probably a simple question to most of you, but here goes. > I've downloaded the xlrd (version 0.6.1) module and placed in in the > site-packages folder. Now, when I write a script, I type: > > import sys > import xlrd > > When I run it, there is an import error saying there is no module > named xlrd. However when I type sys.path, the site-packages folder is > definitely in the path. Do I somehow need to run the xlrd setup.py > first before importing? > > Any help would be appreciated. >From the xlrd home-page (http://www.lexicon.net/sjmachin/xlrd.htm): """ Installation: * Windows only: download and run this installer xlrd-0.6.1.win32.exe. Any platform: download this ZIP file xlrd-0.6.1.zip which you unzip into a suitable directory, then cd to that directory, and do "python setup.py install". """ >From the xlrd README file: """ Installation: * On Windows: use the installer. * Any OS: Unzip the .zip file into a suitable directory, chdir to that directory, then do "python setup.py install". * If PYDIR is your Python installation directory: the main files are in PYDIR/Lib/site-packages/xlrd (except for Python 2.1 where they will be in PYDIR/xlrd), the docs are in the doc subdirectory, and there's a sample script: PYDIR/Scripts/runxlrd.py * If os.sep != "/": make the appropriate adjustments. """ From maxm at mxm.dk Wed Jun 4 15:46:01 2008 From: maxm at mxm.dk (Max M) Date: Wed, 04 Jun 2008 21:46:01 +0200 Subject: ANN: Sydebar 1.0 - A browser sidebar generator for Python documentation In-Reply-To: <4846D09B.3090502@pobox.com> References: <4846D09B.3090502@pobox.com> Message-ID: Remy Blank skrev: > (I apologize for the poorly formatted message. Something between my news > client and the server decided, besides delaying the message for over 17 > hours, to add an empty line for every line of text, which obviously > messed up some headers. Here's the content again, and hopefully this > message comes through unaltered.) > > > I am pleased to announce the first release of Sydebar, a browser sidebar > generator for Python documentation. For the impatient, sample outputs > for all Python versions ever released can be found here: > > http://c-space.org/download/Sydebar/samples/ This looks great. I have been missing my chm based docs since moving to Python. This goes a long way. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From nicodotti2 at gmail.com Wed Jun 25 18:59:35 2008 From: nicodotti2 at gmail.com (nicodotti2) Date: Wed, 25 Jun 2008 15:59:35 -0700 (PDT) Subject: Communication between Python and PHP References: Message-ID: <8cd5f9db-46bc-491a-a58a-4ccc7086fa72@z16g2000prn.googlegroups.com> On Jun 25, 1:50 pm, Larry Bates wrote: > nicodotti2 wrote: > > Don't ask me why, but we have a bunch of legacy code in PHP on a > > server and a wee-bit of Python code for integrating GData google > > calendar services. We now need to build a way of sending messages > > between them. The general flow is: > > > PHP Web Page(on apache) ---> Python Gdata Consumer -----> Gdata > > and then json is returned back like: > > PHP Web Page<----json data---- Pthon Gdata Consumer > > > So I tried to convince my boss to let me use the python c extension to > > write a native bridge but 'no dice'. He also does not want anything > > 'experimental' so pyphp is out. He'd like me to basically have them > > communicate by passing the json via http/apache - so in essence, I'll > > have to make (what I feel) are very expensive calls between two > > objects that, in a perfect world, would be on the same machine in the > > same language! I see this as a potential bottleneck. Any suggestions? > > I have to start prototyping this today so the sooner the better, um, > > please ;) Thanks gurus out there. > > Use sockets. They are efficient and both languages have good implementations. > > -Larry Thanks Larry I'll look into going that route. From fernandes.fd at gmail.com Tue Jun 3 09:43:34 2008 From: fernandes.fd at gmail.com (Filipe Fernandes) Date: Tue, 3 Jun 2008 09:43:34 -0400 Subject: parser recommendation Message-ID: <11397a330806030643w3ff0ddd0v4ed74f57d49088a7@mail.gmail.com> I have a project that uses a proprietary format and I've been using regex to extract information from it. I haven't hit any roadblocks yet, but I'd like to use a parsing library rather than maintain my own code base of complicated regex's. I've been intrigued by the parsers available in python, which may add some much needed flexibility. I've briefly looked at PLY and pyparsing. There are several others, but too many to enumerate. My understanding is that PLY (although more difficult to use) has much more flexibility than pyparsing. I'm basically looking to make an informed choice. Not just for this project, but for the long haul. I'm not afraid of using a difficult (to use or learn) parser either if it buys me something like portability (with other languages) or flexibility). I've been to a few websites that enumerate the parsers, but not all that very helpful when it came to comparisons... http://nedbatchelder.com/text/python-parsers.html http://www.python.org/community/sigs/retired/parser-sig/towards-standard/ I'm not looking to start a flame war... I'd just like some honest opinions.. ;) thanks, filipe From mensanator at aol.com Sun Jun 8 12:04:10 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 8 Jun 2008 09:04:10 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net><484ad07b$0$25721$607ed4bc@cv.net> <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> Message-ID: On Jun 8, 3:19?am, "Terry Reedy" wrote: > "Mensanator" wrote in message > > news:8d7c0912-422f-4480-a034-078f9dbcae24 at 2g2000hsn.googlegroups.com... > | On Jun 7, 6:43?pm, "Terry Reedy" wrote: > | > zip(range(9,2000000000), iterable) > | > | Oh, dear. You didn't actually try this, did you? > > Works fine in Py3, which is what I use now. You really ARE cruel to the newbies, aren't you? Don't you think it would have been appropriate to attach a large red label: WARNING! PY3! From fc14301589 at icqmail.com Thu Jun 12 02:03:37 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Thu, 12 Jun 2008 14:03:37 +0800 Subject: can't assign to literal References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> <1a244dc4-4d10-491d-8ec7-224f3a1f0df5@m73g2000hsh.googlegroups.com> <484feda6_2@news.tm.net.my> Message-ID: <4850bc42_1@news.tm.net.my> On 01:37, gioved? 12 giugno 2008 Ethan Furman wrote: > Do you mean indenting, or wrapping? I mean fill the line by increasing spaces between words in order to get a paragraph aligned both side, left and right on the page. So if the width is 78 chars it wouldn't have jig saw end to the right side, unless applying some word hyphenation. This feature would be nice for writing here and some plain documentation plain text. Beside that it might doing for Python scripts as well. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From __peter__ at web.de Tue Jun 17 07:02:53 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 17 Jun 2008 13:02:53 +0200 Subject: 'string'.strip(chars)-like function that removes from the middle? References: <48569B9E.6030206@admailinc.com> <200806161839.13647.omer@no-log.org> Message-ID: Sion Arrowsmith wrote: > In article , > Peter Otten <__peter__ at web.de> wrote: >>Terry Reedy wrote: >>> >>> 'abcde'.translate(str.maketrans('','','bcd')) >>> 'ae' >>You should mention that you are using Python 3.0 ;) >>The 2.5 equivalent would be >> >>>>> u"abcde".translate(dict.fromkeys(map(ord, u"bcd"))) >>u'ae' > > Only if you're using Unicode: ... which is what you do if you are using the str type in 3.0. Peter From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 9 04:59:53 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 09 Jun 2008 10:59:53 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> Message-ID: <484cf0bb$0$4973$426a34cc@news.free.fr> Russ P. a ?crit : > On Jun 8, 5:40 am, Mark Wooding wrote: >> Russ P. wrote: >>> The idea of being able to discern properties of an object by its name >>> alone is something that is not normally done in programming in >>> general. >> Really? You obviously haven't noticed Prolog, Smalltalk, Haskell, ML, >> or Erlang then. And that's just the ones I can think of off the top of >> my head. >> >> * Prolog and Erlang distinguish atoms from variables by the case of >> the first letter; also `_' is magical and is equivalent to a new >> variable name every time you use it. >> >> * Smalltalk distinguishes between global and local variables according >> to the case of the first letter. >> >> * Haskell distinguishes between normal functions and constructors >> (both data constructors and type constructors) by the case of the >> first letter, and has Prolog's `_' convention. >> >> * ML allows a single-quote in variable names, but reserves names >> beginning with a single-quote for type variables. It also has >> Prolog's `_' convention. >> >> As far as I can see, discerning properties of a thing from its name >> seems relatively common. > > Well, "common" in Prolog, Smalltalk, Haskell, ML, and Erlang is hardly > common in general. I'll bet that Java and C/C++ are used more in North > Dakota than all those languages combined are used in the entire world. And you'll very probably loose. > That's not to say they aren't interesting academic languages, of > course. Erlang an "academic" language ? Man, you're either a troll or totally clueless. From alexnbryan at gmail.com Fri Jun 13 14:13:40 2008 From: alexnbryan at gmail.com (Alexnb) Date: Fri, 13 Jun 2008 11:13:40 -0700 (PDT) Subject: os.startfile() on a mac Message-ID: <17829335.post@talk.nabble.com> So i have a mac and pc, and just found out that os.startfile() doesn't work on a mac. So is there anything like that besides os.system()? -- View this message in context: http://www.nabble.com/os.startfile%28%29-on-a-mac-tp17829335p17829335.html Sent from the Python - python-list mailing list archive at Nabble.com. From hniksic at xemacs.org Thu Jun 12 08:50:40 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 12 Jun 2008 14:50:40 +0200 Subject: ClassName.attribute vs self.__class__.attribute References: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> <4850e95d$0$10444$426a74cc@news.free.fr> Message-ID: <8763sees0v.fsf@mulj.homelinux.net> Duncan Booth writes: > In fact, thinking about it a bit more, I think that if you did have > another metaclass which is its own metaclass then the class cannot > subclass 'object'. You could if the metaclass of your metaclass inherited from 'type'. Then your types could still be binary-compatible with Python types, and your objects with 'object'. It's difficult to envision what you'd gain with a custom meta-meta-class, but it seems possible: >>> class MetaMeta(type): pass ... >>> class Meta(type): ... __metaclass__ = MetaMeta ... >>> class Foo(object): ... __metaclass__ = Meta ... >>> f = Foo() >>> f <__main__.Foo object at 0xb7d27bec> >>> type(f) >>> type(type(f)) >>> type(type(type(f))) >>> isinstance(f, object) True From mensanator at aol.com Sun Jun 15 14:41:53 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 15 Jun 2008 11:41:53 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> Message-ID: <1f658382-1f45-41c2-a884-5478fef394bf@j22g2000hsf.googlegroups.com> On Jun 15, 12:10?pm, "ram.rac... at gmail.com" wrote: > On Jun 15, 7:43?pm, Peter Otten <__pete... at web.de> wrote: > > > ram.rac... at gmail.com wrote: > > > On Jun 15, 6:58?pm, Christian Meesters wrote: > > >> > I do need speed. Is there an option? > > > >> Mind telling us what you *actually* want to achieve? (What do you want to > > >> calculate?) > > > >> Christian > > > > Physical simulations of objects with near-lightspeed velocity. > > > How did you determine that standard python floats are not good enough? > > I have a physical system set up in which a body is supposed to > accelerate and to get very close to lightspeed, while never really > attaining it. After approx. 680 seconds, Python gets stuck and tells > me the object has passed lightspeed. I put the same equations in > Mathematica, again I get the same mistake around 680 seconds. So I > think, I have a problem with my model! Then I pump up the > WorkingPrecision in Mathematica to about 10. I run the same equations > again, and it works! At least for the first 10,000 seconds, the object > does not pass lightspeed. > I concluded that I need Python to work at a higher precision. > > > Everything beyond that is unlikely to be supported by the hardware and will > > therefore introduce a speed penalty. > > I have thought of that as well. However I have no choice. I must do > these calculations. If you know of any way that is supported by the > hardware, it will be terrific, but for now the slower things will have > to do. > > > Did you try gmpy? > > Not yet: I was kind of set back when I saw their homepage was last > updated 2002. Try looking here: http://code.google.com/p/gmpy/ The developers have abandoned SourceForge. > But I'll give it a try. You think it's the best thing > there is? I haven't tried everything, but it's very good. You might also want to go to the GMP site itself and get their manual. Likee anything else, your results will be no better than your algorithms. > > Thanks, > Ram. From mccredie at gmail.com Wed Jun 25 11:35:00 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 25 Jun 2008 08:35:00 -0700 (PDT) Subject: Sequence iterators with __index__ References: <433c6aca-745e-4c9f-b182-d76291449829@m73g2000hsh.googlegroups.com> <119bb268-2064-4128-8006-f5564f0c62f8@q27g2000prf.googlegroups.com> Message-ID: <44e89b70-e2b9-44a5-a02a-27482b6be681@d1g2000hsg.googlegroups.com> On Jun 24, 4:19?pm, schickb wrote: > On Jun 24, 3:45?pm, Matimus wrote: > > > > > > I think it would be useful if iterators on sequences had the __index__ > > > method so that they could be used to slice sequences. I was writing a > > > class and wanted to return a list iterator to callers. ?I then wanted > > > to let callers slice from an iterator's position, but that isn't > > > supported without creating a custom iterator class. > > > Could you post an example of what you are talking about? I'm not > > getting it. > > Interactive mock-up: > > >>> a = ['x','y','z'] > >>> it = iter(a) > >>> a[it:] > ['x', 'y', 'z'] > >>> it.next() > 'x' > >>> a[it:] > ['y', 'z'] > >>> a[:it] > ['x'] > >>> it.next() > 'y' > >>> a[it:] > > ['z'] > > This lets you use sequence iterators more general position indicators. > Currently if you want to track a position and slice from a tracked > position you must do it manually with an integer index. It's not > difficult, but given that sequence iterators already do that already > it seems redundant (and of course more error prone). > > > In any case, the first step is writing a PEP.http://www.python.org/dev/peps/ > > Ok thanks, but I do want some idea of interest level before spending a > bunch of time on this. > > -Brad I have no problem with being able to query the position (state) of an iterator without changing its state. I think using the iterator itself as the index or part of a slice in the original sequence is non- obvious and also less useful than just a new method to query state. "Explicit is better than Implicit". I would rather see just `it.index()` or `it.state()` than the new specialized behavior implied by `it.__index__()`. I'm leaning towards `state` because sequences already have an `index` method, and two methods of the same name with different behaviors may be confusing. This gives you essentially the same ability, and the code seems a little more obvious IMHO. >>> a = ['x','y','z'] >>> it = iter(a) >>> a[it.state():] ['x', 'y', 'z'] >>> it.next() 'x' >>> a[it.state():] ['y', 'z'] >>> a[:it.state()] ['x'] >>> it.next() 'y' >>> a[it.state():] ['z'] >>> it.state() 2 Matt From maehhheeyy at gmail.com Thu Jun 5 15:58:53 2008 From: maehhheeyy at gmail.com (maehhheeyy) Date: Thu, 5 Jun 2008 12:58:53 -0700 (PDT) Subject: Token Error: EOF in multiline statement Message-ID: I'm not sure what it means but it always highlights the last line with nothing on it. My program has 63 lines and it highlights the 64th line. This keeps popping up whenever I try to run my program. Can you please help me fix this? From johnjsal at NOSPAMgmail.com Tue Jun 17 09:34:24 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 17 Jun 2008 09:34:24 -0400 Subject: Buffer size when receiving data through a socket? References: <20080616202135.41c407de.johnjsal@NOSPAMgmail.com> Message-ID: <03b332ec$0$27271$c3e8da3@news.astraweb.com> "Gabriel Genellina" wrote in message news:mailman.547.1213684963.1044.python-list at python.org... > Both programs say recv(buffer_size) - buffer_size is the maximum number of > bytes to be RECEIVED, that is, READ. recv will return at most buffer_size > bytes. It may return less than that, even if the other side sent the data > in a single operation. > Note that most of the time you want to use the sendall() method, because > send() doesn't guarantee that all the data was actually sent. > I was wondering about sendall(). The examples I've read in two different books are consistent in their use of send() and don't even mention sendall(), so I thought maybe it was for a more specialized situation. > Yes, it is stored in an intermediate buffer until you read it. You typed > "hello" and sent it, the server replied with the string "You typed: > hello"; the OS stores it. You read only 10 bytes "You typed:", the > remaining are still in the buffer. Next round: you type something, the > server replies, you read the remaining bytes from the original reply, and > so on... Oh!!!! I didn't even count "You typed:" as part of the 10 bytes! And what a coincidence that it happens to be exactly 10 characters! That really helped to hide the problem from me! > (Note that in this particular configuration, the client will fill its > buffer at some time: because the server sends at least 11 bytes each > round, but the client reads at most 10 bytes, so the client is always > behind the server...) How is the server sending back 11 bytes? Is it because it's sending at least the 10 characters, plus the extra space? Thanks! From mikecdj at gmail.com Tue Jun 24 20:30:16 2008 From: mikecdj at gmail.com (mikecdj at gmail.com) Date: Tue, 24 Jun 2008 17:30:16 -0700 (PDT) Subject: Porn Addiction References: <0bc1d618-f140-4390-9dd0-4ade923ab054@w1g2000prd.googlegroups.com> Message-ID: On Jun 24, 7:24 pm, Hughjar... at gmail.com wrote: > Help, I'm addicted to porn. I've been downloading porn online and > masturbating to it for a few years... Lately it's gotten even worse, I > spend hours and hours surfing and masturbating to it. It's taking over > my life and ruining everything.. I even missed days from work because > of this addiction. > > I'm going to the porn as a way to avoid unwanted feelings or > procrastination and then it just takes over. > > What can I do to end this horrible addiction? > > -Hugh Install a porn filter immediately. This will block explicit sexual material from entering your computer. Download the Optenet porn filter at http://www.optenetpc.com/ You can beat this thing. From fuzzyman at gmail.com Wed Jun 11 15:17:50 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Wed, 11 Jun 2008 12:17:50 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <6e6df35e-e641-44d9-9f56-c0732306eec2@q27g2000prf.googlegroups.com> <13db98b5-ed2e-45ef-97ec-ad3caeeed10e@j1g2000prb.googlegroups.com> <074caf4a-de1e-4290-b688-30148786952c@z72g2000hsb.googlegroups.com> <776fd3e3-7c2e-45b1-8196-7cde93e72da3@w1g2000prd.googlegroups.com> <98d541c3-e974-4a8c-961c-2a59f6bf32ea@v26g2000prm.googlegroups.com> Message-ID: <4beb7bc4-61ae-4c61-b182-270ec1dd06cf@25g2000hsx.googlegroups.com> On Jun 11, 6:49?pm, Rhamphoryncus wrote: > On Jun 11, 7:56 am, Fuzzyman wrote: > > > > > On Jun 11, 6:56 am, Rhamphoryncus wrote: > > > > On Jun 10, 3:41 pm, Fuzzyman wrote: > > > > > On Jun 10, 2:03 am, Rhamphoryncus wrote: > > > > How does that protect code like this? > > > > f = open('somefile', 'w') > > > # interruption here > > > try: > > > ? ? ... > > > finally: > > > ? ? ... > > > How does it *not* protect you if you write this instead: > > > f = None > > try: > > ? f = open('somefile', 'w') > > ? ... > > finally: > > ? if f is not None: > > ? ? ... > > Yeah, that should be safe, so long as the open call itself is > protected. > > > > > > > The calculation is 'coarse grained' (it can call into .NET APIs that > > > > can take a relatively long time to return) - so polling for exit > > > > wouldn't work anyway. We also run user code and can't expect their > > > > code to poll for exit conditions. > > > > Do those .NET get interrupted at arbitrary points? ?Is this > > > "untrusted" user code also audited for correctness? ?(Although I'd bet > > > you simply document what you do and blame the user if something > > > breaks.) > > > We don't audit our user code - of course. We do document and assist > > them as necessary. Changing to a more restrictive model still wouldn't > > meet our use case and put *more* of a burden on our users. > > > Our situation is not the only one. In general there are situations > > where you may want to put a long running calulcation on a background > > thread and you *know* that it is safe to interrupt - but Python > > currently won't let you. > > > > I'm not saying it can't be made to work in your specific case - it > > > likely does work well for you. ?I'm saying it can't work *in > > > general*. ?Stretching it out for general use turns those little cracks > > > into massive canyons. ?A language needs a general mechanism that does > > > work - such as a polite cancellation API. > > > Neither *works in general* - polite cancellation *doesn't* work for > > our us. That's my point - you probably want *both* for different use > > cases. :-) > > Yeah, but mine's less icky. ;) > But requires more code. :-) > I think the ideal for you would be a separate process. ?I'd also > suggest a restricted VM only in a thread, but that probably wouldn't > work for those long-running .NET APIs. ?Now, if those long- > running .NET APIs did polite cancellation, then you could combine that > with a restricted VM to get what you need. No - we need to pull a large object graph *out* of the calculation (with no guarantee that it is even serializable) and the overhead for marshalling that puts using multiple processes out of the running. What we *want* is what we've got! And it works very well... None of the problems you predict. :-) We may at a future date look to using AppDomains to sandbox user code - but haven't needed to yet. Michael http://www.ironpythoninaction.com/ > > I think what bothers me is, even if those external APIs support polite > cancellation properly, your forced interruptions will bleed over and > mess them up. ?There needs to be a way of containing it better. > Writing them in another language (as C is used for most of Python's > builtins today) isn't a reasonable requirement. From johnjsal at NOSPAMgmail.com Thu Jun 5 10:20:53 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 5 Jun 2008 10:20:53 -0400 Subject: Proof that \ is a better line joiner than parenthetical sets Message-ID: <4847f59f$0$25187$c3e8da3@news.astraweb.com> Goofy post of the day... According to the Zen of Python, "explicit is better than implicit", and the section in the Reference Manual describing the \ line joiner is called "Explicit line joining" and the section describing parentheticals is called "Implicit line joining." So there! ;) From deets at nospam.web.de Mon Jun 16 05:04:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 16 Jun 2008 11:04:52 +0200 Subject: Removing inheritance (decorator pattern ?) References: <6blbcoF3b6v17U1@mid.uni-berlin.de> Message-ID: <6bmomrF3d11s6U1@mid.uni-berlin.de> Diez B. Roggisch wrote: > George Sakkis schrieb: >> I have a situation where one class can be customized with several >> orthogonal options. Currently this is implemented with (multiple) >> inheritance but this leads to combinatorial explosion of subclasses as >> more orthogonal features are added. Naturally, the decorator pattern >> [1] comes to mind (not to be confused with the the Python meaning of >> the term "decorator"). >> >> However, there is a twist. In the standard decorator pattern, the >> decorator accepts the object to be decorated and adds extra >> functionality or modifies the object's behavior by overriding one or >> more methods. It does not affect how the object is created, it takes >> it as is. My multiple inheritance classes though play a double role: >> not only they override one or more regular methods, but they may >> override __init__ as well. Here's a toy example: >> >> class Joinable(object): >> def __init__(self, words): >> self.__words = list(words) >> def join(self, delim=','): >> return delim.join(self.__words) >> >> class Sorted(Joinable): >> def __init__(self, words): >> super(Sorted,self).__init__(sorted(words)) >> def join(self, delim=','): >> return '[Sorted] %s' % super(Sorted,self).join(delim) >> >> class Reversed(Joinable): >> def __init__(self, words): >> super(Reversed,self).__init__(reversed(words)) >> def join(self, delim=','): >> return '[Reversed] %s' % super(Reversed,self).join(delim) >> >> class SortedReversed(Sorted, Reversed): >> pass >> >> class ReversedSorted(Reversed, Sorted): >> pass >> >> if __name__ == '__main__': >> words = 'this is a test'.split() >> print SortedReversed(words).join() >> print ReversedSorted(words).join() >> >> >> So I'm wondering, is the decorator pattern applicable here ? If yes, >> how ? If not, is there another way to convert inheritance to >> delegation ? > > Factory - and dynamic subclassing, as shown here: > > import random > > class A(object): > pass > > class B(object): > pass > > > def create_instance(): > superclasses = tuple(random.sample([A, B], random.randint(1, 2))) > class BaseCombiner(type): > > def __new__(mcs, name, bases, d): > bases = superclasses + bases > return type(name, bases, d) > > class Foo(object): > __metaclass__ = BaseCombiner > return Foo() > > for _ in xrange(10): > f = create_instance() > print f.__class__.__bases__ Right now I see of course that I could have spared myself the whole __metaclass__-business and directly used type()... Oh well, but at least it worked :) Diez From bruno.desthuilliers at gmail.com Fri Jun 6 15:02:24 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 6 Jun 2008 12:02:24 -0700 (PDT) Subject: Assigning to __class__ : bad form? References: <61f33$48497912$7402@news.teranews.com> Message-ID: On 6 juin, 19:51, The Pythonista wrote: > I've been wondering for a while about whether assigning to __class__ is > bad form or not. Specifically, I mean doing so when some other method of > implementing the functionality you're after is available (i.e. using an > adapter, or something like the strategy pattern). > > To give an example and a non-example of what I'm talking about, consider > the following recipes from the online Python Cookbook: > > Ring Buffer:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68429 > > In this case, I think the assignment to __class__ just obfuscates things, > and the example would be better coded as a single class. > > On the other hand, > > Fast copy of an object having a slow __init__ : http:// > aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66507 > > This seems like a reasonable use case for assigning to __class__ (except > that it's already implemented in the 'new' module, but, read the Martelli- > bot's comments near the end of the recipe). I consider this a reasonable > use case for assigning to __class__, because, short of the 'new' module, > I don't see any other way to accomplish it. > > So, what is the opinion of the broader Python community? My first opinion is that your formulation, ie "assigning *to* __class__" is perhaps a bit misleading. What you're talking about is rebinding the __class__ attribute, while, from your subject line, I thought you were talking about reassigning to (rebinding) a class attribute from the instance, ie : self.__class__.attrib = value. Now to the point: > Is code that > assigns to __class__ just clever trickiness to be avoided, or is it > sometimes a good thing? Both, definitively !-) Like most of Python's "advanced" features, it's nice to have it because it can easily solve problems that would otherwise be at best a PITA, but it's not something you use on a daily basis - nor without thinking twice. And obviously, there's no clear rule here, except good taste and common sense. Anyway, the mere fact that you're asking yourself if it's a good idea in such or such case is a probably a good indication that you'll find out by yourself the day you'll be tempted to use this trick whether it's a good or bad idea in this particular context. From deets at nospam.web.de Tue Jun 10 10:30:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 10 Jun 2008 16:30:58 +0200 Subject: str to float (rounded) References: Message-ID: <6b7hi9F3augt4U1@mid.uni-berlin.de> Nader wrote: > Hello, > > I have a list of tuple with strin elements. These elements are number, > but they are save as string. Now I will change the string to number > which will be rounded. An example will make it more clear. > > t = [('35.757', '-0.239'), ('33.332', '-2.707'), ('33.640', '-2.423')] > > And I will have the next list: > > t = [(35.76, -2.24), (33.33, -2.71), (33.64, -2.42)] > > The elements of tuple are not more as string. > > Would somebody tell me how I can do that? use float("123.45") to convert a string to a float. Of course you need to do that on all your elements above by e.g. a list-comprehension. Diez From tim.tadh at gmail.com Wed Jun 11 11:47:53 2008 From: tim.tadh at gmail.com (Tim Henderson) Date: Wed, 11 Jun 2008 08:47:53 -0700 (PDT) Subject: How to find duplicate 3d points? References: Message-ID: <4c86fa4b-1710-4e44-b2ed-0f4d82264bcb@d77g2000hsb.googlegroups.com> On Jun 11, 11:35?am, oprah.cho... at gmail.com wrote: > I have a large data file of upto 1 million x,y,z coordinates of > points. I want to identify which points are within 0.01 mm from each > other. I can compare the distance from each point to every other > point , but this takes 1 million * 1 million operations, or forever! > > Any quick way to do it, perhaps by inserting just the integer portion > of the coordinates into an array, and checking if the integer has > already been defined before inserting a new point? what many people do when doing collision detection in 3d games in instead of having one massive list of the vertices will break the field into bounding boxes. in the 2d situation that would look like this. |----|----|----|----| |. . | | .| | |----|----|----|----| |. |. | . |. | |----|----|----|----| | | . | . | | |----|----|----|----| | | | | . .| |----|----|----|----| That so instead of comparing all points against all other points instead sort them into bounding cubes. that should make doing the comparisons more reasonable. now the only sticky bit will be comparing two vertices that are in two different boxes but so close to the edges that they are under .01mm from each other. in this situation if a point is less that .01mm from any edge of its bounding cube you must compare it against the points in the adjacent cubes. hope this helps a bit. cheers Tim Henderson From rocky at panix.com Fri Jun 13 07:21:30 2008 From: rocky at panix.com (R. Bernstein) Date: Fri, 13 Jun 2008 07:21:30 -0400 Subject: Debuggers References: <485220ca_1@news.tm.net.my> Message-ID: TheSaint writes: > Hi, > > while testing my program I found some strange happening with pdb and pydb. > > I like pydb because let me restart the program and nicer features, but if > errors pop up, then it will forget all variables (globals and locals gone). I'm not completely sure what you mean, but I gather that in post-mortem debugging you'd like to inspect local variables defined at the place of error. For example in this program def raise_error: x=5 raise FloatingPointError raise_error you'd like to look at x. Python as a language is a little different than say Ruby. In Python the handler for the exception is called *after* the stack is unwound while in Ruby it is called before. What this means to you is basically what you reported: that you are not going to be able to see some local variables after an exception occurs (i.e. in post-mortem debugging) whether pydb, pdb, any debugger or any Python program you write. This was mentioned a while back: http://groups.google.com/group/comp.lang.python/browse_thread/thread/23418f9450c13c2d/b0b1908495dde7bc?lnk=st&q=#b0b1908495dde7bc By the way, although Ruby *does* call the exception handler before the stack is unwound, there's no way that I know to *clear* the exception so that you can dynamically "handle" it. This has a certain legitimacy since it might be dangerous to continue in some exception and the state of the interpreter may be inconsistent. For example if I write x = 1/0 or if 1/0 > 5 : what value do I use for 1/0? (Far worse is where something like a SEGV occurs, but I'm not sure that will raise an exception instead of terminate Python.) > I've to go for pdb because it isn't affected by that problem, but also in > some case pdb doesn't recognize a fix after a post-mortem restart. The funny > thing is that it shows the line corrected, but pdb execute the one it put in > memory. > However, I think also python shell has such flaw. I'd like to know how to > blank all current data and restart a program or re-import a corrected class > sentence. > Any other to try? > I'm also prone to use Ipython, but I still miss some learning how to run a > program within Ipython itself. > So if I do: > > import myprogram > myprogram.__main__ > > Will it run? And then the other arguments from CLI, how do I pass them in? > -- > Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From Russ.Paielli at gmail.com Thu Jun 5 00:50:19 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 4 Jun 2008 21:50:19 -0700 (PDT) Subject: line continuation for lines ending in "and" or "or" References: <90ee8b5d-1509-4463-aaab-f712f7e72d4b@j33g2000pri.googlegroups.com> Message-ID: <0d723e6d-f81b-4545-b406-fc60b20c5433@u6g2000prc.googlegroups.com> On Jun 4, 9:01 pm, Dan Bishop wrote: > On Jun 4, 10:09 pm, "Russ P." wrote: > > > I've always appreciated Python's lack of requirement for a semi-colon > > at the end of each line. I also appreciate its rules for automatic > > line continuation. If a statement ends with a "+", for example, Python > > recognizes that the statement obviously must continue. > > > I've noticed, however, that the same rule does not apply when a line > > ends with "and," "or," or "not." Yes, it's a minor point, but > > shouldn't the same rule apply? > > > Seems like it would be easy to add. > > Huh? This doesn't work either: > > >>> x = 2 + > > File "", line 1 > x = 2 + > ^ > SyntaxError: invalid syntax > > Implicit line continuation only happens if you have an unmatched '('. > > >>> x = (2 + > > ... 2 > ... )>>> x > > 4 Darnit! You're right. I've been reading up on Scala lately, and I guess I got confused. Well, it wouldn't be a bad idea for Python to do what I thought it did, *plus* what I said it ought to do. Scala is a nice language, by the way. Check it out when you get a chance (http://www.scala-lang.org). I'm thinking about switching over to it from Python if I can. I just wish it had default arguments and argument passing by keyword. Now, those are a couple of features that I really appreciate in Python. Oh, and I wish Scala used "and" and "or" rather than "&&" and "||". There's another thing Python got right. From google at mrabarnett.plus.com Wed Jun 25 09:41:04 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 25 Jun 2008 06:41:04 -0700 (PDT) Subject: Send output to printer References: <013c01c8d67f$869bfea0$1f01a8c0@RAZAK> Message-ID: <53fe9013-47d3-4e3d-a873-ab046812ab20@m3g2000hsc.googlegroups.com> On Jun 25, 7:49?am, "Jorgen Bodde" wrote: > Hi, > > It depends on how your printer can be accessed. Is there a driver for > it? The most simple way might be using ShellExecute (under windows) > but I found ?no way to supress the print dialog. > > Another way is using win32com module and instantiate an IE automation > object, which you feed a HTML page and issue a print. Be careful about > printing too fast allow it 4-5 seconds to process or successive print > jobs will fail. > > Here is a snippet of code to get you on your way; > > from win32com import client > ie = client.Dispatch("InternetExplorer.Application") > ie.Navigate(fn) ? ? ?# fn = filename (to temp file) to print > time.sleep(2) > ie.ExecWB(6, 2) > time.sleep(2) > ie.Quit() > ie = None > > For successive prints it is better to instantiate one IE object per > multiple print jobs, but once done, release it and set it up again. > > - Jorgen > > On Wed, Jun 25, 2008 at 6:54 AM, ajak_yahoo wrote: > > Need some help from you all, > > > I already manage to write a program to print a packaging label. > > > The output on screen is as below, > > > Part Number ? : ?PWEE1111AA > > Quantity ? ? ? ? : ?100 pcs > > Lot Number ? ? : ?10A2008 > > Customer ? ? ? ?: ?ABC Pte. Ltd. > > > My questions is how can I send this output to my Panasonic KX-P1121 dot > > matric printer, > > Is it a module that i can used, previously i wrote my program using foxpro > > 2.6, i have no experience in python. > > > Regards, > > Ajak > > -- > >http://mail.python.org/mailman/listinfo/python-list > > If it's connected to the PC's parallel printer port then you could try writing to "LPT1:": printer = open("LPT1:", "wb") printer.write("Hello world!\r\n") printer.close() Note that in order to advance to the next line you'll need to write a carriage return and linefeed ("\r\n"), as above. From mal at egenix.com Fri Jun 27 06:38:05 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 27 Jun 2008 12:38:05 +0200 Subject: Getting column names from a cursor using ODBC module? In-Reply-To: References: Message-ID: <4864C30D.2090209@egenix.com> John Machin wrote: > On Jun 21, 11:58 pm, dana... at yahoo.com wrote: >> Is there any way to retrieve column names from a cursor using the ODBC >> module? Or must I, in advance, create a dictionary of column position >> and column names for a particular table before I can access column >> values by column names? I'd prefer sticking with the ODBC module for >> now because it comes standard in Python. >> >> I'm using Python 2.4 at the moment. >> > > Do you mean the odbc module? If so, it doesn't come standard in > Python; it's part of the win32 package. > > I haven't used it for years -- my preference on Windows these days > would be mxODBC if the client would pay the licence fee, otherwise > pyodbc. Sorry I'm not answering your question ... perhaps you should > be asking a different question :) mxODBC comes with a cursor.columns() method which allows you to query column names and many other column specific details of the database. See the documentation for details: http://www.egenix.com/products/python/mxODBC/#Documentation If you just want to access the result set columns by name, you can use the cursor.description tuple to map names to positions. Please also see the FAQ of the DB API spec reagrding the issues involved with this approach: http://www.python.org/dev/peps/pep-0249/ -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From fc14301589 at icqmail.com Fri Jun 13 02:53:41 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Fri, 13 Jun 2008 14:53:41 +0800 Subject: can't assign to literal References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> <1a244dc4-4d10-491d-8ec7-224f3a1f0df5@m73g2000hsh.googlegroups.com> <484feda6_2@news.tm.net.my> <4850bc42_1@news.tm.net.my> Message-ID: <4852197f_1@news.tm.net.my> On 15:11, gioved? 12 giugno 2008 Dennis Lee Bieber wrote: > Word spaced line justification is only feasible if one is using a > fixed width font and have a line length defined in "characters/line". ===8<======8<======8<======8<======8<======8<======8<======8<======8<======8< line= 'fixed width font and have a line length defined in "characters/line".' lenLine= 78; newLine= ''; Words= line.split(' ') lnWords= len(Words); norm_spc= lnWords-1; xtr_spc = lenLine -len(line) lenChr= len(line)-norm_spc numspc= (norm_spc+ xtr_spc)/ norm_spc lstword= len(Words[norm_spc]) for spc in range(lnWords): if len(newLine)+lstword + numspc > lenLine : break newLine += Words[spc]+(' '* numspc) if xtr_spc: newLine += ' '; xtr_spc -= 1 print newLine+ ' '+ Words[spc] ===8<======8<======8<======8<======8<======8<======8<======8<======8<======8< In my mind it took me just few seconds :), but to get it working I spent nearly *one* hour. I admit that my skill lacks of knowledge ]) -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From nick at craig-wood.com Tue Jun 24 07:32:12 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 24 Jun 2008 06:32:12 -0500 Subject: Python 3000 vs Perl 6 References: Message-ID: Corey G. wrote: > The main concern (my concern) is whether or not Perl 6 is > more like Java with pre-compiled byte code (did I say that right) See below for some python VM comments > and whether or not individuals without the ability to see past the > surface will begin to migrate towards Perl 6 for its seemingly > faster capabilities. I doubt it but you never know! > With Perl 6 taking 10+ years, if/when it actually gets released, will > it be technically ahead of Python 3000? Perl 6 was a major reason for me to switch to using python. To make that radical a change in the language seemed reckless. The fact that it still hasn't been released after 8 years of development (Larry announced it in his State of the Onion speech in 2000 I think) makes me think that I made the right choice. Python 3.0 is a very gentle change to python in comparison. You won't have to change much of your code and when you do you'll think - that looks better! > Is Parrot worth the extra wait the Perl 6 project is enduring? My > own answer would be a resounding no, but I am curious as to what > others think. :) Another VM to run python would be nice of course, but we already have jython, ironpython and pypy. Both jython and ironpython use JIT, pypy can compile to native code and you can use psyco for JIT code also in normal python. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From xdicry at gmail.com Fri Jun 27 10:48:17 2008 From: xdicry at gmail.com (Evan) Date: Fri, 27 Jun 2008 07:48:17 -0700 (PDT) Subject: what is meaning of "@" in pyhon program. Message-ID: <88990b3d-1916-413f-83b9-796aabf43623@l28g2000prd.googlegroups.com> HI, When I check example of "cmd2" module (a enhancement of cmd module), I can not understand all, for example: the character "@", +++++++++++++++++++++++++++++++++++++++++++++++++++++ def options(option_list): .................. class cmd(...): ............................... @options([make_option('-p', '--piglatin', action="store_true", help="atinLay")]) +++++++++++++++++++++++++++++++++++++++++++++++++++++ I do not understand what "@options" does, most time, I know what the meaning of character "*" and character "**", but I was not use "@" before. Thanks for your help. From george.sakkis at gmail.com Thu Jun 12 00:51:05 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 11 Jun 2008 21:51:05 -0700 (PDT) Subject: Producer-consumer threading problem References: Message-ID: On Jun 11, 10:13?am, Jean-Paul Calderone wrote: > On Tue, 10 Jun 2008 22:46:37 -0700 (PDT), George Sakkis wrote: > >On Jun 10, 11:47 pm, Larry Bates wrote: > > >> I had a little trouble understanding what exact problem it is that you are > >> trying to solve but I'm pretty sure that you can do it with one of two methods: > > >Ok, let me try again with a different example: I want to do what can > >be easily done with 2.5 Queues using Queue.task_done()/Queue.join() > >(see example athttp://docs.python.org/lib/QueueObjects.html), but > >instead of ?having to first put all items and then wait until all are > >done, get each item as soon as it is done. > > >> 1) Write the producer as a generator using yield method that yields a result > >> every time it is called (something like os.walk does). ?I guess you could yield > >> None if there wasn't anything to consume to prevent blocking. > > >Actually the way items are generated is not part of the problem; it > >can be abstracted away as an arbitrary iterable input. As with all > >iterables, "there are no more items" is communicated simply by a > >StopIteration. > > >> 2) Usw somethink like Twisted insted that uses callbacks instead to handle > >> multiple asynchronous calls to produce. ?You could have callbacks that don't do > >> anything if there is nothing to consume (sort of null objects I guess). > > >Twisted is interesting and very powerful but requires a different way > >of thinking about the problem and designing a solution. More to the > >point, callbacks often provide a less flexible and simple API than an > >iterator that yields results (consumed items). For example, say that > >you want to store the results to a dictionary. Using callbacks, you > >would have to explicitly synchronize each access to the dictionary > >since they may fire independently. > > This isn't true. ?Access is synchronized automatically by virtue of the > fact that there is no pre-emptive multithreading in operation. ?This is > one of the many advantages of avoiding threads. :) ?There may be valid > arguments against callbacks, but this isn't one of them. > > Jean-Paul Thanks for the correction; that's an important advantage for callbacks in this case. George From delfick755 at gmail.com Fri Jun 6 07:19:56 2008 From: delfick755 at gmail.com (Stephen Moore) Date: Fri, 6 Jun 2008 19:19:56 +0800 Subject: creating yaml without tags using pyyaml Message-ID: hello I have a situation where I have quite a large python object which I want to convert to yaml so I can then send it to a flex application using pyamf. I've managed to create a yaml document using the python object (http://flashbsm.googlecode.com/svn/testing/yamlTest/tester.yaml) (using pyyaml) however when I send the result of decoding the python object to yaml to the flex app, the flex app complains about expecting a block end, but not getting one. I have come to the conclusion that this is the fault of the tags (for example, !!python/tuple) as getting rid of them gets rid of the errors. So I'm wondering if there is an option to YAML.decode that will create a yaml document without the tags? Thankyou Regards Stephen From ram.rachum at gmail.com Sun Jun 15 15:10:16 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Sun, 15 Jun 2008 12:10:16 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> Message-ID: <7be098bd-7d14-44d0-ac69-0c5fb261d454@25g2000hsx.googlegroups.com> On Jun 15, 8:52?pm, Peter Otten <__pete... at web.de> wrote: > ram.rac... at gmail.com wrote: > > I have a physical system set up in which a body is supposed to > > accelerate and to get very close to lightspeed, while never really > > attaining it. After approx. 680 seconds, Python gets stuck and tells > > me the object has passed lightspeed. I put the same equations in > > Mathematica, again I get the same mistake around 680 seconds. So I > > think, I have a problem with my model! Then I pump up the > > WorkingPrecision in Mathematica to about 10. I run the same equations > > again, and it works! At least for the first 10,000 seconds, the object > > does not pass lightspeed. > > That the values are possible doesn't mean that you can trust them. > I do not understand this comment. > > I concluded that I need Python to work at a higher precision. > > How is WorkingPrecision defined? Python floats have about 16 significant > digits in base 10, so at first glance I would guess that you switched to > a /lower/ precision. > I don't know how WorkingPrecision is defined. However, I think it's not lower, it's higher. > But I've come to agree with Christian that it would be good to show your > model to a physics and/or numerical maths expert. Perhaps you can find a > way for the errors to cancel out rather than accumulate. I might try that. From boingy.boingy at gmail.com Wed Jun 25 17:37:41 2008 From: boingy.boingy at gmail.com (idiolect) Date: Wed, 25 Jun 2008 14:37:41 -0700 (PDT) Subject: Newbie question about tuples and list comprehensions Message-ID: Hi all - Sorry to plague you with another newbie question from a lurker. Hopefully, this will be simple. I have a list full of RGB pixel values read from an image. I want to test each RGB band value per pixel, and set it to something else if it meets or falls below a certain threshold - i.e., a Red value of 0 would be changed to 50. I've built my list by using a Python Image Library statement akin to the following: data = list(image.getdata()) Which produces a very long list that looks like [(0,150,175), (50,175,225),...]. I'm trying to figure out a fast and pythonic way to perform my operation. The closest I've come so far to a succinct statement is a list comprehension along the syntax of: source = [((x,y,z),(x+50,y+50,z+50))[bool(x or y or z < 50)] for (x,y,z) in source] ...which kind of approaches the effect I'm looking for, but it doesn't really test and change each value in the tuple individually. My understanding of the things you can do with lists and python in general is rather naive, so I would appreciate any insight anyone can offer since I am not sure if I'm even headed down the correct path with list comprehensions. Much obliged! From morton.thomas at googlemail.com Tue Jun 10 03:28:14 2008 From: morton.thomas at googlemail.com (Thomas Morton) Date: Tue, 10 Jun 2008 08:28:14 +0100 Subject: Getting current screen resolution References: Message-ID: <6FD81F1D7C2C4CBEAAA31E9D5174172C@ErrantGaming> Yeh that's not such an issue - this is for some basic image analysis for a document / report. It's not HUGELY important data (it can be wrong with no real come back) but it has to be roughly accurate... The idea is I have an image and I need to work out how big it displays on the monitor of the computer running the script :) Thanks for the replies so far ppl :) I think I might have it....... Tom -------------------------------------------------- From: "Larry Bates" Sent: Monday, June 09, 2008 11:16 PM Newsgroups: comp.lang.python To: Subject: Re: Getting current screen resolution > Thomas Morton wrote: >> This is a "thing" that has been annoying me all morning: and I can't >> work out how to do it. >> >> I need a way to get the DPI or screen resolution of the monitor that a >> script is currently runnign on. >> >> I have a way in Windows but it doesnt port to Unix (which is important). >> >> Any ideas? >> > > warning - be very careful about trying to come up with something like > this. > Today it is common for people to have more than one monitor, so you will > need to take that into account. Just getting resolution of one monitor > might not be enough (but then I don't know EXACTLY what is is that you are > doing with the > resolution). I see a lot of software that ignores the dual-monitor > possibility. > > -Larry > -- > http://mail.python.org/mailman/listinfo/python-list From google at mrabarnett.plus.com Thu Jun 12 21:20:09 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 12 Jun 2008 18:20:09 -0700 (PDT) Subject: Charset (hopefully for the last time I ask) References: Message-ID: On Jun 12, 8:04 pm, Gandalf wrote: > now I understand my problem better so their is a good chance you > manage to help me. > > I have a SQlite database full with ANSI Hebrew text , and program that > uses WXpython > Now, I use a- 'wx.TextCtrl' item to receive input from the user, and > when I try to search the database he don't understand this chars. > > it's quite reasonable consider the fact the program set to work on > UTF-8 charset, except for: > > 1. it doesn't work when I delete the charset too > > 2. when I try to use function like decode and encode it output error > like this: > ascii' codec can't encode characters in position 0-4: ordinal not in > range(128) > ascii' codec can't encode characters in position 0-2: ordinal not in > range(128) > > 3. I don't know how to translate my DB from ANSI to UTF-8 > > 4. when I don't use the user WX items input I can change my editor > charset to ansi and it works fine > > Thank you all Have you tried something like: unicode_text = text_from_db.decode("cp1255") print unicode_text utf8_text = unicode_text.encode("utf8") print utf8_text (I believe the codepage 1255 is Hebrew.) From basti.wiesner at gmx.net Tue Jun 10 07:26:59 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Tue, 10 Jun 2008 13:26:59 +0200 Subject: Python, subprocess, dump, gzip and Cron References: <484e0521$1@dnews.tpgi.com.au> <6870ff12-a1f3-419a-9a8e-62c02e33d118@l17g2000pri.googlegroups.com> <484e0f65$1@dnews.tpgi.com.au> Message-ID: Aidan at Dienstag 10 Juni 2008 07:21: > TT wrote: >> On Jun 10, 2:37 pm, Aidan wrote: >>> Hi, >>> >>> I'm having a bit of trouble with a python script I wrote, though I'm not >>> sure if it's related directly to python, or one of the other software >>> packages... >>> >>> The situation is that I'm trying to create a system backup script that >>> creates an image of the system, filters the output though gzip, and then >>> uploads the data (via ftp) to a remote site. >>> >>> The problem is that when I run the script from the command line, it >>> works as I expect it, but when it is run by cron I only get a 20 byte >>> file where the compressed image should be... does anyone have any idea >>> as to why this might be happening? Code follows >>> >>> >>> >>> #!/usr/bin/python >>> >>> from subprocess import PIPE, Popen >>> from ftplib import FTP >>> >>> host = 'box' >>> >>> filename = '%s.img.gz' % host >>> ftp_host = '192.168.1.250' >>> ftpuser, ftppass = 'admin', 'admin' >>> dest_dir = '/share/%s' % host >>> >>> dump = Popen('dump 0uaf - /',shell=True,stdout=PIPE) You should avoid the use of ``shell=True`` here and use a argument list instead: dump = Popen(['dump', '0uaf', '-', '/'], stdout=PIPE) This results in an exception thrown if the executable doesn't exist. This exception can be caught and handle for instance with the logging module. >>> gzip = Popen('gzip',shell=True,stdin=dump.stdout,stdout=PIPE) Same here, but why don't you use the gzip functionality from the standard library? -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From benjamin.kaplan at case.edu Mon Jun 9 23:10:17 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 9 Jun 2008 23:10:17 -0400 Subject: Odd behavior of python module listing In-Reply-To: <7bfeb431-ea2c-4fd1-8263-8f0d25159269@s33g2000pri.googlegroups.com> References: <7bfeb431-ea2c-4fd1-8263-8f0d25159269@s33g2000pri.googlegroups.com> Message-ID: On Mon, Jun 9, 2008 at 4:58 PM, Lie wrote: > Yesterday I installed compiz-icon in my Ubuntu. Today, when I go to > the python interpreter, I happen to do this: > > ### START OF PYTHON SESSION ### > Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> help() > > Welcome to Python 2.5! This is the online help utility. > > If this is your first time using Python, you should definitely check > out > the tutorial on the Internet at http://www.python.org/doc/tut/. > > Enter the name of any module, keyword, or topic to get help on writing > Python programs and using Python modules. To quit this help utility > and > return to the interpreter, just type "quit". > > To get a list of available modules, keywords, or topics, type > "modules", > "keywords", or "topics". Each module also comes with a one-line > summary > of what it does; to list the modules whose summaries contain a given > word > such as "spam", type "modules spam". > > help> modules > > Please wait a moment while I gather a list of all available modules... > > * Starting Compiz > ... executing: compiz.real --replace --sm-disable --ignore-desktop- > hints ccp > Starting gtk-window-decorator > compiz.real (video) - Warn: No 8 bit GLX pixmap format, disabling YV12 > image format > GConf backend: There is an unsupported value at path /apps/compiz/ > plugins/scale/allscreens/options/initiate_edge. Settings from this > path won't be read. Try to remove that value so that operation can > continue properly. > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/site.py", line 342, in __call__ > return pydoc.help(*args, **kwds) > File "/usr/lib/python2.5/pydoc.py", line 1649, in __call__ > self.interact() > File "/usr/lib/python2.5/pydoc.py", line 1667, in interact > self.help(request) > File "/usr/lib/python2.5/pydoc.py", line 1683, in help > elif request == 'modules': self.listmodules() > File "/usr/lib/python2.5/pydoc.py", line 1804, in listmodules > ModuleScanner().run(callback) > File "/usr/lib/python2.5/pydoc.py", line 1855, in run > for importer, modname, ispkg in pkgutil.walk_packages(): > File "/usr/lib/python2.5/pkgutil.py", line 125, in walk_packages > for item in walk_packages(path, name+'.', onerror): > File "/usr/lib/python2.5/pkgutil.py", line 110, in walk_packages > __import__(name) > File "/usr/lib/python2.5/site-packages/FusionIcon/interface_gtk/ > __init__.py", line 3, in > import main > File "/usr/lib/python2.5/site-packages/FusionIcon/interface_gtk/ > main.py", line 213, in > gtk.main() > KeyboardInterrupt > >>> > ### END OF PYTHON SESSION ### > > How on earth could python's help utility crashed compiz-icon, and made > compiz crash too (I lost my windows decoration after the crash). This > is repeatable, until I uninstalled compiz-icon. After uninstalling, I > retried help -> modules again, same problem, different program, now a > blank Tk window showed up and it printed this traceback: > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/site.py", line 342, in __call__ > return pydoc.help(*args, **kwds) > File "/usr/lib/python2.5/pydoc.py", line 1649, in __call__ > self.interact() > File "/usr/lib/python2.5/pydoc.py", line 1667, in interact > self.help(request) > File "/usr/lib/python2.5/pydoc.py", line 1683, in help > elif request == 'modules': self.listmodules() > File "/usr/lib/python2.5/pydoc.py", line 1804, in listmodules > ModuleScanner().run(callback) > File "/usr/lib/python2.5/pydoc.py", line 1855, in run > for importer, modname, ispkg in pkgutil.walk_packages(): > File "/usr/lib/python2.5/pkgutil.py", line 125, in walk_packages > for item in walk_packages(path, name+'.', onerror): > File "/usr/lib/python2.5/pkgutil.py", line 110, in walk_packages > __import__(name) > File "/usr/lib/python2.5/site-packages/OpenGL/Tk/__init__.py", line > 87, in > _default_root.tk.call('package', 'require', 'Togl') > _tkinter.TclError: can't find package Togl > > OK, I don't think I can uninstall Tk without messing up a lot of > harmless python programs later, and by now, I figured out that the > problem isn't in compiz-icon afterall. > > So, has anyone got something like this? > > PS: Ubuntu Hardy Heron (8.04) + Python 2.5.2 > -- The error appears to be in OpenGL. Maybe you should ask the Ubuntu people about it. > > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cokofreedom at gmail.com Wed Jun 18 06:32:48 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 18 Jun 2008 03:32:48 -0700 (PDT) Subject: dict order References: Message-ID: <4804032a-adef-4973-ae21-acc4ad2dce37@z72g2000hsb.googlegroups.com> On Jun 18, 11:22 am, Robert Bossy wrote: > Hi, > > I wish to know how two dict objects are compared. By browsing the > archives I gathered that the number of items are first compared, but if > the two dict objects have the same number of items, then the comparison > algorithm was not mentioned. > > Note that I'm not trying to rely on this order. I'm building a > domain-specific language where there's a data structure similar to > python dict and I need an source of inspiration for implementing > comparisons. > > Thanks > RB I'm a little confused as to what you want. Are you asking whether two dictionary objects have the same keys AND values, or just the Keys? As dictionaries are unordered the best technique is to go through one dictionary and take out a key, then see if that key exists in the other dictionary, and if so do they share the same values. # untested 2.5 for keys in dict_one.items(): if keys in dict_two: if dict_one[keys] != dict_two[keys]: # values are different else: # key is not present This probably isn't the most efficient way, but can quickly find differences... From nick at craig-wood.com Mon Jun 9 05:30:46 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 09 Jun 2008 04:30:46 -0500 Subject: time.clock() or Windows bug? References: <0uep44hpn8rupgr15a135f37q346tif9v2@4ax.com> Message-ID: Tim Roberts wrote: > Nick Craig-Wood wrote: > > > >time.clock() uses QueryPerformanceCounter under windows. There are > >some known problems with that (eg with Dual core AMD processors). > > > >See http://msdn.microsoft.com/en-us/library/ms644904.aspx > > > >And in particular > > > > On a multiprocessor computer, it should not matter which processor > > is called. However, you can get different results on different > > processors due to bugs in the basic input/output system (BIOS) or > > the hardware abstraction layer (HAL). To specify processor > > affinity for a thread, use the SetThreadAffinityMask function. > > That's an extremely arrogant statement on their part, because the fault > here is entirely within Windows. > > Through Windows 2000, the operating system actually synchronized the cycle > counters on the additional processors as they came out of reset at boot > time. (The cycle counter is, after all, a writable register.) As a > result, the cycle counters were rarely off by more than about 20 cycles. > > Beginning with XP, they stopped doing that. As a result, the cycle > counters on multiprocessor machines can vary by millions or even tens of > millions of cycles. Hmmm, 10,000,000 cycles (40 ms @2.5GHz) is nowhere near the ~90,000 second jump in time.clock() output reported by the OP. I wonder if there could be a different cause? -- Nick Craig-Wood -- http://www.craig-wood.com/nick From Wayne.Oosthuizen at gmail.com Sat Jun 14 09:34:43 2008 From: Wayne.Oosthuizen at gmail.com (Constantly Distracted) Date: Sat, 14 Jun 2008 06:34:43 -0700 (PDT) Subject: How do I sort items in a tableview without a column being selected? Message-ID: I have this TableView, which is sorted by column when the user clicks on the header. The problem is though, that all the items are selected and nothing gets sorted. But if the window loses focus everything's get's sorted. Basically I have list of tags say, [{"artist":"Artist1","title":Title1"} , {"artist":"Artist2" , "title": "Title2"}] etc. Where each tag is listed in a column. Then I sort them and reset. Here's the code: def sort(self,column,order=Qt.DescendingOrder): tag=self.headerdata.text newdic={} li=[] i=0 for z in self.taginfo: #taginfo has all the tags if not newdic.has_key(z[tag]): newdic[z[tag]]=z li.append(z[tag]) else: newdic[z[tag] + str(i)]=z li.append(z[tag] + str(i)) i+=1 li.sort() self.taginfo=[newdic[z] for z in li] self.reset() Any ideas? From cokofreedom at gmail.com Fri Jun 13 06:29:00 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Fri, 13 Jun 2008 03:29:00 -0700 (PDT) Subject: boolian logic References: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> Message-ID: <21cca7a7-6f83-4812-bbf5-d91a91fda297@r66g2000hsg.googlegroups.com> > > if var not in (A, B, C): > do_something() > And this is why I love python. From deets at nospam.web.de Wed Jun 18 10:29:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 18 Jun 2008 16:29:43 +0200 Subject: Looking for lots of words in lots of files References: Message-ID: <6bskfpF3d3v42U1@mid.uni-berlin.de> brad wrote: > Just wondering if anyone has ever solved this efficiently... not looking > for specific solutions tho... just ideas. > > I have one thousand words and one thousand files. I need to read the > files to see if some of the words are in the files. I can stop reading a > file once I find 10 of the words in it. It's easy for me to do this with > a few dozen words, but a thousand words is too large for an RE and too > inefficient to loop, etc. Any suggestions? Use an indexer, like lucene (available as pylucene) or a database that offers word-indices. Diez From matei.zaharia at gmail.com Sat Jun 28 18:29:06 2008 From: matei.zaharia at gmail.com (Matei Zaharia) Date: Sat, 28 Jun 2008 15:29:06 -0700 (PDT) Subject: Is there a sampling profiler for Python? Message-ID: I'm looking for a sampling profiler which I can attach to a running Python process without modifying the source code or affecting performance. So far I've only seen references to instrumentation-based profilers. Is any sampling-based tool available? From aisaac at american.edu Sun Jun 29 00:20:27 2008 From: aisaac at american.edu (Alan Isaac) Date: Sun, 29 Jun 2008 04:20:27 GMT Subject: Market simulations with Python In-Reply-To: <8288a0f3-6d0a-4c01-9cf0-295e3a95328a@m73g2000hsh.googlegroups.com> References: <8288a0f3-6d0a-4c01-9cf0-295e3a95328a@m73g2000hsh.googlegroups.com> Message-ID: xamdam wrote: > I am interested in market simulation with Python, simulating buyers > and sellers arriving with goods at random times. I looked at SimPy, > it's pretty nice, but all the examples are around congestion problems. > Should I a) dig deeper b) write something from scratch c) look at > another library? You could use SimPy. Also see: http://gnosis.cx/publish/programming/charming_python_b10.html http://www.mech.kuleuven.be/lce2006/147.pdf If you plan to share you efforts, please post updates here. Alan Isaac From toby at tobiah.org Thu Jun 5 15:24:55 2008 From: toby at tobiah.org (Tobiah) Date: Thu, 05 Jun 2008 12:24:55 -0700 Subject: Question regarding re module References: <9165ed46-4077-44a8-ae93-ceafda975f04@56g2000hsm.googlegroups.com> Message-ID: >> > It could be that the result overloads the __getattr__-method to delegate >> > calls to some object. Thus it's not part of the outer instance. >> > > Didn't I read that Py3 will support a __dir__ method so that classes > *could* report such pseudo-attributes in response to dir? > > -- Paul I don't believe that it possibly could: class foo(object): def __getattr__(self, what): if what[0] == 't': return True f = foo() print f.toby ** Posted from http://www.teranews.com ** From fuzzyman at gmail.com Mon Jun 30 18:15:00 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 30 Jun 2008 15:15:00 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: Message-ID: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > I don't want to be so mean here, but how hard it could be be writing a > freesoftware which would automatically/intelligently auto complete > Python code? (I mean something that really does the job, like > Microsoft's Visual Studio or Sun's NetBeans or something else, you > name it, but just don't give me PyDev please...) > > This could be an extension, a plugin, an Emacs mode, a new editor or > even a brand new huge all-fancy IDE, I don't care, but what am I > missing here? > > Could someone please point me out something that I'm really missing > which is already present in the wild, otherwise I'd like discuss with > whoever is willing to help me to get this thing done. I made my mind > and I could volunteer to make this happen as thesis project for my > incoming graduation in the next year. > > Regards you all, > Ali Servet D?nmez Vim, Emacs, Wing, Komodo, ... more? Yeah, I guess you're missing something. :-) Michael Foord http://www.ironpythoninaction.com/ http://www.trypython.org/ From toby at tobiah.org Tue Jun 3 17:57:20 2008 From: toby at tobiah.org (Tobiah) Date: Tue, 03 Jun 2008 14:57:20 -0700 Subject: Keep a script running in the background References: <210b7fc6-ed52-461d-8b53-455e247d7a29@e39g2000hsf.googlegroups.com> Message-ID: > I need a script to keep running in the background after it's loaded > some data. It will make this data available to the main program in the > form of a dictionary, but I don't want to reload the calculated data > every time the user needs it via the main program. If it were me, I'd go with a database server like mysql. ** Posted from http://www.teranews.com ** From ErendisAldarion at gmail.com Sun Jun 1 19:54:41 2008 From: ErendisAldarion at gmail.com (Aldarion) Date: Sun, 1 Jun 2008 16:54:41 -0700 (PDT) Subject: a question about the #prefix of sys.argv Message-ID: for the little script #egg.py import sys for k,v in enumerate(sys.argv): print k,v it ignores the part after # on linux below is the running output on windows and linux. no clue here. D:\python\note>egg.py #test 0 D:\python\note\egg.py 1 #test D:\python\note>egg.py for bar #spam egg 0 D:\python\note\egg.py 1 for 2 bar 3 #spam 4 egg ddd at bbb:~/transfer$ python2.5 egg.py #test 0 egg.py ddd at bbb:~/transfer$ python2.5 egg.py foo bar #spam egg 0 egg.py 1 foo 2 bar From circularfunc at yahoo.se Wed Jun 11 23:07:26 2008 From: circularfunc at yahoo.se (cirfu) Date: Wed, 11 Jun 2008 20:07:26 -0700 (PDT) Subject: catastrophic regexp, help! References: <26bda6a4-ad16-4b06-aff4-12e311ebaf81@59g2000hsb.googlegroups.com> Message-ID: On 11 Juni, 10:25, Chris wrote: > On Jun 11, 6:20 am, cirfu wrote: > > > pat = re.compile("(\w* *)*") > > this matches all sentences. > > if fed the string "are you crazy? i am" it will return "are you > > crazy". > > > i want to find a in a big string a sentence containing Zlatan > > Ibrahimovic and some other text. > > ie return the first sentence containing the name Zlatan Ibrahimovic. > > > patzln = re.compile("(\w* *)* zlatan ibrahimovic (\w* *)*") > > should do this according to regexcoach but it seems to send my > > computer into 100%CPU-power and not closable. > > Maybe something like this would be of use... > > def sentence_locator(s, sub): > cnt = s.upper().count(sub.upper()) > if not cnt: > return None > tmp = [] > idx = -1 > while cnt: > idx = s.upper().find(sub.upper(), (idx+1)) > a = -1 > while True: > b = s.find('.', (a+1), idx) > if b == -1: > b = s.find('.', idx) > if b == -1: > tmp.append(s[a+1:]) > break > tmp.append(s[a+1:b+1]) > break > a = b > cnt -= 1 > return tmp yes, seems very unpythonic though :) must be a simpler way that isnt slow as hell. From tjreedy at udel.edu Fri Jun 6 02:44:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 6 Jun 2008 02:44:52 -0400 Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> Message-ID: "Mensanator" wrote in message news:bbd90051-36be-4378-9a27-2a47a5471d12 at a1g2000hsb.googlegroups.com... | On Jun 5, 10:42?pm, John Salerno wrote: | > Is it possible to write a list comprehension for this so as to produce a | > list of two-item tuples? | > | > base_scores = range(8, 19) | > score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] | > print zip(base_scores, score_costs) | > | > I can't think of how the structure of the list comprehension would work | > in this case, because it seems to require iteration over two separate | > sequences to produce each item in the tuple. Which is exactly the purpose of zip, or its specialization enumerate! | > zip seems to work fine anyway, but my immediate instinct was to try a | > list comprehension (until I couldn't figure out how!). And I wasn't sure | > if list comps were capable of doing everything a zip could do. | | base_scores = range(8, 19) | score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] | print zip(base_scores, score_costs) | | s = [(i+8,j) for i,j in enumerate( [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3])] | print s | | ##>>> | ##[(8, 0), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, | 2), (16, 2), (17, 3), (18, 3)] | ##[(8, 0), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, | 2), (16, 2), (17, 3), (18, 3)] | ##>>> Of course, enumerate(iterable) is just a facade over zip(itertools.count(), iterable) From carbonimax at gmail.com Fri Jun 20 11:04:57 2008 From: carbonimax at gmail.com (Carbonimax) Date: Fri, 20 Jun 2008 08:04:57 -0700 (PDT) Subject: py2exe, PyQT, QtWebKit and jpeg problem Message-ID: hello I have a problem with py2exe and QtWebKit : I make a program with a QtWebKit view. If I launch the .py directly, all images (jpg, png) are displayed but if I compile it with py2exe I have only png images. No jpg ! No error message, nothing. Have you a solution ? Thank you. From chardish at gmail.com Tue Jun 10 11:47:25 2008 From: chardish at gmail.com (chardish at gmail.com) Date: Tue, 10 Jun 2008 08:47:25 -0700 (PDT) Subject: Instructions on how to build py2exe 0.6.8 (or an installer would be nice, too!) References: <5426baaf-2ba6-41b0-a0ec-1070429b5195@x35g2000hsb.googlegroups.com> Message-ID: <7f3360e4-8a12-45cf-99fa-6172cb5a1aaa@a1g2000hsb.googlegroups.com> On Jun 10, 11:34?am, Mike Driscoll wrote: > Maybe I'm missing something, but I can rename the executables I create > using py2exe 0.6.6 to anything I want after they're created. > > Or are you talking about a Windows installer for the py2exe module > itself? Where are you finding this 0.6.8 version anyway? I can't find > it onwww.py2exe.org > > Anyway, what Thomas is talking about is that the only way to create a > usable installer of py2exe on Windows is to use the same compiler that > the Python you are using. As I understand it, Python 2.4 and 2.5 used > Visual Studio 2003. I think 2.3 used VS6. I have both, so I can try to > compile an installer for any of those versions if you can link me to > the source. > > Mike > > Python Extension Building Network: ? ? http:\\www.pythonlibrary.org The issue with renaming executables only applies to single-file executables, i.e. ones created with zipfile = None as an argument to setup() and --bundle 1 as a command line argument. This is a known issue as of 0.6.6: http://py2exe.org/index.cgi/ProblemsToBeFixed I found sources for 0.6.8 on CVS at: http://sourceforge.net/cvs/?group_id=15583 A Windows installer for the 0.6.8 py2exe module would be ideal, but somehow I doubt that's going to happen anytime soon since there hasn't been a new installer since 2006. If you are willing to build that for me (since I don't have VS) I'd really appreciate it : ) I'm using 32- bit WinXP on this computer. From larry.bates at websafe.com` Mon Jun 23 23:36:45 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 23 Jun 2008 22:36:45 -0500 Subject: 32-bit python memory limits? In-Reply-To: References: Message-ID: Gary Robinson wrote: > I'm running a Python job on OS X 10.5.3 and the Python 2.5.2 that's available as a binary download at python.org for OS X. > > I ran a python program tonight that ended up using much more memory than anticipated. It just kept on using more and more memory. Instead of killing it, I just watched it, using Activity Monitor. I assumed that when it had 2GB allocated it would blow up, because I thought 32-bit python could only address 2GB. > > But Activity Monitor reported that it had allocated 3.99GB of virtual memory before it finally blew up with malloc errors. Was my understanding of a 2GB limit wrong? I guess so! But I'm pretty sure I saw it max out at 2GB on linux... > > Anybody have an explanation, or is it just that my understanding of a 2GB limit was wrong? Or was it perhaps right for earlier versions, or on linux...?? > > Thanks for any thoughts, > Gary > > Yep, 2Gb is only 31 bits. 4Gb is 32 bits (since memory address is an unsigned). -Larry From cmoney62 at gmail.com Wed Jun 18 20:56:50 2008 From: cmoney62 at gmail.com (cmoney62 at gmail.com) Date: Wed, 18 Jun 2008 17:56:50 -0700 (PDT) Subject: FREE YOUR HOME BUSINESS EARN 150 US $$ PER DAY. Message-ID: <88f0c3ba-46e1-4b30-a61d-482e5ecf339a@t12g2000prg.googlegroups.com> FREE YOUR HOME BUSINESS EARN 150 US $$ PER DAY http://govindswamy-govindaswamy.blogspot.com http://kavigovindan.blogspot.com http://govindaswamy-amman.blogspot.com http://govindaswamy10.blogspot.com From grante at visi.com Sat Jun 14 15:15:46 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 14 Jun 2008 14:15:46 -0500 Subject: Making wxPython a standard module? References: <6bidd7F3bg8usU1@mid.uni-berlin.de> Message-ID: On 2008-06-14, Diez B. Roggisch wrote: >>> And on a personal note: I find it *buttugly*. >> >> Do you mind explaining "why" you find it *buttugly*? [...] > For the curious: Not the look & feel (albeit I prefer KDE on > linux over Gnome, which is a Qt/GTK thing and thus affects wx > look & feel as well), but the code & the designers. I've never used any of the designers, but I agree 100% that wxPython code is nasty ugly. wxPython has a very un-Pythonic API that's is, IMO, difficult to use. The API isn't really Robin Dunn's fault: wxPython is a very thin wrapper around wxWidgets, so it largely retains the same nasty low-level C++ API that wxWidgets has. I presume much of wxPython is generated in some automated fasion (a la swing). There have been a couple attempts to wrap wxPython in a cleaner, more Pythonic API, but they've have limited success (wax is the one I can think of off the top of my head). -- Grant Edwards grante Yow! If I had a Q-TIP, I at could prevent th' collapse visi.com of NEGOTIATIONS!! From jgardner at jonathangardner.net Wed Jun 18 11:55:23 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Wed, 18 Jun 2008 08:55:23 -0700 (PDT) Subject: go to specific line in text file References: <1xsmb1wlk1554$.gey53bzk6vfd$.dlg@40tude.net> Message-ID: <5bff9d86-805f-49da-a90c-479a936e130d@r37g2000prm.googlegroups.com> On Jun 17, 3:10?am, Patrick David wrote: > > I am searching for a way to jump to a specific line in a text file, let's > say to line no. 9000. > Is there any method like file.seek() which leads me to a given line instead > of a given byte? > As others have said, no. But if you're wondering how other file formats do this, like BDB or PostgreSQL data files, which absolutely have to jump to the magical spot in the file where the data is, they keep an index at the beginning of the file that points to what byte the data they are looking for is in. So if it's really important to be able to do this, consider that. From evidentemente.yo at gmail.com Wed Jun 25 06:54:34 2008 From: evidentemente.yo at gmail.com (evidentemente.yo) Date: Wed, 25 Jun 2008 03:54:34 -0700 (PDT) Subject: calling a .exe from Python References: Message-ID: <13513ef3-f05c-4749-a8d8-d918abf1d928@z72g2000hsb.googlegroups.com> Thank you for the help!!!:) On 25 jun, 10:32, Nick Craig-Wood wrote: > evidentemente.yo wrote: > > ?On 24 jun, 14:32, Nick Craig-Wood wrote: > > > Probably what you want is this... > > > > from subprocess import call > > > > rc = call(["mypath/myfile.exe",arg1,arg2]) > > > > rc will contain the exit status > > > > See the subprocess module for more things you can do > > > ?Hey, thank you very much!!!:D > > > ?Would it matter if my .exe doesn't return any value? would it return > > ?like an "ok" or something??? > > Your exe will return a value (it is part of the OS) but you can ignore > it if you want. ?Just use > > call(["mypath/myfile.exe",arg1,arg2]) > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick From d3vvnull at gmail.com Thu Jun 5 07:35:39 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Thu, 5 Jun 2008 06:35:39 -0500 Subject: Squeak-like environment for Python? In-Reply-To: <4847c90a$0$6005$426a74cc@news.free.fr> References: <0001HW.C46D717900E84E0DB01AD9AF@news.individual.de> <6apod7F387g23U1@mid.uni-berlin.de> <4847c90a$0$6005$426a74cc@news.free.fr> Message-ID: <170543c70806050435u1d0a0f92tea29df7fa83af603@mail.gmail.com> Check out the Brainwave platform, which uses a new "neural" database model. It allows you to create databases to store any kind of Python object as a "neuron" and allows objects to be connected via link to create complex structures that don't require conventional tables and columns. It is a development platform that has a bundled webserver based on CherryPy, with a built-in application generator and deployer. http://www.brainwavelive.com On Thu, Jun 5, 2008 at 6:08 AM, Bruno Desthuilliers wrote: > Diez B. Roggisch a ?crit : > > Jumping Arne wrote: >> >> I've been playing with Squeak a bit and I really like the persistent >>> storage model, I also liked HyperCard and Frontier (well, the persistent >>> storage model at least). >>> >>> I wonder if there is some similar environment but based on python, I >>> would >>> like to use this environment not as a development environment but as a >>> platform for storing data etc - much like HyperCard. >>> >>> I found a few postings about such an environment: >>> >>> >>> >>> but it looks like nothing happened. >>> >>> pythoncard doesn't seem to have the persistent storage model >>> >> >> What about ZODB? You can use that to store (more or less) arbitrary >> objects. >> Maybe that can be a foundation, if you throw in >> http://nodebox.net/code/index.php/Home >> >> it might be similar to squeak (I only dimly remember what squeak as a >> whole >> is though - smalltalk & easy multimedia I remember) >> > > Mainly, Squeak is a (relatively) recent, free implementation of Smalltalk. > > > The "persistent storage model" - the 'image' storing the whole system > (code, libs, data, whatever) - is part of the Smalltalk system since it's > first conception IIRC (even if some Smalltalk implementations - like GNU > Smalltalk - are more traditionnaly file-based and have no automatic > persistence). > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Mon Jun 16 10:54:19 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 16 Jun 2008 09:54:19 -0500 Subject: PEP 372 -- Adding an ordered directory to collections In-Reply-To: <48567688.7030306@ncee.net> References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <8ec4632c-2cae-40d1-ba5d-8d88854dae52@m73g2000hsh.googlegroups.com> <48567688.7030306@ncee.net> Message-ID: <1C14ED51B41947678D719807320547FD@AWA2> :) Yes, I thought about that even as I was writing that post. But I also said, "ParseResults implements quite a bit of additional behavior that would not be required or necessarily appropriate for odict." Even if odict existed, I think I would have needed ParseResults anyway (but using an odict internally might have simplified things for me, instead of the combined list and dict that I have now). -- Paul -----Original Message----- From: Shane Geiger [mailto:sgeiger at ncee.net] Sent: Monday, June 16, 2008 9:20 AM To: Paul McGuire Cc: python-list at python.org Subject: Re: PEP 372 -- Adding an ordered directory to collections Paul, You seem to be contradicting yourself. You may have never needed an odict, yet you seem to have implemented one on your own. Maybe you needed one but did not realize it? Shane > 5. The more I think and write about this, the more struck I am at the > similarity of odict and the ParseResults class in pyparsing. For > instance, in ParseResults, there is also support for dict-style and > list-style item referencing, and I chose to restrict some cases so > that using [] notation would not be ambiguous. You might want to add > pyparsing.ParseResults as another reference of current "odicts in the > wild" (although ParseResults implements quite a bit of additional > behavior that would not be required or necessarily appropriate for > odict). > > I vote +0 on this PEP - I've never personally needed an odict, but I > can see how some of the XML and ORM coding would be simplified by one. > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From http Tue Jun 3 04:57:11 2008 From: http (Paul Rubin) Date: 03 Jun 2008 01:57:11 -0700 Subject: Code correctness, and testing strategies References: Message-ID: <7x1w3esxp4.fsf@ruckus.brouhaha.com> Duncan Booth writes: > I made the mistake at one point when I was trying to sell the concept of > TDD telling the people I was trying to persuade that by writing the tests > up front it influences the design of the code. I felt the room go cold: > they said the customer has to sign off the design before we start coding, > and once they've signed it off we can't change anything. Usually the customer signs off on a functional specification but that has nothing to do with the coding style. Jacob makes a very good point that TDD influences coding style, for example by giving a strong motivation to separate computational code from I/O. But that is independent of the external behavior that the customer cares about. From rdh at new.rr.com Wed Jun 4 17:30:19 2008 From: rdh at new.rr.com (DataSmash) Date: Wed, 4 Jun 2008 14:30:19 -0700 (PDT) Subject: readline() & seek() ??? Message-ID: <12655f64-33b1-4ab0-b6fb-294bfd2fa8c6@d45g2000hsc.googlegroups.com> Hi group, I have a text file that contains thousands of lines and each line is 256 characters long. This is my task: For each line in the file, move to the 25th character, if the character is a "T", move to the 35th character of the line and read 5 characters from there. Capture these 5 characters and write them to a new text file, each 5 characters separated by a comma. I appreciate your help! R.D. From jason.scheirer at gmail.com Fri Jun 27 17:52:07 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Fri, 27 Jun 2008 14:52:07 -0700 (PDT) Subject: "method involving two objects" is that possible in Python? References: <8c8aec73-bd5b-4dfc-b91a-b100f3b9ddfa@m73g2000hsh.googlegroups.com> Message-ID: <075efde4-4f3b-48d1-a97f-fe068a2b81fb@j1g2000prb.googlegroups.com> On Jun 27, 2:41?pm, Kurda Yon wrote: > Hi, > > I just started to learn Python. I understood how one can create a > class and define a method related with that class. According to my > understanding every call of a methods is related with a specific > object. For example, we have a method "length", than we call this > method as the following "x.length()" or "y.length()" or "z.length()", > where z, y, and z are objects of the class. > > I am wandering if it is possible to create a method which is related > not with a single object (as in the previous example) but with a pare > of objects. For example, I want to have a class for vectors, and I > want to have a methods which calculate a dot product of two vectors. > One of the possibilities is to use __mul__ and that I calculated dot > product of "x" and "y" just as "x * y". However, I am wandering if I > can declare a method in a way that allows me to calculate dot product > as "dot(x,y)". > > Thank you in advance. def dot(x, y): ... class Vector: __mul__ = dot or class Vector: def __mul__(x, y): return dot(x, y) You can refer to the function defined as dot, assuming dot(x, y) returns some vector z. The first argument (x) will be bound to self in either case in any Vector instance. From dusan.smitran at gmail.com Wed Jun 11 08:40:03 2008 From: dusan.smitran at gmail.com (dusans) Date: Wed, 11 Jun 2008 05:40:03 -0700 (PDT) Subject: Dynamic HTML from Python Script References: <484f151c$0$5009$607ed4bc@cv.net> Message-ID: <96a4f695-d0ec-435d-9db1-849acdc0f9ab@p25g2000hsf.googlegroups.com> On Jun 11, 1:58 am, asdf wrote: > I have a python script whose output i want to dynamically display > on a webpage which will be hosted using Apache. How do I do that? > > thanks def index(req): return "Page" u cant run it on lighttpd also, which is much faster then Apache :P From rhamph at gmail.com Mon Jun 9 21:03:58 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 9 Jun 2008 18:03:58 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <6e6df35e-e641-44d9-9f56-c0732306eec2@q27g2000prf.googlegroups.com> Message-ID: <13db98b5-ed2e-45ef-97ec-ad3caeeed10e@j1g2000prb.googlegroups.com> On Jun 9, 2:52 pm, Fuzzyman wrote: > On Jun 9, 9:20 pm, Rhamphoryncus wrote: > > > > > On Jun 9, 5:33 am, Antoon Pardon wrote: > > > > On 2008-06-07, Rhamphoryncus wrote: > > > > > On Jun 6, 12:44 pm, The Pythonista wrote: > > > >> It's always been my understanding that you can't forcibly kill a thread > > > >> in Python (at least not in a portable way). The best you can do is > > > >> politely ask it to die, IIRC. > > > > > Inherently, the best you can do in most languages is ask them politely > > > > to die. Otherwise you'll leave locks and various other datastructures > > > > in an inconvenient state, which is too complex to handle correctly. > > > > The exception is certain functional languages, which aren't capable of > > > > having threads and complex state in the same sense. > > > > Well it would of course depend on what is considered asking politely? > > > > If one thread could cause an exception being thrown in an other thread, > > > would this be considered a polite way to ask? Would it be considered > > > an acceptable way? > > > The exception must not be raised until a point explicitly designed as > > safe is hit. Otherwise, any function that manipulates data you'll > > still use will potentially be buggered. Consider sys.stdout: codecs, > > buffering, lots to go wrong. > > Java and .NET both have ways of killing threads. They both work by > raising a 'ThreadAbort' (or similar) exception in the target thread. > In early implementations they both suffered from a similar problem. > You could protect locks (etc) by having a finally block that would > release all resources as needed - but what happens if the thread abort > exception is raised *inside* the finally block? > > Java responded by deprecating thread aborting. .NET responded by > ensuring that a thread abort exception would never be raised inside a > finally block - if that happened the exception would only be raised > once the code has left the finally block. > > Aborting threads in .NET can be extremely useful. Politely asking a > thread to die is no good if the task the thread is executing is > extremely coarse grained - it may not be able to respond to the > request for some time. If your code is structured correctly > (performing a long running background calculation for example) then > you may *know* that you can kill it without problems, but Python has > no native API to do this. So how does .NET deal with the sys.stdout corruption? Does it? If you've carefully written your code to use only safe primitives and local state (discarded if interrupted) then yes, it could be interruptible. At this point you could specially mark that block of code as safe, leaving the vast majority of other code unsafe by default. Then again, since you're going to the trouble of carefully designing and auditing your code you could just make it cancellable like blocking I/O should be - just by polling a flag at key points (and you're CPU-bound anyway, so it's not expensive.) The only place I know of that you *need* arbitrary interruption is hitting CTRL-C in the interactive interpreter. At this point it's a debugging tool though, so the risk of weirdness is acceptable. From hdante at gmail.com Sun Jun 1 14:27:26 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Sun, 1 Jun 2008 11:27:26 -0700 (PDT) Subject: SPOJ, Problem Code: sumtrian, Reducing time taken to solve. References: Message-ID: <6ae81d02-af69-40f5-835e-87f03ead8051@k30g2000hse.googlegroups.com> On Jun 1, 10:25?am, Shriphani wrote: > Hi, > > I was trying to solve the sumtrian problem in the SPOJ problem set > (https://www.spoj.pl/problems/SUMTRIAN/) and this is the solution I > submitted:http://pastebin.ca/1035867 > > The result was, "Your solution from 2008-06-01 15:13:06 to problem > SUMTRIAN, written in Python, > has exceeded the allowed time limit." > > I suspect that the first portion of my solution which looks at the > input, figures out the number of triangles and forms a list that > contains lists containing each row of the triangle, is wrong. I am not > too sure how to optimize it. I would appreciate help. > > Thanks, > Shriphani Palakodety First, you have to write a correct algorithm. Notice that your code doesn't correctly calculates the given sample input. Later, think about optimization. From hat at se-162.se.wtb.tue.nl Wed Jun 25 07:08:30 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 25 Jun 2008 13:08:30 +0200 Subject: python -regular expression - list element References: <62e21ec1-18f3-4572-b223-1b8a5c40688c@f63g2000hsf.googlegroups.com> Message-ID: On 2008-06-25, antar2 wrote: > I am a beginner in Python and am not able to use a list element for > regular expression, substitutions. > > list1 = [ 'a', 'o' ] > list2 = ['star', 'day', 'work', 'hello'] > > Suppose that I want to substitute the vowels from list2 that are in > list1, into for example 'u'. > In my substitution, I should use the elements in list1 as a variable. I read this as: for each string in list1, search (and replace with 'u') the matching substrings of each string in list2. Since list1 contains only strings instead of regular expressions, you could use string search and replace here. This makes matters much simpler. > I thought about: > > for x in list1: > re.compile(x) re.compile() returns a compiled version of the RE x. Above you don't save that value. Ie you do something similar to 1 + 2 * 3 where the value 7 is computed but not saved (and thus immediately discarded after computing by the Python interpreter). Use something like compiled_x = re.compile(x) instead. 'compiled_x' is assigned the computed compiled version of string x now. > for y in list2: > re.compile(y) The RE module finds matches in strings, not in compiled RE expressions. Since you want to search through y, it has to be a string. > if x in y: Here you test whether the letter in x occurs in y (both x and y are not changed by the re.compile() call, since that function does not alter its arguments, and instead produces a new result that you do not save). Maybe you thought you were checking whether a RE pattern match would occur. If so, it is not useful. Testing for a match takes about the same amount of time as doing the replacement. > z = re.sub(x, 'u', y) > but this does not work Instead of "re.sub(x, 'u', y)" you should use "compiled_x.sub('u', y)" since the former repeats the computation you already did with the re.compile(x). Otherwise, the code does work, and the new string (with replacements) is saved in "z". However, since you don't save that new value, it gets lost (overwritten). You should save "z" in the original list, or (recommended) create a new list with replaced values, and replace list2 after the loop. Sincerely, Albert From mr.opus.penguin at gmail.com Fri Jun 13 17:04:06 2008 From: mr.opus.penguin at gmail.com (mr.opus.penguin at gmail.com) Date: Fri, 13 Jun 2008 14:04:06 -0700 (PDT) Subject: Python 3000 vs. Python 2.x Message-ID: <2c299cdc-adcd-4540-b09f-43b4147e10ca@y21g2000hsf.googlegroups.com> As a new comer to Python I was wondering which is the best to start learning. I've read that a number of significant features have changed between the two versions. Yet, the majority of Python programs out in the world are 2.x and it would be nice to understand those as well. Thanks for all the help. Creosote, From geonomica at gmail.com Mon Jun 30 13:35:20 2008 From: geonomica at gmail.com (gianluca) Date: Mon, 30 Jun 2008 10:35:20 -0700 (PDT) Subject: ctypes - swig - pointer References: Message-ID: <58461c91-ed11-4153-8d74-429353e4fdd1@z72g2000hsb.googlegroups.com> On 30 Giu, 18:26, Jean-Paul Calderone wrote: > On Mon, 30 Jun 2008 09:13:42 -0700 (PDT), gianluca wrote: > >I've a problem with dll function colled with python/ctypes. My > >functions (C) requred a typedef int "value_type" in tree different > >way: > >same as value_type; - mydll.foo1(value_type) > >same as *value_type; - mydll.foo2(*value_type) > >same as **value_type; - mydll.foo3(**value_type) > > >How can pass it in python. If i do that: > >rules=POINTER(value_type) > >opr=rsl.StrengthOfRules(rules,10) > >R=POINTER(rules) > > POINTER takes a class and returns a new class which represents a pointer > to input class. > > pointer takes an instance and returns a new object which represents a > pointer to that instance. > > Jean-Paul so, if I write this: p=pointer(value_type) mydll.foo1(p) could be correct but python say me: TypeError: _type_ must have storage info what does mean? thank you gima From python at rgbaz.eu Mon Jun 16 03:49:00 2008 From: python at rgbaz.eu (Python.Arno) Date: Mon, 16 Jun 2008 09:49:00 +0200 Subject: Combining music or video files? In-Reply-To: <35e3302b-ba01-49b9-ac7a-0c6cc0df5f26@l28g2000prd.googlegroups.com> References: <4855d5a5$0$11609$607ed4bc@cv.net> <35e3302b-ba01-49b9-ac7a-0c6cc0df5f26@l28g2000prd.googlegroups.com> Message-ID: <8E9702DC-1F3E-44D1-9EDC-7949C5AF4301@rgbaz.eu> On 16 jun 2008, at 05:55, Jason Scheirer wrote: > On Jun 15, 7:53 pm, John Salerno wrote: >> Before I try this and destroy my computer :) I just wanted to see if >> this would even work at all. Is it possible to read a binary file >> such >> as an mp3 or an avi, put its contents into a new file, then read >> another >> such file and append its contents to this same new file as well, >> thereby >> making, for example, a single long video instead of two smaller ones? >> >> Thanks. > > This works with basic mpeg videos, but pretty much nothing else. > You're going to need some video editing software. you can't just edit mpeg (including mp3)... mpeg is a stream. it sets a "key" frame for the first frame followed by motion vectors from the changes from that frame until the next keyframe. If you cut in the middle of the vectors the keyframe is lost and the vector frames don;t make any sense anymore. avi is not a video codec, it's a container like quicktime. so it depends... I come from a Mac background and use quicktime a lot. there are some basic editing features that quicktime can do. And Apple has a nice quicktime python module in OSX. I bet there's something for windows too... best thing to do is convert the video o a framesequence and the audio to an uncompressed format like wav or aiff then combine in quicktime or cheers, Arno From gagsl-py2 at yahoo.com.ar Fri Jun 13 05:23:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Jun 2008 06:23:17 -0300 Subject: why can i still able to reproduce the SimpleHTTPServer bug which is said fixed 3 years ago? References: <4e307e0f0806130002u6795c55ejce02b71753df33ae@mail.gmail.com> Message-ID: En Fri, 13 Jun 2008 04:02:48 -0300, Leo Jay escribi?: > http://bugs.python.org/issue1097597 > > in my python 2.5.2, i still find these code in SimpleHTTPServer.py, > is that deliberate? According to http://bugs.python.org/issue839496 it should have been corrected, but apparently the patch was only applied to the 2.4 maintenance branch, not to the trunk. Both 2.5 and 2.6 have the same problem. 3.0 doesn't have this problem but probably it was fixed independently. -- Gabriel Genellina From wizzardx at gmail.com Sun Jun 1 06:46:28 2008 From: wizzardx at gmail.com (David) Date: Sun, 1 Jun 2008 12:46:28 +0200 Subject: method-wrapper? In-Reply-To: <597ecdea-bd88-429c-8b64-03efd4fb0d93@z72g2000hsb.googlegroups.com> References: <597ecdea-bd88-429c-8b64-03efd4fb0d93@z72g2000hsb.googlegroups.com> Message-ID: <18c1e6480806010346l36a8fb37y7cc0b4b67309770f@mail.gmail.com> > What is "method-wrapper"? Google turns up hardly any hits, same with > searching python.org. > It probably means that one object (A) contains another object (B). When you call certain methods on object A, those methods call methods in B, and return B's results to A's caller. >From that docstring: A.__call__() will run B() A.__cmp__(C) will run cmp(B, C) etc. In other words python code which runs A() will be running the equivalent of A.B(), where A can do other things besides calling B() if it wants to. David. From kay.schluehr at gmx.net Tue Jun 24 12:35:11 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 24 Jun 2008 09:35:11 -0700 (PDT) Subject: Python 3000 vs Perl 6 References: <89fbe834-68b7-49e6-8136-62dee53c2f40@t54g2000hsg.googlegroups.com> <7bad9ebd-81ab-48c4-854b-05f085e9d936@27g2000hsf.googlegroups.com> Message-ID: On 24 Jun., 13:19, bearophileH... at lycos.com wrote: > If you want to see an advanced language, you may take a look at > PyMeta, that's a bit of the future of the computer science:http://washort.twistedmatrix.com/ Er, no. The future of CS is also its past i.e. EBNF ;) From svasulu2 at gmail.com Sat Jun 28 02:59:00 2008 From: svasulu2 at gmail.com (chinu) Date: Fri, 27 Jun 2008 23:59:00 -0700 (PDT) Subject: EARN 10000$ IN EVERY MONTH ONLY DOING ONLINE JOB. Message-ID: <48009582-f78b-472e-8e07-12222b7c2ad0@i18g2000prn.googlegroups.com> GET + 1000$$$ @ MANY CASH OFFERS & ENJOY!!!!! Open the Site & Click the Banners = Easy forex + Get Web Hosting-Free Domains-Dating sites etc. site name: http://earnincomeblogspotcom.blogspot.com/ From mdw at distorted.org.uk Mon Jun 23 13:57:35 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Mon, 23 Jun 2008 17:57:35 +0000 (UTC) Subject: Using Python to run SSH commands on a remote server References: <03a078c8$0$3229$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Generally speaking, what tools would I use to do this? Is there a built-in > module for it? There's paramiko (q.g.). I can't personally vouch for it, but it seems popular... It seems to depend on a separate crypto library. > Is Telnet and SSH even the same thing? No. They're very different. -- [mdw] From geoff.bache at jeppesen.com Fri Jun 27 02:50:46 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Thu, 26 Jun 2008 23:50:46 -0700 (PDT) Subject: Windows process ownership trouble References: <3fcf363f-3685-4b7b-8ba5-1ffc32e58af7@m44g2000hsc.googlegroups.com> <990516b7-f7ef-464a-97d0-fd55a0354ab4@y21g2000hsf.googlegroups.com> <33847c9a-a816-48a1-a8c9-4209db9bf0b5@e53g2000hsa.googlegroups.com> <4863D586.8030004@timgolden.me.uk> Message-ID: <33aec7a9-b241-4bdd-8975-77759b2dc8b5@z66g2000hsc.googlegroups.com> Tim, I copied your code exactly from my browser and ran it, so I don't think there was a typo. I could upgrade to Python 2.5.2 I suppose to compare and contrast, but I need to support older Python versions anyway so it's a bit academic... Your speculation about garbage collection did set me going, however, and I discovered that the following code does work on my system, so now I have a functional workaround: import os import subprocess def runProcess(): f = open ("filename", "w") try: proc = subprocess.Popen ("blah", stdout=f) except OSError: f.close () runProcess() os.remove ("filename") So it seems that some things are only being garbage collected when the function exits, but not when the except clause exits or when the exception is thrown. Geoff From dullrich at sprynet.com Wed Jun 4 13:24:33 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Wed, 04 Jun 2008 12:24:33 -0500 Subject: re References: <6anvi4F38ei08U1@mid.uni-berlin.de> Message-ID: In article <6anvi4F38ei08U1 at mid.uni-berlin.de>, "Diez B. Roggisch" wrote: > David C. Ullrich schrieb: > > Actually using regular expressions for the first > > time. Is there something that allows you to take the > > union of two character sets, or append a character to > > a character set? > > > > Say I want to replace 'disc' with 'disk', but only > > when 'disc' is a complete word (don't want to change > > 'discuss' to 'diskuss'.) The following seems almost > > right: > > > > [^a-zA-Z])disc[^a-zA-Z] > > > > The problem is that that doesn't match if 'disc' is at > > the start or end of the string. Of course I could just > > combine a few re's with |, but it seems like there should > > (or might?) be a way to simply append a \A to the first > > [^a-zA-Z] and a \Z to the second. > > Why not > > ($|[\w])disc(^|[^\w]) > > I hope \w is really the literal for whitespace - might be something > different, see the docs. Thanks, but I don't follow that at all. Whitespace is actually \s. But [\s]disc[whatever] doesn't do the job - then it won't match "(disc)", which counts as "disc appearing as a full word. Also I think you have ^ and $ backwards, and there's a ^ I don't understand. I _think_ that a correct version of what you're suggesting would be (^|[^a-zA-Z])disc($|[^a-zA-Z]) But as far as I can see that simply doesn't work. I haven't been able to use | that way, combining _parts_ of a re. That was the first thing I tried. The original works right except for not matching at the start or end of a string, the thing with the | doesn't work at all: >>> test = compile(r'(^|[^a-zA-Z])disc($|[^a-zA-Z])') >>> test.findall('') [] >>> test.findall('disc') [('', '')] >>> test.findall(' disc ') [(' ', ' ')] >>> disc = compile(r'[^a-zA-Z]disc[^a-zA-Z]') >>> disc.findall(' disc disc disc') [' disc '] >>> disc.findall(' disc disc disc') [' disc ', ' disc '] >>> test.findall(' disc disc disc') [(' ', ' '), (' ', ' ')] >>> disc.findall(' disc disc disc') [' disc ', ' disc '] >>> disc.findall(' disc disc disc ') [' disc ', ' disc ', ' disc '] > Diez -- David C. Ullrich From theller at python.net Wed Jun 18 15:32:24 2008 From: theller at python.net (Thomas Heller) Date: Wed, 18 Jun 2008 21:32:24 +0200 Subject: Calling pcre with ctypes In-Reply-To: <947df973-8bae-4364-bf76-64a9a7d4a51f@s50g2000hsb.googlegroups.com> References: <947df973-8bae-4364-bf76-64a9a7d4a51f@s50g2000hsb.googlegroups.com> Message-ID: <6bt667F3c0tlpU1@mid.individual.net> moreati schrieb: > Recently I discovered the re module doesn't support POSIX character > classes: > > Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import re >>>> r = re.compile('[:alnum:]+') >>>> print r.match('123') > None > > So I thought I'd try out pcre through ctypes, to recreate pcredemo.c > in python. The c code is at: > http://vcs.pcre.org/viewvc/code/trunk/pcredemo.c?view=markup > > Partial Python code is below > > I'm stuck, from what I can tell a c array, such as: > int ovector[OVECCOUNT]; > > translates to > ovector = ctypes.c_int * OVECOUNT > > but when I pass ovector to a function I get the traceback > $ python pcredemo.py [a-z] fred > Traceback (most recent call last): > File "pcredemo.py", line 65, in > compiled_re, None, subject, len(subject), 0, 0, ovector, OVECOUNT > ctypes.ArgumentError: argument 7: : Don't > know how to convert parameter 7 > > What is the correct way to construct and pass ovector? 'ctypes.c_int * OVECOUNT' does not create an array *instance*, it creates an array *type*, comparable to a typedef in C. You can create an array instance by calling the type, with zero or more initializers: ovector = (ctypes.c_int * OVECOUNT)(0, 1, 2, 3, ...) Thomas From roy at panix.com Wed Jun 4 08:54:06 2008 From: roy at panix.com (Roy Smith) Date: Wed, 04 Jun 2008 08:54:06 -0400 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> <873antn9il.fsf@benfinney.id.au> <6ammujF38poe2U2@mid.uni-berlin.de> <87y75llp5x.fsf@benfinney.id.au> Message-ID: In article <87y75llp5x.fsf at benfinney.id.au>, Ben Finney wrote: > By definition, "private" functions are not part of the publicly > documented behaviour of the unit. Any behaviour exhibited by some > private component is seen externally as a behaviour of some public > component. You know the difference between theory and reality? In theory, there is none... Sometimes it's useful to test internal components. Imagine this class: class ArmegeddonMachine: def pushTheButton(self): "Destroy a random city" city = self._pickCity() self._destroy(city) def _pickCity(): cities = ['New York', 'Moscow', 'Tokyo', 'Beijing', 'Mumbai'] thePoorSchmucks = random.choice(cities) return 'New York' def _destroy(self, city): missle = ICBM() missle.aim(city) missle.launch() The only externally visible interface is pushTheButton(), yet you don't really want to call that during testing. What you do want to do is test that a random city really does get picked. You can do one of two things at this point. You can say, "But, that's not part of the externally visible interface" and refuse to test it, or you can figure out a way to test it. Up to you. From Lie.1296 at gmail.com Wed Jun 11 10:32:09 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 11 Jun 2008 07:32:09 -0700 (PDT) Subject: can't assign to literal References: Message-ID: On Jun 11, 2:53?am, maehhheeyy wrote: > this is stopping my program from running properly. is there something > wrong in my code when that happens? That simply means you did something like this: 'hello' = 'another' 123 = 'kilo' [12, 'asd] = 123 Sometimes it's not that obvious (although they're obvious for a more experienced programmers): for 123 in xrange(10): pass I think you've realized what you've done. And there is a pretty obvious signal that hints that you didn't know the basic syntax of python (or at least the basic syntax of the for-loop). From fernandes.fd at gmail.com Tue Jun 3 13:34:38 2008 From: fernandes.fd at gmail.com (Filipe Fernandes) Date: Tue, 3 Jun 2008 13:34:38 -0400 Subject: parser recommendation In-Reply-To: <686de663-94d2-4e8b-b079-197793d0a8cc@2g2000hsn.googlegroups.com> References: <686de663-94d2-4e8b-b079-197793d0a8cc@2g2000hsn.googlegroups.com> Message-ID: <11397a330806031034x36a85609m7415ddd27ccd3e6b@mail.gmail.com> On Tue, Jun 3, 2008 at 10:41 AM, Paul McGuire wrote: > If you learn both, you may find that pyparsing is a good way to > quickly prototype a particular parsing problem, which you can then > convert to PLY for performance if necessary. The pyparsing prototype > will be an efficient way to work out what the grammar "kinks" are, so > that when you get around to PLY-ifying it, you already have a clear > picture of what the parser needs to do. > Thanks (both Paul and Kay) for responding. I'm still looking at Trail in EasyExtend and pyparsing is very nicely objected oriented but PLY does seems to have the speed advantage, so I'm leaning towards PLY But I do have more questions... when reading the ply.py header (in 2.5) I found the following paragraph... # The current implementation is only somewhat object-oriented. The # LR parser itself is defined in terms of an object (which allows multiple # parsers to co-exist). However, most of the variables used during table # construction are defined in terms of global variables. Users shouldn't # notice unless they are trying to define multiple parsers at the same # time using threads (in which case they should have their head examined). Now, I'm invariably going to have to use threads... I'm not exactly sure what the author is alluding to, but my guess is that to overcome this limitation I need to acquire a thread lock first before "defining/creating" a parser object before I can use it? Has anyone ran into this issue....? This would definitely be a showstopper (for PLY anyway), if I couldn't create multiple parsers because of threads. I'm not saying I need more than one, I'm just not comfortable with that limitation. I have a feeling I'm just misunderstanding since it doesn't seem to hold you back from creating multiple parsers under a single process. filipe From arslanburney at gmail.com Fri Jun 13 03:24:26 2008 From: arslanburney at gmail.com (arslanburney at gmail.com) Date: Fri, 13 Jun 2008 00:24:26 -0700 (PDT) Subject: Plotting Graphs + Bestfit lines References: <1a919a2b-6430-4e2e-a190-2e00e43a6138@25g2000hsx.googlegroups.com> <022d382b-0b7b-4757-855a-f07019791fcc@d45g2000hsc.googlegroups.com> Message-ID: <05e67e40-db9c-4d85-94c1-f0e31dd5da38@27g2000hsf.googlegroups.com> On Jun 13, 12:13?pm, Peter Otten <__pete... at web.de> wrote: > arslanbur... at gmail.com wrote: > > Umm.... Tried this out too.... Laiken heres the error that this > > gives.. > > > Traceback (most recent call last): > > ? File "D:\Questions\Gradient and C\Gnuplot\Combining Best fit and > > Plotting\combasd.py", line 3, in > > ? ? combine.show_plots([(2,3), (4,8), (5,9), (6,2)], [(1,7), (3,3), > > (4,5), (5,6)], [(1,3), (3,10), (4,8), (7,9) ] ) > > ? File "D:\Questions\Gradient and C\Gnuplot\Combining Best fit and > > Plotting\combine.py", line 54, in show_plots > > ? ? gp = combine.plot( original, expected, actual) > > NameError: global name 'combine' is not defined > > > Still confused though i get the instance part ur trying to tell me. > > Sorry, it should have been > > def show_plots(original, expected, actual): > ? ? gp = plot( original, expected, actual) > ? ? raw_input("first") > ? ? gp = bestfit(expected) > ? ? raw_input("second") > ? ? gp = bestfit(actual) > ? ? raw_input("third") > > Peter Tried that out too. No error however, best fit lines still not being made on the graph. Only the 3 plot lines show up. From george.sakkis at gmail.com Tue Jun 3 18:59:38 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 3 Jun 2008 15:59:38 -0700 (PDT) Subject: Constructor re-initialization issue References: Message-ID: <00d47094-b687-48f2-9dc0-c92994a4f70c@y38g2000hsy.googlegroups.com> On Jun 3, 6:11 pm, pythonrept... at gmail.com wrote: > Hello all, > > I have come across this issue in Python and I cannot quite understand > what is going on. > > class Param(): > def __init__(self, data={}, condition=False): > if condition: > data['class']="Advanced" > print data > > In the previous example, I expect the variable data to be re- > initialized every time I construct an object type Param. However, when > I do the following: > > Param(condition=True) > Param(condition=False) > > The second call still prints {'class': 'Advanced'} > > Shouldn't data be initialized to {} since it is the default in > __init__? Why would the state of data be preserved between two > independent instantiations? > > Any help would be greatly appreciated. > > M. This must be by far the most FAQ.. unfortunately it seems it will remain for 3.x as well: http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects From bruno.42.desthuilliers at websiteburo.invalid Fri Jun 6 10:46:08 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 06 Jun 2008 16:46:08 +0200 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: References: Message-ID: <48494d73$0$31857$426a74cc@news.free.fr> Gabriel Rossetti a ?crit : > Larry Bates wrote: >> Gabriel Rossetti wrote: >>> Hello everyone, >>> >>> I had read somewhere that it is preferred to use >>> self.__class__.attribute over ClassName.attribute to access class >>> (aka static) attributes. I had done this and it seamed to work, until >>> I subclassed a class using this technique and from there on things >>> started screwing up. I finally tracked it down to >>> self.__class__.attribute! What was happening is that the child >>> classes each over-rode the class attribute at their level, and the >>> parent's was never set, so while I was thinking that I had indeed a >>> class attribute set in the parent, it was the child's that was set, >>> and every child had it's own instance! Since it was a locking >>> mechanism, lots of fun to debug... So, I suggest never using >>> self.__class__.attribute, unless you don't mind it's children >>> overriding it, but if you want a truly top-level class attribute, use >>> ClassName.attribute everywhere! >>> >>> I wish books and tutorials mentioned this explicitly.... >>> >>> Gabriel >> >> If you define a class instance variable with the same name as the >> class attribute, how would Python be able to distinguish the two? >> That is a feature not a problem. Getter looks for instance attribute, >> if one is not found it looks for a class attribute, and upwards. This >> behavior is used by Zope to do all sorts of neat stuff. >> >> -Larry Bates >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > A class instance variable, you must mean an instance attribute no? I think that's what he meant, yes. > If > that is so, then with just self.attribute? Maybe there is a concept that > I don't know about, The concept of name resolution (aka lookup) rules in Python, perhaps ? When you do obj.attribute, attribute is first looked for in the object, then in it's class, then in the parent classes. So yes, you can get a class (or parent class) attribute directly on the instance. Note that assignment on the instance (obj.attribute = value) will alway (computed attributes or other hooks excepted) create the attribute on the target, so if you have Class.attribute set, and then do obj = Class(); obj.attribute = 42, then obj.attribute will shadow Class.attribute. > I've studied class/static attributes and instance > attributes in my OOP classes. Forget about your OOP classes, mostly if it was in fact a Java or C++ class. Python's object model is very far away from what most courses present as "OOP". > Gabriel From apardon at forel.vub.ac.be Tue Jun 10 04:03:08 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Jun 2008 08:03:08 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> <49356862-86a6-4df4-886a-cd57827c1b1e@w8g2000prd.googlegroups.com> Message-ID: On 2008-06-09, Lie wrote: >> >> That seems strange to me. The and-or simulation that was offerd in the >> FAQ allowed for about the same kind of structures as the ternary >> operator in C and was used in the standard library IIRC. >> >> So the same unreadable was already possible to write, plus that it >> could cause bugs and had to be made even more unreadable in order >> to work correctly. Considering this it I find it odd that hurting >> readability was a motivation not to have it. > > In case you didn't notice, the and-or simulation is a hack, it is not > to be used by anyone writing real code (instead of for an entry to > Obfuscated Python Code Contest) to substitute it for inline if. If > inline if is "formalized", that means the language encourages the use > of inline if, which we don't want to have. Who is we? The last poll I know about had a majority in favor of a ternary operator. -- Antoon Pardon From martin at v.loewis.de Mon Jun 2 17:01:45 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 02 Jun 2008 23:01:45 +0200 Subject: robotparser behavior on 403 (Forbidden) robot.txt files In-Reply-To: <48441f05$0$17181$742ec2ed@news.sonic.net> References: <48441f05$0$17181$742ec2ed@news.sonic.net> Message-ID: <48445fba$0$7573$9b622d9e@news.freenet.de> > I just discovered that the "robotparser" module interprets > a 403 ("Forbidden") status on a "robots.txt" file as meaning > "all access disallowed". That's unexpected behavior. That's specified in the "norobots RFC": http://www.robotstxt.org/norobots-rfc.txt - On server response indicating access restrictions (HTTP Status Code 401 or 403) a robot should regard access to the site completely restricted. So if a site returns 403, we should assume that it did so deliberately, and doesn't want to be indexed. > A major site ("http://www.aplus.net/robot.txt") has their > "robots.txt" file set up that way. You should try "http://www.aplus.net/robots.txt" instead, which can be accessed just fine. Regards, Martin From johnjsal at gmailNOSPAM.com Sun Jun 15 23:13:34 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sun, 15 Jun 2008 23:13:34 -0400 Subject: newbie question: for loop within for loop confusion In-Reply-To: References: Message-ID: <4855da63$0$11599$607ed4bc@cv.net> takayuki wrote: > inchworm > inchworm P.S. Why does 'inchworm' only print twice? Or is that not the full output? From malaclypse2 at gmail.com Wed Jun 18 11:02:32 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 18 Jun 2008 11:02:32 -0400 Subject: Hrounding error In-Reply-To: References: Message-ID: <16651e80806180802k57c2a2fdra2a006d10786d152@mail.gmail.com> On Wed, Jun 18, 2008 at 1:47 AM, wrote: >>>> 234 - 23234.2345 > -23000.234499999999 > > This is not correct by my calculations. Python floating point operations use the underlying C floating point libraries which, in turn, usually rely on the hardware's floating point implementations. This Wikipedia article talks about how those values are usually stored and manipulated: http://en.wikipedia.org/wiki/IEEE_floating-point_standard So, which IEEE double precision floating point value would you like instead? As far as I understand it, these are your two choices: 'ba490c020f76d6c0' = -23000.234499999999 'bb490c020f76d6c0' = -23000.234500000002 Alternatively, investigate the Decimal module, but keep in mind that it can have the same sorts of issues, just on different numbers. Compare, for instance: >>> (1.0/3.0) * 3.0 1.0 >>> from decimal import Decimal >>> ( Decimal('1.0')/Decimal('3.0') ) * Decimal('3.0') Decimal("0.9999999999999999999999999999") >>> -- Jerry From stefan_ml at behnel.de Fri Jun 13 08:13:42 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 13 Jun 2008 14:13:42 +0200 Subject: Functionality similar to PHP's SimpleXML? In-Reply-To: <2cff2ee3-970d-4ba0-97e5-821c65fbf0d6@d1g2000hsg.googlegroups.com> References: <2cff2ee3-970d-4ba0-97e5-821c65fbf0d6@d1g2000hsg.googlegroups.com> Message-ID: <48526476.7000108@behnel.de> Phillip B Oldham wrote: > I'm going to throw together a quick project over the weekend: a > spider. I want to scan a website for certain elements. > > I come from a PHP background, so normally I'd: > - throw together a quick REST script to handle http request/responses Use the urllib/urllib2 module in the stdlib for GET/POST with parameters or lxml for simple page requests. > - load the pages into a simplexml object and > - run an xpath over the dom to find the nodes I need to test Use lxml. http://codespeak.net/lxml/ Stefan From gherron at islandtraining.com Mon Jun 2 18:33:12 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 02 Jun 2008 15:33:12 -0700 Subject: Cast list of objects to list of strings In-Reply-To: <48546eb1-11f3-4a88-b1ac-97bd485a1823@k30g2000hse.googlegroups.com> References: <48546eb1-11f3-4a88-b1ac-97bd485a1823@k30g2000hse.googlegroups.com> Message-ID: <48447528.9030604@islandtraining.com> bukzor wrote: > I have this function: > > def write_err(obj): > from sys import stderr > stderr.write(str(obj)+"\n") > > and I'd like to rewrite it to take a variable number of objects. > Something like this: > > def write_err(*objs): > from sys import stderr > stderr.write(" ".join(objs)+"\n") > > but I lose the property that the function works on any object. No you don't. If you were happy with printing the str(...) of a single objects, why not just printout the (concatenation) of the str(...) of each of many objects? stderr.write(" ".join([str(b) for b in objs])+"\n") Gary Herron > What's > the simplest way to fix this? In essence, I need to cast a list of > objects to a list of strings. I'd like to do just "str(objs)" but that > (obviously) doesn't quite do what I need. > > -- > http://mail.python.org/mailman/listinfo/python-list > From __peter__ at web.de Thu Jun 12 09:09:53 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Jun 2008 15:09:53 +0200 Subject: using re module to find " but not " alone ... is this a BUG in re? References: Message-ID: anton wrote: > I want to replace all occourences of " by \" in a string. > > But I want to leave all occourences of \" as they are. > > The following should happen: > > this I want " while I dont want this \" > > should be transformed to: > > this I want \" while I dont want this \" > > and NOT: > > this I want \" while I dont want this \\" > > I tried even the (?<=...) construction but here I get an unbalanced > paranthesis error. > > It seems tha re is not able to do the job due to parsing/compiling > problems for this sort of strings. > > > Have you any idea?? The problem is underspecified. Should r'\\"' become r'\\\"' or remain unchanged? If the backslash is supposed to escape the following letter including another backslash -- that can't be done with regular expressions alone: # John's proposal: >>> print re.sub(r'(?>> parts = re.compile("(\\\\.)").split('no " one \\", two \\\\"') >>> parts[::2] = [p.replace('"', '\\"') for p in parts[::2]] >>> print "".join(parts) no \" one \", two \\\" Peter From dullrich at sprynet.com Sat Jun 7 09:48:13 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Sat, 07 Jun 2008 08:48:13 -0500 Subject: how to build a street with more than 1 house ? References: Message-ID: On Sat, 07 Jun 2008 00:45:07 +0200, Stef Mientki wrote: >hello, > >In the code below, I can build a large street like this: > large_street = house * 25 >but not a small street. like this: > small_street = 5 * house > >Why is this different ? Because you're multiplying on the left in one case and on the right in the other. You realize that house*5 should work, right? >And more interesting, how do I get the right results ? > >thanks, >Stef Mientki > >class type_house ( object ) : > def __init__( self, front_doors = 1 ) : > self.front_doors = front_doors > def __mul__ ( self, b ) : > return type_house ( self.front_doors * b ) The reason house*25 works is that the __mul__ method says what it should be. If you want 5*house to work you need a __rmul__. Nothing in Python automatically makes a*b the same as b*a; when it sees 5*house first it checks 5 to see whether it knows whether it knows what 5*house should be (no, 5 never heard of this house thing), then it checks house to see if it knows what 5*house should be (no, house has no __rmul__). The simplest thing is just to define __rmul__ to make multiplication commuttative: def __rmul__(self, b): """Defines what b*self should return.""" return self*b Now 5*house calls __rmul__, which returns house*5. That in turn calls __mul__, which returns what you want. And some day when you modify __mul__ (in a subclass?) you won't need to worry about making the same change to __rmul__. >house = type_house () >large_street = house * 25 >print large_street.front_doors >small_street = 5 * house >print small_street.front_doors David C. Ullrich From fetchinson at googlemail.com Thu Jun 12 14:25:54 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 12 Jun 2008 11:25:54 -0700 Subject: howto split string with both comma and semicolon delimiters In-Reply-To: <3e2540ab-1d2a-45a5-a5b6-3f7ae7a4efac@x35g2000hsb.googlegroups.com> References: <3e2540ab-1d2a-45a5-a5b6-3f7ae7a4efac@x35g2000hsb.googlegroups.com> Message-ID: > howto split string with both comma and semicolon delimiters? > > i.e. (for example) get ['a','b','c'] from string "a,b;c" > > I have tried s.split(',;') but it don't work A very pedestrian solution would be: def multisplit( s, seps ): words = [ ] word = '' for char in s: if char in seps: if word: words.append( word ) word = '' else: word += char if word: words.append( word ) return words Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From gagsl-py2 at yahoo.com.ar Fri Jun 13 03:36:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Jun 2008 04:36:17 -0300 Subject: best way to create a timer/alarm References: <17815502.post@talk.nabble.com> Message-ID: En Fri, 13 Jun 2008 02:42:53 -0300, Alexnb escribi?: > I am wondering what is the best way to create a timer, like an alarm, > once it > reaches a time, it triggers an event. I have a way of doing this but it > seems like it isn't good at all. If it helps at all I am using a Tkinter, > but that probably doesn't mean much. Actually it *is* very important - such things are done in very different ways on different GUI libraries. > The way I was doing it was using a > while loop, and just saying while current time is not = to trigger time, > do > nothing, and when it is, do event. Doing so makes your application irresponsive (frozen) until the time elapses. Use the "after" method; see -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri Jun 13 03:05:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Jun 2008 04:05:06 -0300 Subject: FPC: Exception : Unknown Run-Time error : 210 References: Message-ID: En Thu, 12 Jun 2008 12:38:34 -0300, Sa?a Bistrovi? escribi?: > FPC: Exception : Unknown Run-Time error : 210 Wrong list... you are probably looking for http://lists.freepascal.org/mailman/listinfo/fpc-pascal/ -- Gabriel Genellina From i.i at i.i Sun Jun 22 14:24:25 2008 From: i.i at i.i (Josip) Date: Sun, 22 Jun 2008 20:24:25 +0200 Subject: Storing value with limits in object References: <6tednUvC9-jDxMPVnZ2dnUVZ_hGdnZ2d@comcast.com> Message-ID: > Why not make it a function? > > function assignLimited(value, vmin, vmax): > value = max(vmin, value) > value = min(vmax, value) > return value > > > a = assignLimited(7, 0, 10) > > > Seems like it solves your problem relatively cleanly. > Note: I also removed min/max variables because they would mask the > built-in min/max functions. > > -Larry Yes, the simple solution is often the best. Still, I'm going for object oriented solution because I want the value and it's limits to be kept together as I'll have many such values with different limits. Storing all the limits in caller namespace is not really an option. From omer at no-log.org Thu Jun 19 12:10:43 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Thu, 19 Jun 2008 18:10:43 +0200 Subject: Installing Python 3.0 no probs running 2.5 at the same time? In-Reply-To: <4eb587db-ccd2-4d98-bfc0-abfda4edc4fc@i76g2000hsf.googlegroups.com> References: <4eb587db-ccd2-4d98-bfc0-abfda4edc4fc@i76g2000hsf.googlegroups.com> Message-ID: <200806191810.43661.omer@no-log.org> Le Thursday 19 June 2008 17:32:10 cirfu, vous avez ?crit?: > Can I install 3.0 without breaking 2.5? Meaning does it overwrite some > bindings or something or it just installs 3.0 in a different folder as > a completely separate program? It's OK for any version having different major/minor version numbers (so 2.4 + 2.5 is OK, but _not_ 2.4.2 + 2.4.4). Everything go in different directories, and a version specific executable is also installed (python2.5, python3.0...). The main one (python) is just a link to one of them. -- C?dric Lucantis From tedpottel at gmail.com Fri Jun 6 16:14:52 2008 From: tedpottel at gmail.com (tedpottel at gmail.com) Date: Fri, 6 Jun 2008 13:14:52 -0700 (PDT) Subject: Trying to install mysql lib for python Message-ID: <7a963eaa-2468-4d3d-bf24-f05d8bd57937@f36g2000hsa.googlegroups.com> Hi How do I install mysql db libray for python? I went to source forg and downloaded the following zip folder MySQL_python-1.2.2-py2.4-win32 I open the folder and looked inside did not see any directions. Help From dinilkarun at gmail.com Fri Jun 6 06:52:27 2008 From: dinilkarun at gmail.com (Dinil Karun) Date: Fri, 6 Jun 2008 16:22:27 +0530 Subject: Convert Word .doc to Acrobat .pdf files Message-ID: <1dc26c3a0806060352k442475ccp6716b713268c161a@mail.gmail.com> hi, I am using the below code but i am getting a error saying pyUno module not found. can u please help. Regards Dinil ------------------------X----------------------X_---------------------- I wrote a script which uses OpenOffice. It can convert and read a lot of formats. #!/usr/bin/env python #Old: !/optlocal/OpenOffice.org/program/python # (c) 2003-2006 Thomas Guettler http://www.tbz-pariv.de/ # OpenOffice1.1 comes with its own python interpreter. # This Script needs to be run with the python from OpenOffice1: # /opt/OpenOffice.org/program/python # Start the Office before connecting: # soffice "-accept=socket,host=localhost,port=2002;urp;" # # With OpenOffice2 you can use the default Python-Interpreter (at least on SuSE) # # Python Imports import os import re import sys import getopt default_path="/usr/lib/ooo-2.0/program" sys.path.insert(0, default_path) # pyUNO Imports try: import uno from com.sun.star.beans import PropertyValue except: print "This Script needs to be run with the python from OpenOffice.org" print "Example: /opt/OpenOffice.org/program/python %s" % ( os.path.basename(sys.argv[0])) print "Or you need to insert the right path at the top, where uno.py is." print "Default: %s" % default_path raise sys.exit(1) extension=None format=None def usage(): scriptname=os.path.basename(sys.argv[0]) print """Usage: %s [--extension pdf --format writer_pdf_Export] files All files or directories will be converted to HTML. You must start the office with this line before starting this script: soffice "-accept=socket,host=localhost,port=2002;urp;" If you want to export to something else, you need to use give the extension *and* the format. For a list of possible export formats see http://framework.openoffice.org/files/documents/25/897/filter_description.html or /opt/OpenOffice.org/share/registry/data/org/openoffice/Office/TypeDetection.xcu or grep -ri MYEXTENSION /usr/lib/ooo-2.0/share/registry/modules/org/openoffice/TypeDetection/ the format is Message-ID: brechmos writes: >Hi, >I have been using PHP the last while and in particular strtotime. >What I want to replicate is finding the second or fourth Monday of the >next month. In PHP with strtotime it is easy (strtotime("second >Monday", strtotime("next month"), but I can't find an easy way to do >it in Python. I have seen DateUtil, but it seems to be able to do >only the simpler parsing (could be wrong). >Any other ideas? http://code-bear.com/code/parsedatetime/ >>> import parsedatetime.parsedatetime as pdt >>> p = pdt.Calendar() >>> p.parse('next month') ((2008, 7, 1, 9, 0, 0, 1, 183, -1), 1) Eddie From Lie.1296 at gmail.com Wed Jun 18 06:47:13 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 18 Jun 2008 03:47:13 -0700 (PDT) Subject: dict order References: Message-ID: <25f4d43d-1fb7-47f9-82b6-1b82ad42e73a@j33g2000pri.googlegroups.com> On Jun 18, 4:22?pm, Robert Bossy wrote: > Hi, > > I wish to know how two dict objects are compared. By browsing the > archives I gathered that the number of items are first compared, but if > the two dict objects have the same number of items, then the comparison > algorithm was not mentioned. > > Note that I'm not trying to rely on this order. I'm building a > domain-specific language where there's a data structure similar to > python dict and I need an source of inspiration for implementing > comparisons. > > Thanks > RB Why not consider them as equal, it's simple and is basically telling people not to rely on them because one day A might be lower than B and the other day, A and B that hasn't been modified at all might switch sides without warning. Or you could just use any arbitrary way of comparison (Python Zen: In the face of ambiguity, refuse the temptation to guess.). From john.dohn.john at gmail.com Fri Jun 6 08:22:38 2008 From: john.dohn.john at gmail.com (John Dohn) Date: Sat, 7 Jun 2008 00:22:38 +1200 Subject: How to kill a thread? In-Reply-To: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> Message-ID: <608040960806060522m32c4e6abp836684b15c98aac3@mail.gmail.com> On Fri, Jun 6, 2008 at 10:30 PM, John Dohn wrote: > Hi there, > > How can I kill a threading.Thread subclass from MainThread? At the end I did: def run(self): while True: if exit_event.isSet(): # Thread exiting return try: data = q_in.get(timeout = .5) except Queue.Empty: continue # ... process data And then in the MainThread I do exit_event.set() and wait for all threads to exit. It's a pretty awkward solution but works. BTW Guys, is something like Thread.kill() planned for the future? Or is there a reason not to have it? Thanks JD -------------- next part -------------- An HTML attachment was scrubbed... URL: From Russ.Paielli at gmail.com Mon Jun 9 17:39:03 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 9 Jun 2008 14:39:03 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <4847d39d$0$7614$426a74cc@news.free.fr> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> <484cf5f6$0$15495$426a74cc@news.free.fr> <127975a3-b3d9-4799-9673-b292ec8d37e3@x19g2000prg.googlegroups.com> <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> Message-ID: <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> On Jun 9, 2:10 pm, "bruno.desthuilli... at gmail.com" wrote: > But if it takes 6 month to get the mentioned developer to release > something I can use, I'm screwed up. Fine. I've lost track of how many times I've said this now, but my suggestion for a "priv" keyword allowed for "indirect" access to private data through some name-mangling scheme. That could be your temporary fix while you are waiting for the developer to release a corrected version. And even if that option were not available, you could simply open up the relevant source file in the editor of your choice and remove the offending "priv" declaration. I completely fail to see how you are "screwed." Sorry, but when I have to keep repeating the same basic points over and over, I can't help but think I might be wasting my time. From gabriela.soares.fcup at gmail.com Wed Jun 11 09:04:35 2008 From: gabriela.soares.fcup at gmail.com (Gabriela Soares) Date: Wed, 11 Jun 2008 14:04:35 +0100 Subject: python gui In-Reply-To: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> References: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> Message-ID: <9d68e4e90806110604n29dd847ah729a02b4398a3072@mail.gmail.com> Greetings, I want to make a dynamic dashboard, something like: http://examples.adobe.com/flex3/labs/dashboard/main.html# but using python. Is it possible ? Thanks in advance. Best regards, Gabriela Soares. -------------- next part -------------- An HTML attachment was scrubbed... URL: From none at this.time Fri Jun 6 14:44:33 2008 From: none at this.time (The Pythonista) Date: Fri, 06 Jun 2008 14:44:33 -0400 Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> Message-ID: It's always been my understanding that you can't forcibly kill a thread in Python (at least not in a portable way). The best you can do is politely ask it to die, IIRC. -- code.py: A blog about life, the universe, and Python http://pythonista.wordpress.com ** Posted from http://www.teranews.com ** From johnjsal at NOSPAMgmail.com Fri Jun 27 12:09:59 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 27 Jun 2008 12:09:59 -0400 Subject: How do web templates separate content and logic? Message-ID: <486510f7$0$3007$c3e8da3@news.astraweb.com> I've been doing some research on web templates, and even though I read that they help enforce the MVC pattern, I don't really understand how they are keeping content and logic separated. Layout is easy, it's just not there as far as I can see, and CSS can be used for that. But when you have a templating system that mixes HTML and Python code, how is this helping to keep things separate? It seems to be the same issue that some people have with PHP (that it is too integrated with the HTML, rather than being separate). Of course, I suppose whether or not any of this matters depends on if you are a web designer or a programmer, but am I missing something about templates, or is it really the case that they, more or less by definition, combine content and logic? Thanks. From bsagert at gmail.com Tue Jun 10 11:56:53 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Tue, 10 Jun 2008 08:56:53 -0700 (PDT) Subject: Python doesn't understand %userprofile% Message-ID: In xp when I try os.path.getmtime("%userprofile/dir/file%") Python bites back with "cannot find the path specified" Since my script has to run on machines where the username is unspecified I need a fix. Thanks in advance. From s0suk3 at gmail.com Wed Jun 25 23:30:38 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Wed, 25 Jun 2008 20:30:38 -0700 (PDT) Subject: Working with the Windows Registry References: <49beca2a-9d6c-40a2-a7c3-bf1cf376df0a@l28g2000prd.googlegroups.com> Message-ID: On Jun 25, 9:48 pm, teh_sAbEr wrote: > Hi everybody. I'm trying to write a script that'll change desktop > wallpaper every time its run. Heres what I've gotten so far: > > #random wallpaper changer! > import _winreg > from os import walk > from os.path import exists > from random import randint > > #first grab a registry handle. > handle = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,'Control Panel > \Desktop',_winreg.KEY_SET_VALUE) > > def GenerateListOfWallpapers(): > targetDir = 'C:\Documents and Settings\Enrico Jr\My Documents\Jr > \'s Wallpapers' > fileNames = [] > filePaths = [] > if exists(targetDir): > #proceed to make the list of files > for x,y,z in walk(targetDir): > for name in z: > fileNames.append(name) > for item in fileNames: > filePaths.append(targetDir + '\\' + item) > return filePaths > > def RandomlySelectWallpaper(filePaths): > index = randint(0,len(filePaths)-1) > RandomlySelectedWallpaper = filePaths[index] > return RandomlySelectedWallpaper #it should be a string... > > #now to edit the wallpaper registry key > newWallpaper = RandomlySelectWallpaper(GenerateListOfWallpapers()) > print "Registry Handle Created." > print "Random wallpaper selected." > _winreg.SetValueEx(handle,'ConvertedWallpaper', > 0,_winreg.REG_SZ,newWallpaper) > print "New wallpaper value set." > > The problem is, every time I run it, I get an "Access Denied" error > when it tries to execute > _winreg.SetValueEx(), even though i've opened the key with the > KEY_SET_VALUE mask like it said in the help docs. Could there be > another problem or a better way to do this? Note the line #first grab a registry handle. handle = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Control Panel \Desktop', _winreg.KEY_SET_VALUE) OpenKey() takes four arguments: (1) The Registry key handle or one of the predefined constants, (2) the string containing the subkey to open, (3) the 'res' (which I don't know what is :), and the 'sam', which is the access mask (KEY_SET_VALUE, in this case). You are only passing three arguments, so the access mask is going to the 'res' argument instead of the 'sam' argument. Pass instead 0 as the res: handle = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Control Panel\Desktop', 0, _winreg.KEY_SET_VALUE) Regards, Sebastian From wuwei23 at gmail.com Thu Jun 5 20:58:19 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 5 Jun 2008 17:58:19 -0700 (PDT) Subject: Guide to organizing modules? References: <1611a070-35f9-4072-b95f-ab592820f516@c65g2000hsa.googlegroups.com> Message-ID: <5b68316f-b2d6-4cec-bb8e-c9ed55202842@v26g2000prm.googlegroups.com> On Jun 6, 10:32 am, bukzor wrote: > In summary: are there any good (or official) guidelines for how to > organize and separate python functions and classes into modules? Hey bukzor, Are you familiar with the concept of packages in Python? http://docs.python.org/tut/node8.html#SECTION008400000000000000000 That should allow you to keep all of your scriptlets as separate files while still having the advantage of keeping them in a single namespace for importing. (But if you know this already, don't mind me....) From george.sakkis at gmail.com Thu Jun 12 02:08:24 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 11 Jun 2008 23:08:24 -0700 (PDT) Subject: Producer-consumer threading problem References: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> <680969c8-dfb2-4021-b33c-790c5de2a849@27g2000hsf.googlegroups.com> Message-ID: <61046d91-2512-4cb4-b36a-1af690c5c219@c65g2000hsa.googlegroups.com> On Jun 11, 3:07 pm, Carl Banks wrote: > On Jun 10, 11:33 pm, George Sakkis wrote: > > > I pasted my current solution athttp://codepad.org/FXF2SWmg. Any > > feedback, especially if it has to do with proving or disproving its > > correctness, will be appreciated. > > It seems like you're reinventing the wheel. The Queue class does all > this, and it's been thorougly battle-tested. Synchronized queues are an extremely useful data structure in many situations. The producer/consumer paradigm however is a more general model and doesn't depend on any specific data structure. > So first of all, can you tell us why the following wouldn't work? It > might help us understand the issue you're facing (never mind the > produce and consume arguments for now--I'll cover that below). > > def iter_consumed(items): > q = Queue.Queue() > sentinel = object() > def produce_all() > for item in items: > q.put() > q.put(sentinel) > producer = threading.Thread(target=produce_all) > producer.start() > try: > while True: > item = q.get() > if item is sentinel: > return > yield item > finally: > # for robustness, notify producer to wrap things up > # left as exercise > producer.join() As it is, all this does is yield the original items, but slower, which is pretty much useless. The whole idea is to transform some inputs to some outputs. How exactly each input is mapped to an output is irrelevant at this point; this is the power of the producer/consumer model. Produce might mean "send an email to address X" and consume might mean "wait for an automated email response, parse it and return a value Y". No queue has to be involved; it *may* be involved of course, but that's an implementation detail, it shouldn't make a difference to iter_consumed(). If you replace "q.push"/"q.pop" with "produce"/"consume" respectively and make the last two parameters, you're much closer to my idea. What's left is getting rid of the sentinel, since the producer and the consumer may have been written independently, not aware of iter_consumed. E.g. for the email example, all producers and consumers (there may be more than one) must agree in advance on a "sentinel email". For a given situation that might not be a big issue, but then again, if iter_consumed() is written once without assuming a sentinel, it makes life easier for all future producers and consumers. > If you want to customize the effect of getting and putting, you can > subclass Queue and override the _get and _put methods (however, last > time I checked, the Queue class expects _put to always add an item to > the internal sequence representing the queue--not necessarily to the > top--and _get to always remove an item--not necessarily from the > bottom). Assuming that you're talking about the stdlib Queue.Queue class and not some abstract Queue interface, extending it may help for limited customization but can only get you so far. For instance the producer and the consumer may not live in the same address space, or even in the same machine. > One issue from your function. This line: > > done_remaining[1] += 1 > > is not atomic, but your code depends on it being so. No, it doesn't; it is protected by the condition object. George From bkustel at gmail.com Sun Jun 15 04:04:37 2008 From: bkustel at gmail.com (bkustel at gmail.com) Date: Sun, 15 Jun 2008 01:04:37 -0700 (PDT) Subject: marshal.dumps quadratic growth and marshal.dump not allowing file-like objects Message-ID: I'm stuck on a problem where I want to use marshal for serialization (yes, yes, I know (c)Pickle is normally recommended here). I favor marshal for speed for the types of data I use. However it seems that marshal.dumps() for large objects has a quadratic performance issue which I'm assuming is that it grows its memory buffer in constant increments. This causes a nasty slowdown for marshaling large objects. I thought I would get around this by passing a cStringIO.StringIO object to marshal.dump() instead but I quickly learned this is not supported (only true file objects are supported). Any ideas about how to get around the marshal quadratic issue? Any hope for a fix for that on the horizon? Thanks for any information. From grante at visi.com Mon Jun 23 16:12:59 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 23 Jun 2008 15:12:59 -0500 Subject: Using Python to run SSH commands on a remote server References: <03a078c8$0$3229$c3e8da3@news.astraweb.com> Message-ID: <_pSdnUkh3Z5Wnv3VnZ2dnUVZ_sninZ2d@posted.visi> On 2008-06-23, John Salerno wrote: > Generally speaking, what tools would I use to do this? In shell scripts I use expect to automate ssh stuff, so I would probably give pyexpect or pexpect a try: http://sourceforge.net/projects/pexpect/ > Is there a built-in module for it? I looked at the telnetlib > module, but the documentation wasn't really complete enough > for me to get a good idea of it. Is Telnet and SSH even the > same thing? Not even close. > Basically, I want to write a script that will automate the > process of making all .py files on my web server executable > (chmod 755, or something similar). I'd probably just write an expect script: http://expect.nist.gov/ -- Grant Edwards grante Yow! Is a tattoo real, like at a curb or a battleship? visi.com Or are we suffering in Safeway? From kyosohma at gmail.com Wed Jun 4 14:01:28 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 4 Jun 2008 11:01:28 -0700 (PDT) Subject: how to combine 2 program? References: Message-ID: On Jun 4, 8:53?am, a... at cs.its.ac.id wrote: > i am a newbe in pyhton. > i am using "Twisted Network Programming Essentials By Abe Fettig" as my > tutorial. in that tutorial, i found 2 example, IMAPDOWNLOAD.py and > requesthandler.py > > my problem is how to combine those program become one program, so that i > can input the imapdownload inputs via web? > thanks, ?Any guidance in this would be greatly appreciated... I recommend re-posting to the Twisted mailing list: http://twistedmatrix.com/trac/wiki/TwistedCommunity Mike From georgeoliverGO at gmail.com Sat Jun 28 13:25:10 2008 From: georgeoliverGO at gmail.com (George Oliver) Date: Sat, 28 Jun 2008 10:25:10 -0700 (PDT) Subject: 2D online multiplayer framework? References: <6dc6195b-b8a0-42a9-a982-3a4b70943c24@r37g2000prm.googlegroups.com> Message-ID: <49e9fbe6-26de-40f0-ae03-fb559499e450@h1g2000prh.googlegroups.com> On Jun 28, 9:04 am, Gary Herron wrote: > > Pyglet is my favorite: http://www.pyglet.org/ > > Twisted might be fine for the "online multiplayer" parts, but really if > you want a 2D/3D real-time game, start with a game framework. > > Gary Herron Thanks C?dric and Gary for the suggestions, I'm familiar with all of those. So a good workflow for a graphical online game is to make the game first and just plan for the incoming connections without knowing how they will be done exactly? My only experience with networked games is muds, where usually you do the opposite -- sockets first. From none at this.time Fri Jun 6 14:28:37 2008 From: none at this.time (The Pythonista) Date: Fri, 06 Jun 2008 14:28:37 -0400 Subject: Change in interactive interpreter? Message-ID: I remember the interactive interpreter used to define the name _ to return the value of the last expression that was evaluated. However, I tried it just today and got a NameError. Is this a change in the interpreter or is there a configuration option I need to set to enable it? Thanks! -- code.py: A blog about life, the universe, and Python http://pythonista.wordpress.com ** Posted from http://www.teranews.com ** From tew24 at spam.ac.uk Thu Jun 12 05:21:40 2008 From: tew24 at spam.ac.uk (Tom Wright) Date: Thu, 12 Jun 2008 10:21:40 +0100 Subject: matplotlib question References: <485079a0$0$11641$607ed4bc@cv.net> Message-ID: asdf wrote: > basically I need to plot a graph of data vs time. However when i use > matplotlib the hr:min tick marks come out very close together and > appear jumbled. You need to look up the matplotlib.dates package - it's covered briefly in the tutorial at http://matplotlib.sourceforge.net/tutorial.html At a guess, you want something along the lines of this... from matplotlib.dates import YearLocator, MonthLocator, WeekdayLocator, \ DayLocator, HourLocator, MinuteLocator, SecondLocator, \ DateFormatter subplot.xaxis.set_major_locator(HourLocator(range(0,24,6))) subplot.xaxis.set_major_formatter(DateFormatter("%a %H:%M")) subplot.xaxis.set_minor_locator(HourLocator(range(0,24,1))) ...but you'll probably need to look up the documentation to get the details to suit what you need. Hope that helps! -- I'm at CAMbridge, not SPAMbridge From eddieatter at gmail.com Wed Jun 11 20:21:23 2008 From: eddieatter at gmail.com (agent E 10) Date: Wed, 11 Jun 2008 17:21:23 -0700 (PDT) Subject: Brand New! References: <7f1828bf-ebe7-4111-bc59-70d125facb0a@d26g2000prg.googlegroups.com> <1208324917.7339.10.camel@paul-laptop> Message-ID: <76a2afe1-ab71-4e6c-b1db-dcf264ae6e69@g16g2000pri.googlegroups.com> On Apr 18, 12:47?pm, Nick Stinemates wrote: > On Wed, Apr 16, 2008 at 07:48:37AM +0200, Paul Scott wrote: > > > On Wed, 2008-04-16 at 02:35 -0300, Gabriel Genellina wrote: > > > I'm unsure if teaching Javascript, VBScript and Python at the same time is ? > > > a good thing, I'd think one would get a language soup and mix all the ? > > > concepts, but if it works for you, go ahead. > > > For other resources, see the beginners section in the Python wiki: ? > > >http://wiki.python.org/moin/BeginnersGuide > > > Well, as an example, I learnt Python to a decent level of competency in > > 2 days. I looked through the Dive into Python tuts, and then had a look > > at the Python GUI FAQ (Which didn't really help much, as I started with > > a GTK based GUI app). A little bit of Googling and a couple of questions > > to this list gave me everything that I needed to roll out a pretty > > decent application in 5 days. Oh, and just by the way, I am _not_ a > > Computer Scientist or anything, I am a botanist, which means that if I > > can do that, just about anyone that can read can do it. > > > Python has been long on my list of TODO's, and now, finally, it is > > there. I have immensely enjoyed it so far, and will continue to tinker > > well into the future. > > > --Paul > > I think that's wonderful! > > I think problem solving language independent. As long as you can break down what you need to do and conceptualize. You must have learned to do with with botany, so programming came natural :) > > -- > Nick Stinemates (n... at stinemates.org)http://nick.stinemates.org- Hide quoted text - > > - Show quoted text - I am using a windows computer. thanks for all the information, it was very helpful! -agent E 10 From rdabane at gmail.com Tue Jun 3 21:04:40 2008 From: rdabane at gmail.com (rdabane at gmail.com) Date: Tue, 3 Jun 2008 18:04:40 -0700 (PDT) Subject: Help need with subprocess communicate References: <0312b7e9-bffe-4360-bf3a-f5b3b26d243d@l64g2000hse.googlegroups.com> Message-ID: <530ccda9-818e-4abe-9f82-0720e27c48fd@z72g2000hsb.googlegroups.com> On Jun 3, 5:42 pm, Daniel Klein wrote: > On Tue, 3 Jun 2008 14:04:10 -0700 (PDT), rdab... at gmail.com wrote: > >I'm trying to perform following type of operation from inside a python > >script. > >1. Open an application shell (basically a tcl ) > >2. Run some commands on that shell and get outputs from each command > >3. Close the shell > > >I could do it using communicate if I concatenate all my commands > >( separated by newline ) and read all the output in the end. So > >basically I could do following sequence: > >1. command1 \n command2 \n command 3 \n > >2. Read all the output > > >But I want to perform it interactively. > >1. command1 > >2. read output > >3. command2 > >4. read output ...... > > >Following is my code: > > >from subprocess import * > >p2 = Popen('qdl_tcl',stdin=PIPE,stdout=PIPE) > >o,e = p2.communicate(input='qdl_help \n qdl_read \n > >qdl_reg_group_list ') > > >Please suggest a way to perform it interactively with killing the > >process each time I want to communicate with it. > > Use > stdin.write(command + '\n') > to 'send' data to the sub-process. > > Use > stdout.readline() > to 'receive' data from the sub-process. > > But to use this requires you open the subprocess with: > > universal_newlines = True > > It assumes that 'command' will be sent with '\n' and received data will come > in a line at a time. Your Python program needs to know what to expect; you > are in control. > > Alternatively, you can use std.write() and stdout.read() (without > universal_newlines) but this means you need to create your own IPC protocol > (like netstrings). > > Hope this helps, > > Daniel Klein Hi Daniel, Thanks for your reply.. I've done exactly as you suggested...but I'm still having problem with the read...it just gets stuck in the read ( I think because its a blocking read...) following is a simple example of problem..please try running it ... from subprocess import * p2 = Popen('python',shell=True,stdin=PIPE,stdout=PIPE,universal_newlines=True) for i in range(10): p2.stdin.write('print 10'+'\n') # Write Command o = p2.stdout.readline() # Read Command print o I appreciate all your help... Thanks, -Rahul Dabane. From kretik at yahoo.com Thu Jun 19 13:13:26 2008 From: kretik at yahoo.com (kretik) Date: Thu, 19 Jun 2008 10:13:26 -0700 Subject: Getting Python to run Python Scripts in cygwin In-Reply-To: References: Message-ID: You do have Python installed in Cygwin, right? It's an optional component, IIRC? If it is then it should have set the symlink in /usr/bin to wherever it's installed. Calvin Cheng wrote: > Hi guys, > > This may be a cygwin issue but I was hoping to get some answers here > as well if someone has fixed this problem before. > > Basically, I am able to run "python .py" python files in > command prompt. Unfortunately, I can't seem to get it to work in > cygwin. I always get an error that says: > python: can't open file '.py': [Errno 2] No such file or directory > > I have looked at my environment variables and it seems to be correct. > > Would be grateful if someone who has gotten python to work correctly > on cygwin could point me in the right direction. > > It is very cumbersome switching back-and-forth between command prompt > and cygwin just to run python scripts. > > Thank you in advance, > Calvin From deets at nospam.web.de Sun Jun 1 15:14:14 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 01 Jun 2008 21:14:14 +0200 Subject: Integrating a code generator into IDLE In-Reply-To: References: Message-ID: <6agaofF36ap0uU1@mid.uni-berlin.de> Sam Denton schrieb: > Code generators seem to be popular in Python. > (http://www.google.com/search?q=python+code-generator) Certainly not. The most of them will be used for generating bindings. Apart from that, you rareley (if ever) need to generate code. > I have one that I'd like to integrate into IDLE. Ideally, I'd like to > (1) have a new file type show up when I use the File/Open dialog, and > (2) have a function key that lets me run my generator against the file, > just like F5 lets me run my Python code; ideally, I'd like to re-purpose > the F5 key to be file-type aware. I've got a simple extension written > that uses the F6 key to "compile" my files, but two goals I've listed > seem a bit beyond me. Does anyone have any advice/pointers? Or is one > or both ideas impractical? Thanks! You might consider using eric, a python-ide written in python with the Qt-Framework. It allows plugins. Diez From joemacbusiness at yahoo.com Thu Jun 26 20:45:19 2008 From: joemacbusiness at yahoo.com (joemacbusiness at yahoo.com) Date: Thu, 26 Jun 2008 17:45:19 -0700 (PDT) Subject: Need help capturing output of re.search References: <771ef68a-d976-4f61-a3cc-7ed56fddc756@k37g2000hsf.googlegroups.com> <9757288e-0b48-46ee-8fd0-0adf36bbd710@p39g2000prm.googlegroups.com> <5fd345b7-6b32-4d45-8c55-662684adf5e9@34g2000hsf.googlegroups.com> <8e0883f9-f36d-4d62-a1a4-4cd66163a1cc@s21g2000prm.googlegroups.com> Message-ID: <9394de8d-7c81-4b86-990b-91c51dc50efc@z72g2000hsb.googlegroups.com> On Jun 26, 5:12?pm, John Machin wrote: > On Jun 27, 10:01 am, joemacbusin... at yahoo.com wrote: > > > >You may like to read this:http://www.amk.ca/python/howto/regex/ > > > This is a good resource. ?Thank you. > > Someone else pointed out that I needed to change the > > > if reCheck == "None": > > > to > > > if reCheck == None: ? # removed the "s > > "Somebody else" should indeed remain anonymous if they told you that. > Use > ? ?if reCheck is None: > or even better: > ? ?if not reCheck: > > It's not obvious from your response if you got these points: > (1) re.match, not re.search > (2) filename.startswith does your job simply and more understandably Understood. I replaced re.search with re.match (although both work) can filename.startswith be used in a conditional? ala: if filename.startswith('CC_'): processtheFile() Thanks for the great help! From workitharder at gmail.com Mon Jun 2 19:21:58 2008 From: workitharder at gmail.com (bukzor) Date: Mon, 2 Jun 2008 16:21:58 -0700 (PDT) Subject: Cast list of objects to list of strings References: <48546eb1-11f3-4a88-b1ac-97bd485a1823@k30g2000hse.googlegroups.com> <63d3d50d-0e9b-4682-b523-c2ff7d336c6a@m44g2000hsc.googlegroups.com> Message-ID: <2593e641-5dff-4f58-a4ba-b43bca07f24a@x41g2000hsb.googlegroups.com> On Jun 2, 2:56 pm, jay graves wrote: > On Jun 2, 4:02 pm, Larry Bates wrote: > > > I think what you want is: > > def write_err(*args): > > from sys import stderr > > stderr.write("\n".join([str(o) for o in args])) > > Slight nitpick. If you are using version >= 2.4 you could use a > generator expression instead of a list comprehension to avoid building > and throwing away a list. > > "\n".join(str(o) for o in args) > > http://www.python.org/dev/peps/pep-0289/ > > Very unlikely to yield a material time difference in this case but > cleaner IMO. > > ... > Jay Graves Thanks! That's exactly what I was looking for. From goldnery at gmail.com Thu Jun 12 15:04:55 2008 From: goldnery at gmail.com (Gandalf) Date: Thu, 12 Jun 2008 12:04:55 -0700 (PDT) Subject: Charset (hopefully for the last time I ask) Message-ID: now I understand my problem better so their is a good chance you manage to help me. I have a SQlite database full with ANSI Hebrew text , and program that uses WXpython Now, I use a- 'wx.TextCtrl' item to receive input from the user, and when I try to search the database he don't understand this chars. it's quite reasonable consider the fact the program set to work on UTF-8 charset, except for: 1. it doesn't work when I delete the charset too 2. when I try to use function like decode and encode it output error like this: ascii' codec can't encode characters in position 0-4: ordinal not in range(128) ascii' codec can't encode characters in position 0-2: ordinal not in range(128) 3. I don't know how to translate my DB from ANSI to UTF-8 4. when I don't use the user WX items input I can change my editor charset to ansi and it works fine Thank you all From mail at timgolden.me.uk Thu Jun 5 14:58:35 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 05 Jun 2008 19:58:35 +0100 Subject: Question regarding re module In-Reply-To: <9165ed46-4077-44a8-ae93-ceafda975f04@56g2000hsm.googlegroups.com> References: <9165ed46-4077-44a8-ae93-ceafda975f04@56g2000hsm.googlegroups.com> Message-ID: <4848375B.6030702@timgolden.me.uk> Paul McGuire wrote: > On Jun 5, 7:11 am, Tomohiro Kusumi > wrote: >>> It could be that the result overloads the __getattr__-method to delegate >>> calls to some object. Thus it's not part of the outer instance. > > Didn't I read that Py3 will support a __dir__ method so that classes > *could* report such pseudo-attributes in response to dir? It's already there in 2.6: ... class X (object): ... def __init__ (self, a, b): ... self.a = a ... self.b = b ... def __dir__ (self): ... return ['a', 'b', 'c'] ... >>> dir (X (1, 2)) ['a', 'b', 'c'] >>> TJG From teh.saber at gmail.com Thu Jun 26 05:24:08 2008 From: teh.saber at gmail.com (teh_sAbEr) Date: Thu, 26 Jun 2008 02:24:08 -0700 (PDT) Subject: Working with the Windows Registry References: <49beca2a-9d6c-40a2-a7c3-bf1cf376df0a@l28g2000prd.googlegroups.com> Message-ID: <11e16b1f-0770-4932-994e-1ac3bc8e17e4@c19g2000prf.googlegroups.com> Great! It works properly now but I have one more question, would anyone know how to get the changes to take effect immediately? Like some sort of Python way to force the desktop to reload? AFAIK the only way that'll happen is if I use the Display Properties dialog box. The Registry value is changed properly, its just I don't think the changes will take effect until I restart. From theo at van-werkhoven.nl.invalid Thu Jun 12 15:45:18 2008 From: theo at van-werkhoven.nl.invalid (Theo v. Werkhoven) Date: Thu, 12 Jun 2008 21:45:18 +0200 Subject: time.clock() or Windows bug? References: <0uep44hpn8rupgr15a135f37q346tif9v2@4ax.com> Message-ID: The carbonbased lifeform Tim Roberts inspired comp.lang.python with: > Nick Craig-Wood wrote: >> >>Hmmm, 10,000,000 cycles (40 ms @2.5GHz) is nowhere near the ~90,000 >>second jump in time.clock() output reported by the OP. I wonder if >>there could be a different cause? > > Just wild theorizing, but it's possible that they are actually getting a > negative delta, and some kind of signed/unsigned manipulation produces the > 90,000 number. Actually, in previous runs I /did/ see negative timestamps using time.clock(). Bizar. Theo -- theo at van-werkhoven.nl ICQ:277217131 SuSE Linux linuxcounter.org: 99872 Jabber:muadib at jabber.xs4all.nl AMD XP3000+ 1024MB "ik _heb_ niets tegen Microsoft, ik heb iets tegen de uitwassen *van* Microsoft" From yardennis at gmail.com Thu Jun 26 14:12:34 2008 From: yardennis at gmail.com (yardennis) Date: Thu, 26 Jun 2008 11:12:34 -0700 (PDT) Subject: python interface to Firefox and Thunderbird Message-ID: <6c5dab9f-3521-4434-8100-65ad1fe207d0@i36g2000prf.googlegroups.com> Hi, I need python moudles that can auto install python 2.5 (web install or a EXE file) auto download and install Firefox3 and Thunderbird 2 auto import from IE 6, 7 and OE 5,6 and Outlook read contacts and emails from Thunderbird store read Firefox 3 bookmarks, history, cookies and password Can anyone point to a open source solution ? If you know of any freelancer that can help me develop the module please let me know. Thanks Dennis yardennis at gmail dot com From miki.tebeka at gmail.com Mon Jun 23 01:39:05 2008 From: miki.tebeka at gmail.com (Miki) Date: Sun, 22 Jun 2008 22:39:05 -0700 (PDT) Subject: rightclick-copy in IDLE? References: <6b40b216-65b8-40da-9072-7b3249086c7c@m44g2000hsc.googlegroups.com> Message-ID: <7e57e15e-2a85-47b4-a999-e4a85c02eb39@x1g2000prh.googlegroups.com> > when i rightclick in python idle i get set breakpoint or something. > > n options i dont find a way to change to the normal copy/paste options. Under "Preferences ..." menu you'll find "Keys" tab, there you can change the keys bindings to whatever you want. HTH, -- Miki http://pythonwise.blogspot.com From d.a.abernathy at gmail.com Mon Jun 9 16:36:41 2008 From: d.a.abernathy at gmail.com (dj) Date: Mon, 9 Jun 2008 13:36:41 -0700 (PDT) Subject: time module methods give an am or pm value ? References: <2309efff-5c6b-4434-a2cd-01c3fee86fee@l42g2000hsc.googlegroups.com> Message-ID: <55eb5dc1-3040-43dd-84ab-7fbb66d0248e@d77g2000hsb.googlegroups.com> On Jun 7, 9:24 am, "Mark Tolonen" wrote: > "dj" wrote in message > > news:2309efff-5c6b-4434-a2cd-01c3fee86fee at l42g2000hsc.googlegroups.com... > > > Hello again, > > > Does anyone know which method in the time module will generate and am > > or pm ? > > If none of the method will do this for me. Can I produce the value on > > my own ? > > Any suggestions ? > >>> from time import * > >>> strftime('%I:%M:%S %p',localtime(time())) > '07:23:24 AM' > >>> strftime('%I:%M:%S %p',gmtime(time())) > > '02:23:39 PM' > > -Mark Hello Mark, Thank you very much. I finally found this function in the documentation. From roopesh.raj at gmail.com Sat Jun 28 02:48:13 2008 From: roopesh.raj at gmail.com (Roopesh) Date: Fri, 27 Jun 2008 23:48:13 -0700 (PDT) Subject: Problems with file IO in a thread, and shutil References: <38f798c9-983f-4f0c-a281-d2a89e738590@v1g2000pra.googlegroups.com> Message-ID: <3cb1b183-5a89-40a7-9ef8-484416eac779@y22g2000prd.googlegroups.com> > Maybe it's a Windows service, eg the indexing service or generating > thumbnails. Anyway, retrying after a delay would still be worth it. Yes, this thing works :-) Thanks a lot. Thanks Roopesh From Lie.1296 at gmail.com Tue Jun 10 11:20:51 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 10 Jun 2008 08:20:51 -0700 (PDT) Subject: Does the python library of Google Data API is truly free? References: <3ac654b2-61b4-44ce-8e03-75f2344d5869@s50g2000hsb.googlegroups.com> <6fb57ab1-b0d2-4b7d-93c1-b919ca0e51a0@i36g2000prf.googlegroups.com> <3a296d00-d4e0-4f03-b6b3-bef4c5d628dd@x35g2000hsb.googlegroups.com> <6b5mloF3aeui4U1@mid.uni-berlin.de> <18115776-edf7-41b8-a5e9-639847c57a6a@x41g2000hsb.googlegroups.com> Message-ID: <851da24f-1681-46ff-9df4-c12941ad4078@v26g2000prm.googlegroups.com> On Jun 10, 2:49?pm, Kless wrote: > On 9 jun, 22:46, "Diez B. Roggisch" wrote: > > > Kless schrieb: > > > > On 9 jun, 21:40, Lie wrote: > > >> Do you notice that the terms are for the SERVICE not for the SOFTWARE. > > >> The terms for the service is quite reasonable, as I see it. > > >> The software itself is governed by the Apache License 2.0, detailed > > >> here:http://www.apache.org/licenses/LICENSE-2.0 > > > > Well, it's used a free license to access to a service that is not free > > > -it's owner and too restrictive-. And it isn't nothing reasonable that > > > Google get many rights about your content, and that you have not any > > > right about the rest of the content. > > > > This goes against the free software, considering that a service is > > > software. > > > This is nonsense. If a hosting provider offers you free hosting based on > > linux - and then goes out of business or is forced to charge money - do > > you say "that's against free software?" > > I don't speak about hosting else rights about data, data that are > entered by people: > This shows you have not made any efforts to understand the difference between software and service: SOFTWARE != SERVICE. The freedom and the restriction of the software is governed by the Apache License 2.0. On the other hand, the freedom and the restriction of the service is governed by this rules, which has a pretty reasonable terms for a service. > "By submitting, posting or displaying the content you give > Google a perpetual, irrevocable, worldwide, royalty-free, and non- > exclusive license to reproduce, adapt, modify, translate, publish, > publicly perform, publicly display and distribute any Content which > you submit, post or display on or through, the Services..." You have cut an important line to support your proposition: This license is for the sole purpose of enabling Google to display, distribute and promote the Services and may be revoked for certain Services as defined in the Additional Terms of those Services. > "You agree that this license includes a right for Google to make > such Content available to other companies, organizations or > individuals with whom Google has relationships for the provision of > syndicated services..." Without this line, there is no way the service could work, since basically the service (GData) is all about making your data available to other people. > > Or if they prohibit you to host malicious, offending or otherwise > > problematic content served by the free apache - is that "against free > > software?" > > Please, don't be demagogue. > > > A service is a service. It is offered as is, under whatever conditions > > the provider likes it. > > A service or web service to follows being software. A software where > is more easy to add restrictions, in this case those restrictions goes > against the freedoms of the free software. Some companies advertise Software as a Service, in those case the Service is equivalent to the Software. In this case, the service is GData Service and the Software is the GData API. > > Offering a convenient way to access the service using a FOSS license is > > good style. But you aren't forced to use that, you can write your own. > > But that doesn't change the terms and conditions of the service itself. > > Offering access via Apache 2.0 -wich is not compatible with GPLv2- to > a non-free service is a mortal trap where people are falling. Whether Apache 2.0 is GPLv2 compatible or not is irrelevant, GPL is only one type of license, no more no less, it's not the Holy Grail of free software spirit. The fact that many other softwares use GPL license is because the license has been designed for general use and many open source groups doesn't really have the knowledge, capability, and/or time to create their own license (creating a license is not as easy as it seems), most doesn't even care what their software is licensed on and their exact terms. The use of a well-known license also made it easy for the users to know the license he's agreeing to without reading and reading and reading a license again and again and again. From maehhheeyy at gmail.com Tue Jun 10 15:53:51 2008 From: maehhheeyy at gmail.com (maehhheeyy) Date: Tue, 10 Jun 2008 12:53:51 -0700 (PDT) Subject: can't assign to literal Message-ID: this is stopping my program from running properly. is there something wrong in my code when that happens? From nospam at nospam.com Mon Jun 2 18:42:18 2008 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 03 Jun 2008 00:42:18 +0200 Subject: Checking each item in m.group()? References: <47412fe8-ba45-4f66-8064-75137c022339@m36g2000hse.googlegroups.com> Message-ID: On Mon, 2 Jun 2008 12:06:21 -0700 (PDT), Matimus wrote: >Here is a brief example. Note that this code is very insecure and >susceptible to a SQL injection attack. Hopefully these csv files are >from a trusted source. Yes they are, and this script will only run on my PC, so it doesn't need to be more secure than this. >sql = "INSERT INTO mytable (col1, col2) VALUES ('%s','%s')"%tuple( > (c, "NULL")[c == ''] for c in m.groups() > ) > I don't understand this syntax :-/ >Also, check out the csv module for parsing your csv file. Will do. Thank you. From jgardner at jonathangardner.net Thu Jun 26 19:11:41 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 26 Jun 2008 16:11:41 -0700 (PDT) Subject: ask for a RE pattern to match TABLE in html References: <6a4f17690806260653i136681bdsabe0f6bb1dfab67b@mail.gmail.com> Message-ID: <62f752f3-d840-42de-a414-0d56d15d7c5a@w4g2000prd.googlegroups.com> On Jun 26, 3:22?pm, MRAB wrote: > Try something like: > > re.compile(r'.*?
1. the curd of milk separated from the whey and prepared in many ways as a food.
', re.DOTALL) So you would pick up strings like "
foo
"? I doubt that is what oyster wants. From sjmachin at lexicon.net Mon Jun 30 20:01:41 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 30 Jun 2008 17:01:41 -0700 (PDT) Subject: The Yield statement References: Message-ID: <33686323-25e3-4442-9667-cb098e1686d9@p39g2000prm.googlegroups.com> On Jul 1, 8:31 am, Alex Bryan wrote: > Okay, so i don't really understand the Yield thing and i know it is > useful. I've read a few things about it but it is all programming > jargon and so basically it is hard for me to understand. So can anyone > give me a description or link me to a site that has a good definition > and/or examples of it? If you could I would really appreciate it. Try this: http://www.dabeaz.com/generators/ (ignore the "tricks" word in the title) From tjreedy at udel.edu Sun Jun 15 15:01:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 15 Jun 2008 15:01:03 -0400 Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com><3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> Message-ID: wrote in message news:1257aa24-14fa-426e-8019-262984c70633 at 2g2000hsn.googlegroups.com... |> How did you determine that standard python floats are not good enough? | I have a physical system set up in which a body is supposed to | accelerate and to get very close to lightspeed, while never really |attaining it. Just a thought. You might do better if you can rearrange your equations in terms of c-v instead of v. Letting c=1, you cannot accutrately express v = .99999999999999999999 in Python, but can easily express 1-v = .00000000000000000001. And so on. tjr From bruno.desthuilliers at gmail.com Tue Jun 24 14:47:58 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Tue, 24 Jun 2008 11:47:58 -0700 (PDT) Subject: shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": References: Message-ID: On 24 juin, 20:32, cirfu wrote: > if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": > > cant i write something like: > if char in "[A-Za-z]": > Nope. But there are other solutions. Here are two: # 1 import string if char in string.letters: print "yay" # 2 import re exp = re.compile(r'[A-Za-z]') if exp.match(char): print "yay" From srhegde at gmail.com Fri Jun 27 12:26:46 2008 From: srhegde at gmail.com (python_enthu) Date: Fri, 27 Jun 2008 09:26:46 -0700 (PDT) Subject: Simple regular expression References: <47031cc4-2b5e-43b3-9338-cf4a7b4c1568@d45g2000hsc.googlegroups.com> <03a59caa$0$3254$c3e8da3@news.astraweb.com> Message-ID: On Jun 27, 11:05?am, "John Salerno" wrote: > "python_enthu" wrote in message > > news:47031cc4-2b5e-43b3-9338-cf4a7b4c1568 at d45g2000hsc.googlegroups.com... > > >I am trying this.. what is wrong in this.. > > > IDLE 1.2.2 > >>>> import re > >>>> a="my name is fname lname" > >>>> p=re.compile('name') > >>>> m=p.match (a) > >>>> print p.match(a) > > None > > ? ? ? match( string[, pos[, endpos]]) > > If zero or more characters at the beginning of string match this regular > expression, return a corresponding MatchObject instance. Return None if the > string does not match the pattern; note that this is different from a > zero-length match. > > ? ? ? search( string[, pos[, endpos]]) > > Scan through string looking for a location where this regular expression > produces a match, and return a corresponding MatchObject instance. Return > None if no position in the string matches the pattern; note that this is > different from finding a zero-length match at some point in the string. Thanks John Salerno and John Machin, I am used to perl. So I guess I am better of using re.search instead of re.match BTW, is re.search('string') equivalent to re.match ('^string') From mal at egenix.com Wed Jun 4 04:43:14 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 04 Jun 2008 10:43:14 +0200 Subject: Keep a script running in the background In-Reply-To: References: <210b7fc6-ed52-461d-8b53-455e247d7a29@e39g2000hsf.googlegroups.com> Message-ID: <484655A2.6080701@egenix.com> On 2008-06-04 01:33, Guillermo wrote: > These are the basic requirements: > > Script A must keep a dictionary in memory constantly and script B must > be able to access and update this dictionary at any time. Script B > will start and end several times, but script A would ideally keep > running until it's explicitly shut down. > > I have the feeling the way to do this is Python is by pickling the > dict, but I need the method that gives the best performance. That's > why I'd rather want to keep it in memory, since I understand pickling > involves reading from and writing to disk. > > I'm using SQLite as a database. But this dict is an especial index > that must be accessed at the highest speed possible. If you're on Unix, it's easiest to have script A implement a signal handler. Whenever it receives a signal, it rereads the pickled dict from the disk. Script B then writes a new revision of the dict and sends the signal to script A. Alternatively, you could use an on-disk dictionary like e.g. mxBeeBase: https://www.egenix.com/products/python/mxBase/mxBeeBase/ -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jun 04 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania 32 days to go :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From george.sakkis at gmail.com Mon Jun 30 13:41:17 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 30 Jun 2008 10:41:17 -0700 (PDT) Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> Message-ID: <6a8d3b30-b7d6-4f41-b491-0cfc44e46109@27g2000hsf.googlegroups.com> On Jun 30, 1:19 pm, Mike wrote: > On Jun 30, 10:57 am, Bruno Desthuilliers > 42.desthuilli... at websiteburo.invalid> wrote: > > > Some (if not most) templating systems use their own mini-language to > > handle presentation logic. > > IMHO this is the funniest (worst) part of all this 'templating' > buss :) > It reminds me the good old slogan: "Have you invented your own GUI > library yet?" > > > > > The meme "thou shall not mix domain logic with presentation" is very > > often misunderstood as "you must not have anything else than html in > > templates", which is just plain non-sense. Even declarative templating > > systems (cf Has's post) require some special (ie: non standard) stuff to > > work. > > > > Or could it just be that > > > this is a *good* way to mix HTML and Python, and there are other ways > > > which may be bad? > > > Bingo. > > Then what is so *good* about it, why embedding HTML into Python is not > good? Because _typically_ a web template consists of mostly HTML, with relatively little presentational logic and (ideally) no business logic. Now, if all one wants to do is a quick and dirty way to, say, view a log file in the browser, a separate template is probably an overkill; there's nothing wrong with something like "for line in logfile: print cgi.escape(line.strip()) + '
'". It's a matter of relative frequencies which language is the embedded one. George From gh at ghaering.de Tue Jun 10 12:32:44 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 10 Jun 2008 18:32:44 +0200 Subject: problems with opening files due to file's path In-Reply-To: <17759531.post@talk.nabble.com> References: <17759531.post@talk.nabble.com> Message-ID: Alexnb wrote: > Okay, so what I want my program to do it open a file, a music file in > specific, and for this we will say it is an .mp3. Well, I am using the > system() command from the os class. [...] > > system("\"C:\Documents and Settings\Alex\My Documents\My > Music\Rhapsody\Bryanbros\Weezer\(2001)\04 - Island In The Sun.wma\"") > [...] Try os.startfile() instead. It should work better. -- Gerhard From mail at timgolden.me.uk Thu Jun 12 03:51:53 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 12 Jun 2008 08:51:53 +0100 Subject: How to set directory in save as combo box In-Reply-To: <01f201c8cc3f$2f6ba990$2fc513ac@pwit.com> References: <01f201c8cc3f$2f6ba990$2fc513ac@pwit.com> Message-ID: <4850D599.6020609@timgolden.me.uk> gopal mishra wrote: > In 'save as' dialog of window application, I am trying to set the path in > 'save in' combo box using python win32 programming. > How we can set the directory in the 'save in' combo box. There are several ways to display a "Save As" dialog. Can you post [a minimal version of] the code you're using so we can see what you're doing, please? TJG From lepto.python at gmail.com Thu Jun 26 06:57:40 2008 From: lepto.python at gmail.com (oyster) Date: Thu, 26 Jun 2008 18:57:40 +0800 Subject: instructions on adding external Tcl/Tk widget into Tkinter? Message-ID: <6a4f17690806260357j4bfe9140vf1084436d371a2e8@mail.gmail.com> It is so funny that the official GUI lib for python is Tkinter, but I cannot find an articles which explains indetail how can we use thounsands of Tcl/Tk widget in Tkinter. For example, I have download the dll at http://www.hwaci.com/sw/tkhtml/index.html, renamed it to tkhtml12.dll and put it in H:\python25\bin\tcl\Tkhtml1.2\ then I edited a h:\python25\bin\tcl\Tkhtml1.2\pkgIndex.tcl file: [**********pkgIndex.tcl********] if {![package vsatisfies [package provide Tcl] 8]} {return} if {[string compare $::tcl_platform(platform) windows]} {return} if {[info exists ::tcl_platform(debug)]} { package ifneeded Tkhtml 1.2.3 [list load [file join $dir Tkhtml12g.dll] Tkhtml] } else { package ifneeded Tkhtml 1.2.3 [list load [file join $dir Tkhtml12.dll] Tkhtml] } [/**********pkgIndex.tcl********] but http://tix.sourceforge.net/Tixapps/src/Python/TkHtml.py says [*********says*********] attempt to provide package Tkhtml 1.2.3 failed: package Tkhtml 0.0 provided instead [/*********says*********] From ncoghlan at gmail.com Wed Jun 4 07:14:04 2008 From: ncoghlan at gmail.com (NickC) Date: Wed, 4 Jun 2008 04:14:04 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> Message-ID: <911bd81e-1342-4870-8b7a-f706c5dea01b@a32g2000prf.googlegroups.com> On May 26, 2:49 pm, "Russ P." wrote: > I am also bothered a bit by the seeming inconsistency of the rules for > the single underscore. When used at file scope, they make the variable > or function invisible outside the module, but when used at class > scope, the "underscored" variables or functions are still fully > visible. For those who claim that the client should be left to decide > what to use, why is the client prohibited from using underscored > variables at file scope? They aren't - the only thing that won't see the underscore prefixed names is "from x import *". If you do "import x" instead, all the underscored names will be accessible as attributes of the module. From sjmachin at lexicon.net Wed Jun 4 07:45:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 4 Jun 2008 04:45:15 -0700 (PDT) Subject: Zipfile module errors References: <1bea3f60-5866-4ecb-a2a2-51f7130f03c8@y21g2000hsf.googlegroups.com> Message-ID: <8a2a1e8d-cde2-45f4-9329-407e0c2980c8@l28g2000prd.googlegroups.com> On Jun 4, 8:06 pm, jwesonga wrote: > Hi, > > I have a python script that supposed to go through a folder, pick the > zipped files, unzip them and process the data inside. I'm not sure > where i'm going wrong with this script because it all seems correct: Nothing is ever as it seems. Let's try to work backwards from the error message ... and we don't need your magnificent script, just the traceback will do for now, so: [ big snip] > > The error I keep getting is: > > Traceback (most recent call last): > File "processor3.py", line 124, in ? > unzip(infolder) > File "processor3.py", line 53, in unzip The error says that you are trying to seek 22 bytes backwards from the end of a file that you presume is a zip file, and this is deemed to be invalid. Hypotheses: (1) zipfile.py is buggy (2) your file is less than 22 bytes long. Let's park hypothesis 1 for the moment. Insert the following code before the call to zipfile.ZipFile: print "trying to unzip %r whose size is %d bytes" \ % (one, os.stat(one).st_size) and tell us your conclusions. > zfile = zipfile.ZipFile(one,'r') > File "/usr/lib/python2.4/zipfile.py", line 210, in __init__ > self._GetContents() > File "/usr/lib/python2.4/zipfile.py", line 230, in _GetContents > self._RealGetContents() > File "/usr/lib/python2.4/zipfile.py", line 240, in _RealGetContents > endrec = _EndRecData(fp) > File "/usr/lib/python2.4/zipfile.py", line 83, in _EndRecData > fpin.seek(-22, 2) # Assume no archive comment. > IOError: [Errno 22] Invalid argument P.S. Printing the contents of filelist immediately after it's been created might be a good idea. You say "pick the zipped files" but the only condition I see is a test using os.path.isdir. HTH, John From brendon at christian.net Thu Jun 19 03:05:13 2008 From: brendon at christian.net (Brendon Costa) Date: Thu, 19 Jun 2008 00:05:13 -0700 (PDT) Subject: How do i : Python Threads + KeyboardInterrupt exception References: <089f56d2-5e44-4161-b580-84881717bd05@w4g2000prd.googlegroups.com> <6cfbfaa2-293f-41d3-b544-fd47f05d0d36@j33g2000pri.googlegroups.com> Message-ID: I tested this a bit more. My windows example was incorrect. It should have used CTRL_C_EVENT. But even then, the problem is that the process will also close the console window from which it was called because of the 0. Also this requires that the process actually have a console and is not a GUI application. Is there some other method rather than a blocking "for line in fin:" that i can use for reading from a file like device that plays nicely with other threads asynchronously waking it up? Sorry for all the posts. I am giving updates as i look further into the problem. From martin at v.loewis.de Tue Jun 24 02:34:02 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Jun 2008 08:34:02 +0200 Subject: Is there any way to find out sizeof an object In-Reply-To: References: Message-ID: <4860955a$0$9759$9b622d9e@news.freenet.de> > I have written a class which has some attributes. I want to know how > do i find out the size of an instance of this class?? > class T(object): > def __init__(self, fn_name, *args, **kwds): > self.fn_name = fn_name > self.args = args > self.kwds = kwds In Python 2.6, you can use sys.getsizeof to find out how large an object is. Notice that this is a really tricky question: Assuming you have t = T(1,2,3, a="hello", b="world") then you should certainly consider the size atleast sys.getsizeof(t) + sys.getsizeof(t.__dict__) But then you also have the attribute values (i.e. the tuple resp. dict), which you might want to account for: + sys.getsizeof(t.args) + sys.getsizeof(t.dict) Now, what to do about the sizes of the various items in the dict and the tuple? One could do total = ... # from above for o in t.args: total+=sys.getsizeof(o) for k,v in t.kwds.items(): total+=sys.getsizeof(k)+sys.getsizeof(v) However, that might be accounting too much, since the at least the keys of the dict are shared across other dicts. Likewise, the integers are shared, and the string literals (as written above) would be shared if the very same T constructor is run twice. In short, "size of an instance" can't be answered without a specific instance (i.e. you can't answer it in advance for all instances), plus even for a single instance, its difficult to answer. Regards, Martin From dstromberglists at gmail.com Thu Jun 5 00:59:38 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Thu, 5 Jun 2008 04:59:38 +0000 (UTC) Subject: sed to python: replace Q References: <48180348$0$34534$742ec2ed@news.sonic.net> <4820714b$0$34544$742ec2ed@news.sonic.net> Message-ID: On Tue, 06 May 2008 14:55:07 +0000, Raymond wrote: >>Another approach is to use the split() function in "re" module. > > Ah ha, thar's the disconnect. Thanks for all the pointers, my def is > now working. Still don't understand the logic behind this design > though. I mean why would any programming language have separate search > or find functions, one for regex and and another for non-regex based > pattern matching? > > Aren't sed, awk, grep, and perl the reference implementations of search > and replace? They don't have non-regex functions, why does Python? > Wouldn't it be a lot simpler to use a flag, like grep's '-f', to change > the meaning of a search string to be literal? > > My other gripe is with the kludgy object-oriented regex functions. > Couldn't these be better implemented in-line? Why should I, as a coder, > have to 're.compile()' when all the reference languages do this at > compile time, from a much more straightforward and easy to read in-line > function... > > Raymon Hm. Are regex's first class citizens in these languages, like they are in python? And from a language design perspective, isn't it much cleaner to put regex's into just another portion of the runtime rather than dumping it into the language definition proper? It does actually make sense - to have a string method do a string thing, and to have a regex method do a regex thing. And while command line options are pretty nice when done well, there's nothing in particular stopping one from using arguments with defaults in python. I'm good with sed and grep, though I never got into awk much - perhaps a small mistake. When it came to perl, I skipped it and went directly to python, and have never regretted the decision. Python's got a much more coherent design than perl, most certainly, and more than sed as well. awk's not that bad though. And grep's nice and focused - I quite like grep's design. From lists at cheimes.de Sat Jun 14 09:32:20 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 14 Jun 2008 15:32:20 +0200 Subject: numpy: handling float('NaN') different in XP vs. Linux In-Reply-To: <17835502.post@talk.nabble.com> References: <17835502.post@talk.nabble.com> Message-ID: John [H2O] wrote: > I have a script: > > from numpy import float > OutD=[] > v=['3','43','23.4','NaN','43'] > OutD.append([float(i) for i in v[1]]) > > > On linux: > Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > [john at andLinux analysis]$ python jnk.py > [[3.0, 43.0, 23.399999999999999, nan, 43.0]] > > On XP: > Python 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > C:\analysis>C:\Python25\python.exe jnk.py > Traceback (most recent call last): > File "jnk.py", line 4, in > OutD.append([float(i) for i in v]) > ValueError: invalid literal for float(): NaN I've fixed the issue for Python 2.6 and 3.0 a while ago. Mark and I have spent a lot of time on fixing several edge cases regarding inf, nan and numerical unsound functions in Python's math und cmath module. Christian From sajmikins at gmail.com Thu Jun 19 19:10:09 2008 From: sajmikins at gmail.com (Simon Forman) Date: Thu, 19 Jun 2008 16:10:09 -0700 (PDT) Subject: Simple and safe evaluator References: <1de31143-7d8e-42e9-ae9d-8b0a0274ddc3@e53g2000hsa.googlegroups.com> Message-ID: On Jun 16, 8:32?pm, bvdp wrote: > sween... at acm.org wrote: > > On Jun 17, 8:02 am, bvdp wrote: > > >> Thanks. That was easy :) > > >>> The change to the _ast version is left as an exercise to the reader ;) > >> And I have absolutely no idea on how to do this. I can't even find the > >> _ast import file on my system. I'm assuming that the _ast definitions > >> are buried in the C part of python, but that is just a silly guess. > > >> Bob. > > > If you just need numeric expressions with a small number of functions, > > I would suggest checking the expression string first with a simple > > regular expression, then using the standard eval() to evaluate the > > result. ?This blocks the attacks mentioned above, and is simple to > > implement. ?This will not work if you want to allow string values in > > expressions though. > > > import re > > def safe_eval( expr, safe_cmds=[] ): > > ? ?toks = re.split( r'([a-zA-Z_\.]+|.)', expr ) > > ? ?bad = [t for t in toks if len(t)>1 and t not in safe_cmds] > > ? ?if not bad: > > ? ? ? ? ? ?return eval( expr ) > > Yes, this appears to be about as good (better?) an idea as any. > Certainly beats writing my own recursive decent parser for this :) > > And it is not dependent on python versions. Cool. > > I've run a few tests with your code and it appears to work just fine. > Just a matter of populating the save_cmds[] array and putting in some > error traps. Piece of cake. And should be fast as well. > > Thanks!!! > > Bob. FWIW, I got around to implementing a function that checks if a string is safe to evaluate (that it consists only of numbers, operators, and "(" and ")"). Here it is. :) import cStringIO, tokenize def evalSafe(source): ''' Return True if a source string is composed only of numbers, operators or parentheses, otherwise return False. ''' try: src = cStringIO.StringIO(source).readline src = tokenize.generate_tokens(src) src = (token for token in src if token[0] is not tokenize.NL) for token in src: ttype, tstr = token[:2] if ( tstr in "()" or ttype in (tokenize.NUMBER, tokenize.OP) and not tstr == ',' # comma is an OP. ): continue raise SyntaxError("unsafe token: %r" % tstr) except (tokenize.TokenError, SyntaxError): return False return True for s in ( '(1 2)', # Works, but isn't math.. '1001 * 99 / (73.8 ^ 88 % (88 + 23e-10 ))', # Works '1001 * 99 / (73.8 ^ 88 % (88 + 23e-10 )', # Raises TokenError due to missing close parenthesis. '(1, 2)', # Raises SyntaxError due to comma. 'a * 21', # Raises SyntaxError due to identifier. 'import sys', # Raises SyntaxError. ): print evalSafe(s), '<--', repr(s) From jeffober at gmail.com Sun Jun 22 19:10:35 2008 From: jeffober at gmail.com (Jeff) Date: Sun, 22 Jun 2008 16:10:35 -0700 (PDT) Subject: listcomprehension, add elements? References: <13452c64-ef91-49a2-bb73-7f33c088660e@d45g2000hsc.googlegroups.com> Message-ID: <324ebd7d-2024-404e-b392-5c77c43366f3@25g2000hsx.googlegroups.com> On Jun 22, 6:32?pm, cirfu wrote: > [a+b for a,b in zip(xrange(1,51), xrange(50,0,-1))] > > [51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, > 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, > 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51] > > i want to add all the elemtns a s well. can i do this all in a > listcomprehension? > > i can do this ofc: > reduce(lambda x,y:x+y,[a+b for a,b in zip(xrange(1,51), > xrange(50,0,-1))]) > > but reduce is a functional way of doing it, what is the more pythonic > way of doing this? Nothing that would be more concise than reduce. Anything you did with iteration would just mimic reduce in any case. Jeff Ober artfulcode.net From george.sakkis at gmail.com Fri Jun 20 16:54:09 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 20 Jun 2008 13:54:09 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> <8711b1fe-8256-4f6f-a3d7-f99f44eb23b0@e53g2000hsa.googlegroups.com> Message-ID: <195ccfd2-3751-44ac-af5e-22c77f8999b7@k37g2000hsf.googlegroups.com> On Jun 20, 3:44 pm, eliben wrote: > On Jun 20, 3:19 pm, George Sakkis wrote: > > > > > On Jun 20, 8:03 am, eliben wrote: > > > > On Jun 20, 9:17 am, Bruno Desthuilliers > > > 42.desthuilli... at websiteburo.invalid> wrote: > > > > eliben a ?crit :> Hello, > > > > > > In a Python program I'm writing I need to dynamically generate > > > > > functions[*] > > > > > (snip) > > > > > > [*] I know that each time a code generation question comes up people > > > > > suggest that there's a better way to achieve this, without using exec, > > > > > eval, etc. > > > > > Just to make things clear: you do know that you can dynamically build > > > > functions without exec, do you ? > > > > Yes, but the other options for doing so are significantly less > > > flexible than exec. > > > > > > But in my case, for reasons too long to fully lay out, I > > > > > really need to generate non-trivial functions with a lot of hard-coded > > > > > actions for performance. > > > > > Just out of curiousity : could you tell a bit more about your use case > > > > and what makes a simple closure not an option ? > > > > Okay. > > > > I work in the field of embedded programming, and one of the main uses > > > I have for Python (and previously Perl) is writing GUIs for > > > controlling embedded systems. The communication protocols are usually > > > ad-hoc messages (headear, footer, data, crc) built on top of serial > > > communication (RS232). > > > > The packets that arrive have a known format. For example (YAMLish > > > syntax): > > > > packet_length: 10 > > > fields: > > > - name: header > > > offset: 0 > > > length: 1 > > > - name: time_tag > > > offset: 1 > > > length: 1 > > > transform: val * 2048 > > > units: ms > > > - name: counter > > > offset: 2 > > > length: 4 > > > bytes-msb-first: true > > > - name: bitmask > > > offset: 6 > > > length: 1 > > > bit_from: 0 > > > bit_to: 5 > > > ... > > > > This is a partial capability display. Fields have defined offsets and > > > lengths, can be only several bits long, can have defined > > > transformations and units for convenient display. > > > > I have a program that should receive such packets from the serial port > > > and display their contents in tabular form. I want the user to be able > > > to specify the format of his packets in a file similar to above. > > > > Now, in previous versions of this code, written in Perl, I found out > > > that the procedure of extracting field values from packets is very > > > inefficient. I've rewritten it using a dynamically generated procedure > > > for each field, that does hard coded access to its data. For example: > > > > def get_counter(packet): > > > data = packet[2:6] > > > data.reverse() > > > return data > > > > This gave me a huge speedup, because each field now had its specific > > > function sitting in a dict that quickly extracted the field's data > > > from a given packet. > > > It's still not clear why the generic version is so slower, unless you > > extract only a few selected fields, not all of them. Can you post a > > sample of how you used to write it without exec to clarify where the > > inefficiency comes from ? > > > George > > The generic version has to make a lot of decisions at runtime, based > on the format specification. > Extract the offset from the spec, extract the length. Is it msb- > first ? Then reverse. Are specific bits required ? If so, do bit > operations. Should bits be reversed ? etc. So you are saying that for example "if do_reverse: data.reverse()" is *much* slower than "data.reverse()" ? I would expect that checking the truthness of a boolean would be negligible compared to the reverse itself. Did you try converting all checks to identity comparisons with None ? I mean replacing every "if compile_time_condition:" in a loop with compile_time_condition = compile_time_condition or None for i in some_loop: if compile_time_condition is None: ... It's hard to believe that the overhead of identity checks is comparable (let alone much higher) to the body of the loop for anything more complex than "pass". George From bearophileHUGS at lycos.com Mon Jun 16 06:24:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 16 Jun 2008 03:24:16 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> Message-ID: <08482987-b105-49cb-b8ea-0d469f6dc641@k13g2000hse.googlegroups.com> Oh, very good, better late than never. This is my pure Python version, it performs get, set and del operations too in O(1): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498195 Working with C such data structure becomes much faster, because it can use true pointers. Then another data structure that may be named SortedDict can be created, that keeps items in their natural order (instead of the insertion order). Bye, bearophile From roopesh.raj at gmail.com Thu Jun 26 03:06:03 2008 From: roopesh.raj at gmail.com (Roopesh) Date: Thu, 26 Jun 2008 00:06:03 -0700 (PDT) Subject: Problems with file IO in a thread, and shutil References: Message-ID: <38f798c9-983f-4f0c-a281-d2a89e738590@v1g2000pra.googlegroups.com> Thanks for the reply. I did testing in a clean system, were anti virus/ spyware is not installed. It still gave this problem, in say 1 out of 1000 cases. By any chance would it be possible that the Windows OS has not completed writing to the file even after file.flush() and file.close() is called? Thanks Roopesh From socyl at 987jk.com.invalid Fri Jun 6 18:04:26 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 6 Jun 2008 22:04:26 +0000 (UTC) Subject: How to send a POST request? References: Message-ID: In kj writes: >Hi. Sorry for this very clueless question, but how does one write >in Python an HTTP client that can send a POST request? The modules >I've found (e.g. urllib, urllib2), as far as I can tell, seem to >be limited to GET requests. (I could be wrong though; please >correct me if this is so.) Sorry, my mistake. I now see that urllib2 handles POSTs too. kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From fsenkel at lynx.neu.edu Thu Jun 19 16:37:47 2008 From: fsenkel at lynx.neu.edu (monkeyboy) Date: Thu, 19 Jun 2008 13:37:47 -0700 (PDT) Subject: Simple Class/Variable passing question Message-ID: <8a0cb1c6-8b54-4123-8f94-c0e0d465a1e9@e39g2000hsf.googlegroups.com> Hello, I'm new to python, and PythonCard. In the code below, I'm trying to create a member variable (self.currValue) of the class, then just pass it to a simple function (MainOutputRoutine) to increment it. I thought Python "passed by reference" all variables, but the member variable doesn't seem to be incremented. If I make the function just increment the member variable directly, without passing it in, it works fine? In the code below, "self.currValue" stays at 5, and value evaluates to 1? Any insight would be appreciated... class TestModel(model.Background): def on_initialize(self,event): self.currValue = 5 def on_startBtn_mouseClick(self, event): self.MainOutputRoutine(self.currValue) self.OutputRoutine(self.currValue) def OutputRoutine(self,value): self.components.txtBox1.text = str(value) def MainOutputRoutine(self,value): value = value + 1 From brian_vanderburg2 at yahoo.com Thu Jun 26 19:30:19 2008 From: brian_vanderburg2 at yahoo.com (Allen) Date: Thu, 26 Jun 2008 19:30:19 -0400 Subject: sqlite3 alternative option In-Reply-To: <3274f950-bfaf-4e3f-bb87-7ce205067557@m36g2000hse.googlegroups.com> References: <3274f950-bfaf-4e3f-bb87-7ce205067557@m36g2000hse.googlegroups.com> Message-ID: Gandalf wrote: > Hi every one I'm looking for a good alternative db to replace sqlite > > I'm using pySQlite3, And I tried to translate very big database from > Mysql to sqlite. > I generated through PHP a python script that insert 200,000 records > to my sqlite db and took me more then 5 hours and managed to insert > only 100,000 records. > I have almost million records so I need a better solution. > > > thank you I don't know if this will help, but using transactions dramatically speed things up. I've only played around with inserting records from large CVS files in C++, but outside of a transaction it creates an automatic transaction every time an update is made and takes forever, but if all the updates are inserted into one transaction and committed as one, it is substantially faster. Brian Vanderburg II From laurent.ploix at gmail.com Fri Jun 20 16:15:37 2008 From: laurent.ploix at gmail.com (=?ISO-8859-1?Q?m=E9choui?=) Date: Fri, 20 Jun 2008 13:15:37 -0700 (PDT) Subject: How to request data from a lazily-created tree structure ? References: <6bo3ifF3dj7dmU1@mid.uni-berlin.de> <896f8600-4183-4147-96c9-64ab5a9ad753@x41g2000hsb.googlegroups.com> <6bp68jF3cv5c7U1@mid.uni-berlin.de> <6bqq4hF3bshiiU1@mid.uni-berlin.de> Message-ID: On Jun 17, 10:54?pm, "Diez B. Roggisch" wrote: > > Do you know if there is such XPath engine that can be applied to a DOM- > > like structure ? > > No. But I toyed with the idea to write one :) > > > One way would be to take an XPath engine from an existing XML engine > > (ElementTree, or any other), and see what APIs it calls... and see if > > we cannot create a DOM-like structure that has the same API. Duck > > typing, really... > > Why can't you create a *real* DOM? > > Diez I don't know what "real" means, in fact. In python, being a "real" sg is all about having the same interface, right? May be I did not undertand what you meant. I cannot load all the data in memory before I request it, because it would take too long. If using XPath-like tools requires that I load the data in memory, I'd better create my own algorithm instead. It will be much faster. What I mean it: if I have a XPath engine that works well on a specific DOM-like structure... may be I can create my own DOM-lile structure to fool the XPath engine; so that I can use it on my own structure. From deets at nospam.web.de Wed Jun 11 17:57:05 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 11 Jun 2008 23:57:05 +0200 Subject: Strange bug doesn't occur in Pydb In-Reply-To: References: Message-ID: <6bb01lF38u72tU1@mid.uni-berlin.de> kj schrieb: > I'm running into a strange seg fault with the module cjson. The > strange part is that it does not occur when I run the code under > Emacs' Pydb. > > Here's an example: > > > import sys, cjson > > d1 = {'a': 1, 'b': 2, 'c': 3} > print sys.version > j1 = cjson.encode(d1) > print j1 # should print the string '{"a": 1, "c": 3, "b": 2}' > > The code above runs fine under Pydb, but segfaults at the call to > cjson.encode when I run it from the command line in a standard > Linux shell interaction. In the printed version strings are > identical. > > I figure this must be a bug in cjson. I'd love to find a workaround > for it, and hope that this strange difference between Pydb and the > shell command line may be a clue to that. > > Any thoughts? Are you sure you actually run the same interpreter in emacs as you do on the commandline? Diez From workitharder at gmail.com Thu Jun 5 20:32:28 2008 From: workitharder at gmail.com (bukzor) Date: Thu, 5 Jun 2008 17:32:28 -0700 (PDT) Subject: Guide to organizing modules? Message-ID: <1611a070-35f9-4072-b95f-ab592820f516@c65g2000hsa.googlegroups.com> I've been finding at work that I've written a set of functions several times, sometimes with more or less features or bugs, so I've decided to take my small, useful functions and put them in some common place. I've made a module for this, but it is quickly becoming a jumbled mess of unrelated functions. Also the one class that I've written with inheritance takes up fully 1/3 of the documentation (compared to 20 other functions). Since this is a large class I'm thinking of moving it to a separate module, but on the other hand it seems silly to have a whole module for just a single class. Also I'm worried that if I wait till later to organize it better, I'll have a lot of code where I'll need to fix-up the naming conventions. In summary: are there any good (or official) guidelines for how to organize and separate python functions and classes into modules? From bruno.42.desthuilliers at websiteburo.invalid Thu Jun 5 07:08:48 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 05 Jun 2008 13:08:48 +0200 Subject: Squeak-like environment for Python? In-Reply-To: <6apod7F387g23U1@mid.uni-berlin.de> References: <0001HW.C46D717900E84E0DB01AD9AF@news.individual.de> <6apod7F387g23U1@mid.uni-berlin.de> Message-ID: <4847c90a$0$6005$426a74cc@news.free.fr> Diez B. Roggisch a ?crit : > Jumping Arne wrote: > >> I've been playing with Squeak a bit and I really like the persistent >> storage model, I also liked HyperCard and Frontier (well, the persistent >> storage model at least). >> >> I wonder if there is some similar environment but based on python, I would >> like to use this environment not as a development environment but as a >> platform for storing data etc - much like HyperCard. >> >> I found a few postings about such an environment: >> >> >> >> but it looks like nothing happened. >> >> pythoncard doesn't seem to have the persistent storage model > > What about ZODB? You can use that to store (more or less) arbitrary objects. > Maybe that can be a foundation, if you throw in > > http://nodebox.net/code/index.php/Home > > it might be similar to squeak (I only dimly remember what squeak as a whole > is though - smalltalk & easy multimedia I remember) Mainly, Squeak is a (relatively) recent, free implementation of Smalltalk. The "persistent storage model" - the 'image' storing the whole system (code, libs, data, whatever) - is part of the Smalltalk system since it's first conception IIRC (even if some Smalltalk implementations - like GNU Smalltalk - are more traditionnaly file-based and have no automatic persistence). From tarek_enpc at yahoo.fr Thu Jun 5 06:12:13 2008 From: tarek_enpc at yahoo.fr (merzouki tarek) Date: Thu, 5 Jun 2008 10:12:13 +0000 (GMT) Subject: can you help me Message-ID: <469737.59430.qm@web26602.mail.ukl.yahoo.com>   hello please, I have this error, error C1083 Cannot open include file BaseTsd.h, invalide argument, I installed the platformSDK , but the same error , can you help me __________________________________________________ Do You Yahoo!? En finir avec le spam? Yahoo! Mail vous offre la meilleure protection possible contre les messages non sollicit?s http://mail.yahoo.fr Yahoo! Mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From patrick.m.bouffard at gmail.com Tue Jun 10 16:49:19 2008 From: patrick.m.bouffard at gmail.com (Patrick Bouffard) Date: Tue, 10 Jun 2008 13:49:19 -0700 (PDT) Subject: Determining which things in 'from package import *' are actually used References: Message-ID: <65aee7cf-eb16-46fa-b1b4-ecc4f0e5d849@x35g2000hsb.googlegroups.com> On Jun 10, 3:03?pm, Robert Kern wrote: > Patrick Bouffard wrote: > > I have a fairly large library of Python code, where 'from package import *' is > > used rather liberally, and it's not uncommon for more than one of these to > > appear in any given module. What I'd like to be able to do is to clean my code > > up a bit and turn each of the 'from package import *' statements into 'from > > package import thing_1, thing_2, ..., thing_n', where only thing_i's that are > > actually _used_ in the module are imported. In this way I hope to make my code a > > bit more understandable by future civilizations. :) (it needs all the help it > > can get!) > > > Does anyone know of a package/recipe/whatever that does something like this > > automatically, even in limited cases? Ideally it should be accomplished only by > > looking at the source, or at most, importing the module. > > I don't know of any automatic tools. I usually comment out those import > statements and use pyflakes to show me the undefined names. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > ? that is made terrible by our own mad attempt to interpret it as though it had > ? an underlying truth." > ? ?-- Umberto Eco Thanks, I didn't know about pyflakes. What you describe sounds like a great place to start, I'll give it a go. -Pat From george.sakkis at gmail.com Mon Jun 16 17:30:37 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 16 Jun 2008 14:30:37 -0700 (PDT) Subject: Simple and safe evaluator References: Message-ID: <1de31143-7d8e-42e9-ae9d-8b0a0274ddc3@e53g2000hsa.googlegroups.com> On Jun 16, 4:47 pm, bvdp wrote: > 2. I thought I'd be happy with * / + -, etc. Of course now I want to add > a few more funcs like int() and sin(). How would I do that? For the builtin eval, just populate the globals dict with the names you want to make available: import math globs = {'__builtins__' : None} # expose selected builtins for name in 'True False int float round abs divmod'.split(): globs[name] = eval(name) # expose selected math constants and functions for name in 'e pi sqrt exp log ceil floor sin cos tan'.split(): globs[name] = getattr(math,name) return eval(s, globs, {}) The change to the _ast version is left as an exercise to the reader ;) George From paddy3118 at netscape.net Wed Jun 25 15:39:26 2008 From: paddy3118 at netscape.net (Donald 'Paddy' McCarthy) Date: Wed, 25 Jun 2008 20:39:26 +0100 Subject: Question: How do I format printing in python In-Reply-To: <98d2a6fc-bcd3-44b8-bcf6-7059859683ff@c19g2000prf.googlegroups.com> References: <98d2a6fc-bcd3-44b8-bcf6-7059859683ff@c19g2000prf.googlegroups.com> Message-ID: Lie wrote: > On Jun 24, 12:12 am, joemacbusin... at yahoo.com wrote: >> Hi All, >> >> How do I format printed data in python? >> I could not find this in the Python Reference Manual:http://docs.python.org/ref/print.html >> Nor could I find it in Matloff's great tutorial:http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf >> >> For example, how do I turn this: >> >> 512 Jun 5 2004 X11r6 >> 22 Jan 17 2005 a2p >> 22 Jan 17 2005 acctcom >> 5374 Sep 15 2002 acledit >> 5664 May 13 2004 aclget >> 12020 May 13 2004 aclput >> 115734 Jun 2 2004 adb >> 46518 Jun 4 2004 admin >> 66750 Sep 16 2002 ali >> 1453 Sep 15 2002 alias >> 28150 Jun 4 2004 alog >> 15 May 12 2005 alstat >> >> into this: >> >> 512 Jun 5 2004 X11r6 >> 22 Jan 17 2005 a2p >> 22 Jan 17 2005 acctcom >> 5374 Sep 15 2002 acledit >> 5664 May 13 2004 aclget >> 12020 May 13 2004 aclput >> 115734 Jun 2 2004 adb >> 46518 Jun 4 2004 admin >> 66750 Sep 16 2002 ali >> 1453 Sep 15 2002 alias >> 28150 Jun 4 2004 alog >> 15 May 12 2005 alstat >> >> Thank you > > There is string formatting > > print formatspecifier_string % data_sequence > The format specifier is similar to the one used in C's printf, and > data sequence may be tuple or list. Dictionary may also be used for > data, but it has its own way to specify string formatting since > dictionary is unordered but "indexed" by the dict key. I have attached a prog I wrote to answer someones elses similar problem. - Paddy. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: pprinter2.py URL: From socyl at 987jk.com.invalid Fri Jun 20 08:14:22 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 20 Jun 2008 12:14:22 +0000 (UTC) Subject: Noob: finding my way around the docs... References: <4b56c745-9803-452a-a876-8f93afbea7c7@w7g2000hsa.googlegroups.com> Message-ID: In <4b56c745-9803-452a-a876-8f93afbea7c7 at w7g2000hsa.googlegroups.com> Matimus writes: >If you are in the interpreter and you type: help(foo.bar.baz) you get >the embeded documentation. >I usually go straight to the `global module index` http://docs.python.org/m= >odindex.html Thanks! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From omer at no-log.org Sun Jun 15 14:48:12 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Sun, 15 Jun 2008 20:48:12 +0200 Subject: randrange loops In-Reply-To: <6e424f2a-872d-4dd1-b28d-cf2a985895c9@j22g2000hsf.googlegroups.com> References: <6e424f2a-872d-4dd1-b28d-cf2a985895c9@j22g2000hsf.googlegroups.com> Message-ID: <200806152048.12102.omer@no-log.org> Le Sunday 15 June 2008 20:23:56 luislupe at gmail.com, vous avez ?crit?: > Hi, > > > I've created a method where the script defines twenty variables and > several of them should be random having a maximum and a minimum value. > > What I did was this: > > from random import randrange as rr, random > > self.tr2_vezes = self.rr(self.d_tr2_vezes[0],self.d_tr2_vezes[-1], > 1) # just an example, others are similar self.rr ? is it a typo or some method you defined yourself ? > > The minimum and maximum limits are never lower than -50 and higher > than 250 and are integer. > > Many times, not always, the problem is that the script just loops > forever and no value is chosen for the variable. > > What's happening here? What am I doing wrong? > as it's very unlikely to be a bug in the randrange function I'd say something is wrong with your script but we'll need more infos to help. Can you post the whole function ? -- C?dric Lucantis From miller.paul.w at gmail.com Mon Jun 2 20:42:08 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Mon, 2 Jun 2008 17:42:08 -0700 (PDT) Subject: "Faster" I/O in a script References: Message-ID: <4cf35e78-8d19-4367-9e1d-efed2b5a360c@79g2000hsk.googlegroups.com> On Jun 2, 2:08?am, "kalakouentin" wrote: > Do you know a way to actually load my data in a more > "batch-like" way so I will avoid the constant line by line reading? If your files will fit in memory, you can just do text = file.readlines() and Python will read the entire file into a list of strings named 'text,' where each item in the list corresponds to one 'line' of the file. From cdcasey at gmail.com Fri Jun 20 01:03:28 2008 From: cdcasey at gmail.com (chris) Date: Thu, 19 Jun 2008 22:03:28 -0700 (PDT) Subject: images on the web Message-ID: <2e72bd7d-9d33-43ba-8c08-ba3b39368466@z72g2000hsb.googlegroups.com> I'm creating a data plot and need to display the image to a web page. What's the best way of doing this without having to save the image to disk? I already have a mod_python script that outputs the data in tabular format, but I haven't been able to find anything on adding a generated image. From rhamph at gmail.com Wed Jun 11 20:37:45 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Wed, 11 Jun 2008 17:37:45 -0700 (PDT) Subject: Confusion with weakref, __del__ and threading References: <113f383e-9027-461b-88db-7e5331e7d361@59g2000hsb.googlegroups.com> <7ed2109d-3b88-484c-9d19-67706747c95f@v26g2000prm.googlegroups.com> <5da23b98-9434-41d4-9dd1-0a423fd387b1@26g2000hsk.googlegroups.com> Message-ID: <2a3ae0a4-144b-44ce-8e30-53b5586ccb7e@w4g2000prd.googlegroups.com> On Jun 11, 2:15 pm, George Sakkis wrote: > On Jun 11, 2:01 pm, Rhamphoryncus wrote: > > > > > On Jun 11, 10:43 am, George Sakkis wrote: > > > > On Jun 11, 1:40 am, Rhamphoryncus wrote: > > > > The trick here is that calling proxy.sleep(0.01) first gets a strong > > > > reference to the Mystery instance, then holds that strong reference > > > > until it returns. > > > > Ah, that was the missing part; I thought that anything accessed > > > through a proxy didn't create a strong reference. The good thing is > > > that it seems you can get a proxy to a bounded method and then call it > > > without creating a strong reference to 'self': > > > That's not right. Of course a bound method has a strong reference to > > self, otherwise you'd never be able to call it. There must be > > something else going on here. Try using sys.setcheckinterval(1) to > > make threads switch more often. > > I tried that and it still works; all objects die at the main thread. > Any other idea to break it ? Nothing comes to mind. However, none of this is guaranteed anyway, so you can't rely on it. __del__ might be called by any thread at any point (even when you're holding a lock, updating a datastructure.) From gagsl-py2 at yahoo.com.ar Mon Jun 16 02:33:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 16 Jun 2008 03:33:16 -0300 Subject: NoneType Error References: Message-ID: En Sun, 15 Jun 2008 05:35:18 -0300, Maryam Saeedi escribi?: > I am using a python program on a lot of different documents and for few of > them I will get NoneType error. I just want to skip those files and continue > for others, I do this without a problem for > IndexError,TypeError,ValueError,NameError : > > try: > .... > except (IndexError,TypeError,ValueError,NameError): > .... > > but when I add NoneType it gives the following error: > except (NoneType,IndexError,TypeError,ValueError,NameError): > NameError: name 'NoneType' is not defined > > and if I do not use the NoneType then it does not go through either and > stops the program when I get to such a file. Is there another name that > captures this error? NoneType is not an exception, but the type of the None object. Perhaps you're not interpreting correctly some error messages: >>> x=None >>> x() Traceback (most recent call last): File "", line 1, in TypeError: 'NoneType' object is not callable (the exception raised is a TypeError; NoneType is part of the message). It appears that you want to catch all exceptions, just use Exception for that: try: ... except Exception: ... -- Gabriel Genellina From kirk at daycos.com Mon Jun 16 15:39:28 2008 From: kirk at daycos.com (Kirk Strauser) Date: Mon, 16 Jun 2008 14:39:28 -0500 Subject: Good cross-host IPC? Message-ID: <87ve096ufj.fsf@internal.daycos.com> We've been using NetWorkSpaces (http://www.ddj.com/web-development/200001971) for IPC on programs running on several different machines. Since it uses a central, shared server for storing values, you don't have to write socket code in your various programs to pass data back and forth. For example, a program can request some work to be done by a random machine on the network like so: >>> from nws.client import NetWorkSpace >>> space = NetWorkSpace('test') >>> space.store('value', 42) >>> ws.fetch('results') 43 ...and a worker process can listen for work to do and return the results by doing: >>> from nws.client import NetWorkSpace >>> space = NetWorkSpace('test') >>> value = space.fetch('value') >>> space.store('results', value + 1) Since space.fetch() is a blocking call and the NetWorkSpaces server answers requests in the order that they're received, this is a nice way to coordinate a cluster. This is pretty spiffy and works great in practice, but it feels like we're the only people using it. Parallel Python lives in kind of the same problem space, but not all of our code is easily bent to its will. Is there another, more common way of doing this stuff? Popularity isn't the most important thing in the world, but I like the warm fuzzies of knowing that thousands of others are testing and using the same project as we are. -- Kirk Strauser The Day Companies From omer at no-log.org Sun Jun 15 10:14:03 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Sun, 15 Jun 2008 16:14:03 +0200 Subject: problem with Py_BuildValue In-Reply-To: References: Message-ID: <200806151614.03734.omer@no-log.org> Hi, > Hi, > > currently I have a problem understanding Py_BuildValue. I have this code: > > static PyObject *function(PyObject *self, PyObject *args) { > PyObject * python_return_value = NULL; > PyObject * dummy = NULL; > double * internal_list; > > > /* converting to python representation */ > for (i=0; i < limit; i++) { > dummy = Py_BuildValue("d", internal_list[i]); > if (!dummy) return NULL; > PyList_Append(python_return_value, dummy); > Py_DECREF(dummy); dummy = NULL; > } > return python_return_value > } > > This doesn't work. What I see, when invoking the function "function()" in > Python is a list of refcounts, like: [, 0x94a29e4>, ...]. However, if I change the Py_BuildValue-line to be > dummy = Py_BuildValue("i", (int)internal_list[i]); > I do get the 'right' integer return values. Point is that I really would > like to work with Python-floats afterwards. > > Any idea where a pitfall might be here? > I see nothing wrong with your code so I'd say it is somewhere else (did you snip any code between the end of the loop and the return?). I've never seen those 'refcnt' objects but a refcount of 0 sounds like you unrefed your objects one extra time by mistake. This would produce a segfault on unix, but maybe not on all platforms ? You should check the return value of PyList_Append() and if it doesn't help trace the content of your list after each iteration to see when the bad things happen (you can check the reference count of an object with obj->ob_refcnt). Finally note that in your case it would be much simpler and more efficient to use the float constructor directly: dummy = PyFloat_FromDouble(internal_list([i])) PS: always use Py_CLEAR(dummy) instead of Py_DECREF(dummy); dummy=NULL; (though it doesn't really matter in this simple case - see http://docs.python.org/api/countingRefs.html) -- C?dric Lucantis From joamag at gmail.com Sun Jun 22 16:23:14 2008 From: joamag at gmail.com (joamag) Date: Sun, 22 Jun 2008 13:23:14 -0700 (PDT) Subject: Way to unblock sys.stdin.readline() call References: <56b21108-45b4-4b9e-bda5-171c9ddc21ce@i76g2000hsf.googlegroups.com> Message-ID: <40203698-2b5d-4436-89e9-692360183d03@k37g2000hsf.googlegroups.com> On Jun 21, 11:34?pm, Terry Reedy wrote: > joamag wrote: > > Is there any possible way to unblock the sys.stdin.readline() call > > from a different thread. > > If you want the thread to do something 'else' when no input is > available, would this work? ?Put readline in a thread that puts lines in > a q=queue.Quese(). ?Then > try: > ? ? ?l=q.ge_nowait > ? ? ? > except queue.Empty > ? ? ? Yes, that would work but still I would have a thread that would block (the one with the readline call). The problem with that solution is that if I try to exit the application, while the thread is waiting in the readline call, that thread would be blocking the exit of the application. That behavior occurs even if the thread is configured in daemon mode. Do you think it?s possible to solve the readline blocking problem in any other way ? From 42flicks at gmail.com Tue Jun 10 22:29:44 2008 From: 42flicks at gmail.com (Mike) Date: Wed, 11 Jun 2008 14:29:44 +1200 Subject: Dynamic HTML from Python Script In-Reply-To: <484f3574$0$4998$607ed4bc@cv.net> References: <484f151c$0$5009$607ed4bc@cv.net> <484f21aa$1@dnews.tpgi.com.au> <484f24e9$0$5020$607ed4bc@cv.net> <484f2870$1@dnews.tpgi.com.au> <484f3574$0$4998$607ed4bc@cv.net> Message-ID: <2b54d4370806101929y643d7765pe5dc3876bb59bcde@mail.gmail.com> On Wed, Jun 11, 2008 at 2:16 PM, asdf wrote: > On Wed, 11 Jun 2008 11:20:48 +1000, Aidan wrote: > > > asdf wrote: > >>> Well, there's a few ways you could approach it. > >>> > >>> You could create a cgi program from your script - this is probably the > >>> solution you're looking for. > >>> > >>> > >> Output from the script does come up very often. There is a new output > >> every 10 secs and it's possible that the script might be run > >> indefinitely. Basically I want all that output displayed in a web > >> browser > > > > Well, in that case you could simply append the new output to a static > > file every 10 seconds, or whenever there is new output. That way, you > > just need to refresh the static file in your browser to see updates... > > Given what I understand of your situation, that's how I'd do it. > > > The problem with this is that browser would have to be refreshed manually > every 10 seconds. Unless there is a way to set this in the script itself. > > > > A constantly running CGI app is probably not the best idea, given > > timeouts and other such constraints you might run into. > > > > > >>> You could have the script run periodically and create a static html > >>> file in the webroot... this would be acceptable, maybe preferable, if > >>> the output from your script doesn't change frequently. > >>> > > -- > http://mail.python.org/mailman/listinfo/python-list > Sorry should have asked how often a user would be requesting new content. To avoid page refreshing I'd look into Django AJAX support, havn't tried it myself but will be soon. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Jun 13 03:42:55 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Jun 2008 09:42:55 +0200 Subject: Plotting Graphs + Bestfit lines References: <1a919a2b-6430-4e2e-a190-2e00e43a6138@25g2000hsx.googlegroups.com> <022d382b-0b7b-4757-855a-f07019791fcc@d45g2000hsc.googlegroups.com> <05e67e40-db9c-4d85-94c1-f0e31dd5da38@27g2000hsf.googlegroups.com> Message-ID: arslanburney at gmail.com wrote: > Tried that out too. No error however, best fit lines still not being > made on the graph. Only the 3 plot lines show up. Sorry, I don't know gnuplot, so I can't help you with any but the obvious (read: Python) errors. Peter From collinyeung at shaw.ca Thu Jun 12 00:29:56 2008 From: collinyeung at shaw.ca (Collin) Date: Thu, 12 Jun 2008 04:29:56 GMT Subject: =?windows-1256?Q?=E3=DE=D8=DA_=DD=ED=CF=ED=E6_=5B=C7=E1=E6?= =?windows-1256?Q?=E1=C7=CF=E5_=C7=E1=DE=ED=D5=D1=ED=E5=5D_=ED=E3=E4=DA?= =?windows-1256?Q?_=CF=CE=E6=E1_=D6=DA=C7=DD_=C7=E1=DE=E1=E6=C8?= In-Reply-To: References: Message-ID: <8D14k.25653$gc5.1766@pd7urf2no> a7labnt wrote: > ?????? VMware Workstation 6.0 > > http://www.antya7la.com/vb/t26858.html#post286993 > > ?????? ????? ??????? auto run ? folder option > > http://www.antya7la.com/vb/t26859.html#post286996 > > ?? ????? ???? ??? ?????? > > http://www.antya7la.com/vb/t26860.html#post286997 > > ??? ???? ?? Ftp ? 64 % + ??????? ?????? ? ????? ? ????? > > http://www.antya7la.com/vb/t26861.html#post286999 > > ???? ?? ????? ????? ?????.. ???????? > > http://www.antya7la.com/vb/t26862.html#post287000 > > ????? : ???? ????? ????? ?? ??????? - ??? ????? ?????? ?????? ! > > http://www.antya7la.com/vb/t26863.html#post287010 > > > ????? ?? ????? ??????? > > http://www.antya7la.com/vb/t27127.html#post289835 > > ??????? ??? ??? ??? ?????? ??????000????????? > > http://www.antya7la.com/vb/t27128.html#post289837 > > ????? - ???? ???????? > > http://www.antya7la.com/vb/t27129.html#post289839 > > ?? ??? ?? ?????? ???? ?????? ??? ????? ?? ???? ??????? > > http://www.antya7la.com/vb/t27130.html#post289841 > > ??? ?????? ?????? ???????? ???? ?????? > > http://www.antya7la.com/vb/t27131.html#post289843 > > ????? ????? ?? ???? > > http://www.antya7la.com/vb/t27132.html#post289845 > > ?????????? ???? ??????? ?? ??? ????? ?????? !! > > http://www.antya7la.com/vb/t27133.html#post289846 > > ????? ????? ?????? ???? > > http://www.antya7la.com/vb/t27135.html#post289851 > > ???? ?????? (?????????) ????? ???? ???? ?????? > > http://www.antya7la.com/vb/t27138.html#post289855 > > ?????? ??????? ?????? ???? ???? ?? ???? ???? ??? ?????? 5 ????? ????? > http://www.antya7la.com/vb/t27134.html#post289850 > > ???? ????? 300 ??? ???? 24 ????!!! > > http://www.antya7la.com/vb/t27139.html#post289859 > > ???? ???? ?? ?????? ??????????? ??????? ???????????? > > http://www.antya7la.com/vb/t26884.html#post289876 > > ???? ?? ????? ????? ????? ????? > > http://www.antya7la.com/vb/t26783.html#post289879 > > ????? ??? ?????? ?????? ???? ???? > > http://www.antya7la.com/vb/t26935.html#post289880 > > ??? ?????? ?? ???? ???? ?????? > > http://www.antya7la.com/vb/t26932.html#post289884 > > ????? ??? ??????!!????? ???? ?????? ????? ?????? ?? ?????? > > http://www.antya7la.com/vb/t26617.html#post289885 > > ????? ?????? ??? ??????........... > http://www.antya7la.com/vb/t26815.html#post289889 > > ?????? ??????? ? ???????? ?????? ??? !!! ?? ?????????????? > > http://www.antya7la.com/vb/t26914.html#post289893 > > ???? ????? [??????? ????????] ???? ???? ???? ?????? > > http://www.antya7la.com/vb/t26992.html#post289907 > > {{{ ??? ??? ?? ?????? ??? ???..!!}}} > > http://www.antya7la.com/vb/t26793.html#post289913 > > ??? ?????? ??? ???? > > http://www.antya7la.com/vb/t27081.html#post289912 > > ?? ?????? ??? ??????..#! > > http://www.antya7la.com/vb/t2223.html#post289911 > > ??????? ???? ??? ???????! > > http://www.antya7la.com/vb/t4378.html#post289915 > > > ????? Windows Xp ????? ????? ???!!!!! > > http://www.antya7la.com/vb/t21396.html#post242891 > > ?????? ??????? ??????? Internet Explorer 8 Beta 1 > > http://www.antya7la.com/vb/t21395.html#post242889 > > ????? Ares ?????? ?? ??? > > > http://www.antya7la.com/vb/t21394.html#post242887 > > ???? ??????? ?????? ?? ?????? KinG Fm ????? ???? ?? ?? ??????? ?? > ???????? ??? ?????, > > http://www.antya7la.com/vb/t21397.html#post242896 > > ?????? ??????? ??????? Internet Explorer 8 Beta 1 > > http://www.antya7la.com/vb/t21395.html#post242889 > > ????? ????!?? ???? ?????? ??????!????? On Speeeed, ?????? ?????? > ?????? ????????!???? > > http://www.antya7la.com/vb/t21398.html#post242898 > > The Logo Creator ?????? ???????? > > http://www.antya7la.com/vb/t21399.html#post242900 > > ?????? Driver Wizard ????? ?????? ????? ??????? > > http://www.antya7la.com/vb/t21400.html#post242913 > > > ????? ?????? ? ?????? ??? ????? ??? ??? ????? ????? ??????? ??? > ??????? ???? > > > http://www.antya7la.com/vb/t21401.html#post242914 > > ???? ??? ?????? ?? ????? ?????? ????? ???? ??! ???? ??????? > > > http://www.antya7la.com/vb/t21402.html#post242919 > > ?? ???? ???? ????? ????? ???WinXP ???? ?????? ?????? > > http://www.antya7la.com/vb/t21403.html#post242920 > > ?????? ?????? ???? ????? ?????! ????? 100% > > http://www.antya7la.com/vb/t21404.html#post242921 > > > Is this arabic spam? From frank at chagford.com Wed Jun 11 10:14:55 2008 From: frank at chagford.com (Frank Millman) Date: Wed, 11 Jun 2008 07:14:55 -0700 (PDT) Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: On Jun 11, 4:39?pm, Ethan Furman wrote: > Frank Millman wrote: > > Thanks to all for the various replies. They have all helped me to > > refine my ideas on the subject. These are my latest thoughts. > > Out of curiosity, what is the purpose of these numbers? ?Do they > represent money, measurements, or something else? I am writing a business/accounting application. The numbers represent mostly, but not exclusively, money. Examples - Multiply a selling price (scale 2) by a product quantity (scale 4) to get an invoice value (scale 2), rounded half-up. Multiply an invoice value (scale 2) by a tax rate (scale 2) to get a tax value (scale 2), rounded down. Divide a currency value (scale 2) by an exchange rate (scale 6) to get a value in a different currency (scale 2). Divide a product quantity (scale 4) by a pack size (scale 2) to get an equivalent quantity in a different pack size. In my experience, the most important thing is to be consistent when rounding. If you leave the rounding until the presentation stage, you can end up with an invoice value plus a tax amount differing from the invoice total by +/- 0.01. Therefore I always round a result to the required scale before 'freezing' it, whether in a database or just in an object instance. Frank From hniksic at xemacs.org Tue Jun 17 03:05:11 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 17 Jun 2008 09:05:11 +0200 Subject: String Concatenation O(n^2) References: <3fc761710806160941q3c1a93b5p7761fbe148718585@mail.gmail.com> <20080616170916.4714.1881297769.divmod.quotient.9773@ohm> Message-ID: <87k5gov8wo.fsf@mulj.homelinux.net> "Ian Kelly" writes: > On Mon, Jun 16, 2008 at 11:09 AM, Jean-Paul Calderone > wrote: >> It will depend what version of Python you're using and the *exact* details >> of the code in question. An optimization was introduced where, if the >> string being concatenated to is not referred to anywhere else, it will be >> re-sized in place. This means you'll probably see sub-quadratic behavior, >> but only with a version of Python where this optimization exists and only >> if the code can manage to trigger it. > > AFAICT, PyString_Concat never calls _PyString_Resize. Am I looking > in the wrong place? Take a look at ceval.c:string_concatenate. As Jean-Paul says, note that the optimization doesn't work in many circumstances. For example, change local variable to instance attribute, and it goes away. Other python implementations don't have it at all. From eric.acevedo at gmail.com Fri Jun 13 10:15:44 2008 From: eric.acevedo at gmail.com (ericdaniel) Date: Fri, 13 Jun 2008 07:15:44 -0700 (PDT) Subject: Create list from string Message-ID: Hi, I'm new to Python and I need to do the following: from this: s = "978654321" to this : ["978", "654", "321"] Any help is appreciated Thanks, Eric From malaclypse2 at gmail.com Wed Jun 11 16:42:33 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 11 Jun 2008 16:42:33 -0400 Subject: problems with opening files due to file's path In-Reply-To: <17786320.post@talk.nabble.com> References: <17759531.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> <77acc29a-fffa-44d6-b07b-6bcf8b5bdd74@h1g2000prh.googlegroups.com> <17786320.post@talk.nabble.com> Message-ID: <16651e80806111342k1d2d0b3ay9a558452f48fc2d9@mail.gmail.com> On Wed, Jun 11, 2008 at 4:16 PM, Alexnb wrote: > > I posted the underlying code, but I haven't made the GUI code because if I > can't get the underlying code right it doesn't matter, well in my eyes it > doesn't but I am probably wrong. But it will look somehting like this: What you're missing is that all of the problems you're having with escape characters *only apply to string literals inside your python source code.* If you're getting the string from the console, you don't need to escape or change anything. If you're getting the string from a Tk text box, you don't need to escape or change anything. If you're getting the string from the filesystem, you don't need to escape or change anything. The only place you have to be careful is when you type out a literal string inside your .py source code. When you do that, you need to properly escape backslashes, either by putting them in raw strings, or by doubling up your backslashes. If you haven't already, reread the section of the python tutorial about string literals: http://docs.python.org/tut/node5.html. -- Jerry From mensanator at aol.com Mon Jun 23 13:53:43 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 23 Jun 2008 10:53:43 -0700 (PDT) Subject: Question: How do I format printing in python References: <2e43cbba-bcd1-492e-97aa-bf8d2708d665@26g2000hsk.googlegroups.com> Message-ID: On Jun 23, 12:47?pm, Mensanator wrote: > On Jun 23, 12:12?pm, joemacbusin... at yahoo.com wrote: > > > > > > > Hi All, > > > How do I format printed data in python? > > I could not find this in the Python Reference Manual:http://docs.python.org/ref/print.html > > Nor could I find it in Matloff's great tutorial:http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf > > > For example, how do I turn this: > > > 512 Jun 5 2004 X11r6 > > 22 Jan 17 2005 a2p > > 22 Jan 17 2005 acctcom > > 5374 Sep 15 2002 acledit > > 5664 May 13 2004 aclget > > 12020 May 13 2004 aclput > > 115734 Jun 2 2004 adb > > 46518 Jun 4 2004 admin > > 66750 Sep 16 2002 ali > > 1453 Sep 15 2002 alias > > 28150 Jun 4 2004 alog > > 15 May 12 2005 alstat > > > into this: > > > 512 ? ? ? ?Jun ? 5 ? 2004 ? ?X11r6 > > 22 ? ? ? ? Jan ? 17 ?2005 ? ?a2p > > 22 ? ? ? ? Jan ? 17 ?2005 ? ?acctcom > > 5374 ? ? ? Sep ? 15 ?2002 ? ?acledit > > 5664 ? ? ? May ? 13 ?2004 ? ?aclget > > 12020 ? ? ?May ? 13 ?2004 ? ?aclput > > 115734 ? ? Jun ? 2 ? 2004 ? ?adb > > 46518 ? ? ?Jun ? 4 ? 2004 ? ?admin > > 66750 ? ? ?Sep ? 16 ?2002 ? ?ali > > 1453 ? ? ? Sep ? 15 ?2002 ? ?alias > > 28150 ? ? ?Jun ? 4 ? 2004 ? ?alog > > 15 ? ? ? ? May ? 12 ?2005 ? ?alstat > > > Thank you > > You could do this: > > data = ['512 Jun 5 2004 X11r6 ', \ > '22 Jan 17 2005 a2p', \ > '22 Jan 17 2005 acctcom ', \ > '5374 Sep 15 2002 acledit ', \ > '5664 May 13 2004 aclget ', \ > '12020 May 13 2004 aclput ', \ > '115734 Jun 2 2004 adb ', \ > '46518 Jun 4 2004 admin ', \ > '66750 Sep 16 2002 ali ', \ > '1453 Sep 15 2002 alias ', \ > '28150 Jun 4 2004 alog ', \ > '15 May 12 2005 alstat '] > > for i in data: > ? d = i.split() > ? print d[0].ljust(9), > ? print d[1].ljust(6), > ? print d[2].ljust(4), > ? print d[3].ljust(7), > ? print d[4].ljust(9) > > which gives you > > 512 ? ? ? Jun ? ?5 ? ?2004 ? ?X11r6 > 22 ? ? ? ?Jan ? ?17 ? 2005 ? ?a2p > 22 ? ? ? ?Jan ? ?17 ? 2005 ? ?acctcom > 5374 ? ? ?Sep ? ?15 ? 2002 ? ?acledit > 5664 ? ? ?May ? ?13 ? 2004 ? ?aclget > 12020 ? ? May ? ?13 ? 2004 ? ?aclput > 115734 ? ?Jun ? ?2 ? ?2004 ? ?adb > 46518 ? ? Jun ? ?4 ? ?2004 ? ?admin > 66750 ? ? Sep ? ?16 ? 2002 ? ?ali > 1453 ? ? ?Sep ? ?15 ? 2002 ? ?alias > 28150 ? ? Jun ? ?4 ? ?2004 ? ?alog > 15 ? ? ? ?May ? ?12 ? 2005 ? ?alstat > > or perhaps this: > > for i in data: > ? d = i.split() > ? print d[0].rjust(9), > ? print d[1].ljust(6), > ? print d[2].zfill(2).ljust(4), > ? print d[3].ljust(7), > ? print d[4].ljust(9) > > which gives this (if you want the digits in the numbers to > line up): > > ? ? ? 512 Jun ? ?05 ? 2004 ? ?X11r6 > ? ? ? ?22 Jan ? ?17 ? 2005 ? ?a2p > ? ? ? ?22 Jan ? ?17 ? 2005 ? ?acctcom > ? ? ?5374 Sep ? ?15 ? 2002 ? ?acledit > ? ? ?5664 May ? ?13 ? 2004 ? ?aclget > ? ? 12020 May ? ?13 ? 2004 ? ?aclput > ? ?115734 Jun ? ?02 ? 2004 ? ?adb > ? ? 46518 Jun ? ?04 ? 2004 ? ?admin > ? ? 66750 Sep ? ?16 ? 2002 ? ?ali > ? ? ?1453 Sep ? ?15 ? 2002 ? ?alias > ? ? 28150 Jun ? ?04 ? 2004 ? ?alog > ? ? ? ?15 May ? ?12 ? 2005 ? ?alstat In retrospect, that looks kind of clunky. If it was for my use, I'd do for i in data: d = i.split() print d[0].rjust(9), print d[1].rjust(6), print d[2].zfill(2), print d[3].ljust(7), print d[4].ljust(9) which looks like: 512 Jun 05 2004 X11r6 22 Jan 17 2005 a2p 22 Jan 17 2005 acctcom 5374 Sep 15 2002 acledit 5664 May 13 2004 aclget 12020 May 13 2004 aclput 115734 Jun 02 2004 adb 46518 Jun 04 2004 admin 66750 Sep 16 2002 ali 1453 Sep 15 2002 alias 28150 Jun 04 2004 alog 15 May 12 2005 alstat From Lie.1296 at gmail.com Sun Jun 1 14:29:29 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 1 Jun 2008 11:29:29 -0700 (PDT) Subject: How to get all the variables in a python shell References: Message-ID: <61f7681d-5cd3-4093-96f9-82f0e7383217@y38g2000hsy.googlegroups.com> lixinyi... at gmail.com wrote: > Hi! > > I'm currently working on a scientific computation software built in > python. > What I want to implement is a Matlab style command window <-> > workspace interaction. > > For example, you type 'a=1' in the command window, and you see a list > item named 'a' in the workspace. > You double click the icon of the item, and you see its value. You can > modify the value of the list item, > 1 -> 100 etc, after which if you go back to the command window and > type 'a' and press enter, you see that > varable a's value has been changed to 100. > > So my question is : if you have two DOS command windows running under > WINDOWS OS, how can you make them share the same internal variable > buffer? Or is there any easier way to implement such kind of > interaction? > > Maybe I could just build a small database to store all the values and > access them from both programs, but chances are sometimes I have to > deal with big arrays, and they will eat extra memory if I keep them in > a database. Is there anyway to access a shell's local memory buffer? > I tried to use shell.interp.locals() in wxPython, but there's too many > variables in the list which I don't actually need. > > Come on guys, give me some ideas. Thanks in advance! In all kinds of code, it's best to seperate the workers code and the UI code, in your case, you should create a backend (worker), which is a class that stands on its own, and two foreground class (UI) that is completely independent of each other but have the same interface. The backend code would have an event that is raised when it is changed to notify the UI (esp. The gui one) that it has changed since last time, possibly passing info on what have been changed. The front ends, would watch for this event as necessary (I don't think it is necessary for the command line to watch this event) and react to it as necessary like refreshing the view. The front-end window may only call functions on the backend to interact with the data being worked on (in short the backend class is opaque). This obliviate the need to share data between the two (or more) windows (UI) because all the data are contained in the backend class that the frontend can't access directly. From brendon at christian.net Fri Jun 20 01:09:38 2008 From: brendon at christian.net (Brendon Costa) Date: Thu, 19 Jun 2008 22:09:38 -0700 (PDT) Subject: How do i : Python Threads + KeyboardInterrupt exception References: <089f56d2-5e44-4161-b580-84881717bd05@w4g2000prd.googlegroups.com> <6cfbfaa2-293f-41d3-b544-fd47f05d0d36@j33g2000pri.googlegroups.com> Message-ID: <93eb3402-1dde-4ad3-b91f-d4b091048ac0@g16g2000pri.googlegroups.com> > If only the main thread can receive KeyboardInterrupt, is there any > reason why you couldn't move the functionality of the Read thread into > the main thread? It looks like it's not doing any work, just waiting > for the Proc thread to finish. > > You could start the Proc thread, do the current Read thread > functionality until the interrupt occurs, put the apporpriate message > in the queue, and then wait for the Proc thread to finish. It is already doing that. You will notice that the Proc() function is called by a threading.Thread instance so Proc() is running in a thread, but the Read() function is being called by the main thread right after this. It DOES work with the Ctrl + C, but i can find no way at all of closing down the script from within the Proc() thread. The relevant bit of code is: t = MyThread(Proc, queue, sys.stderr, None) Read(queue, sys.stdin, sys.stderr) In the end, the problem is that i am trying to multiplex IO and other operations. In UNIX i would use select with the input file descriptor and an anonymous pipe for the extra commands to achieve this without any threads, but this script needs to run primarily on a windows box and i would like to use it on UNIX too. I thought i could use threads to achieve the IO Multiplexing in python, but it seems not or at least not simply. How do people usually manage IO multiplexing (not just using sockets) cross platform in python? I only need to multiplex two sources really: * Input file or stdin * A input event queue This will have messages injected from various locations: timers, the processing thread itself, and possibly from a single GUI thread at a later point in time. Though i can foresee that at some point in the future i may also need to multiplex those two above and some sockets (For a server with a few clients). I was thinking of looking at some asynchronous IO libraries for python on Windows + UNIX, any suggestions (Must include more than just sockets)? From afanning at pbtcomm.net Wed Jun 18 23:24:36 2008 From: afanning at pbtcomm.net (George) Date: Wed, 18 Jun 2008 23:24:36 -0400 Subject: moyea flv to video converter keygen Message-ID: <000501c8d1bc$00bde180$0200000a@GEORGECOMPUTER> got error on your page -------------- next part -------------- An HTML attachment was scrubbed... URL: From mattheww at chiark.greenend.org.uk Wed Jun 18 12:50:04 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 18 Jun 2008 17:50:04 +0100 (BST) Subject: Getting Python exit code when calling Python script from Java program References: Message-ID: In article , > I tried using the sys.exit() method in my script and passed non -zero > values. However the value wasn't picked up the by Java > Process.exitValue() method - it kept picking up 0. On investigation > it turned out that the exit value being read is from python.exe > process, not from the Python script. I don't believe there is any such distinction. The exit status of python.exe is the exit status determined by the script. -M- From cashm491 at gmail.com Sat Jun 28 04:01:56 2008 From: cashm491 at gmail.com (casahm491@gmail.com) Date: Sat, 28 Jun 2008 01:01:56 -0700 (PDT) Subject: Money In Us $ No Investment Except Minimum Time Daily!!! Message-ID: <72ada42a-01bd-4c18-9a4b-22433d835889@i18g2000prn.googlegroups.com> Worth Clicking If You Mean Time = Money In Us $ No Investment Except Minimum Time Daily! You Will Reveal A Great Home Business Opportunity By Opening The Below Link. http://www.govindswamy-govindaswamy.blogspot.com You Will Be Paid 2 US DOLLARS For Each Member Joining Under You (Provided they should also work actively) To Enroll Members You Can Use google groups Or Any Other Free Ads. 100% LEGAL - 100% PROFIT - 100% GROWTH - 100% TIME EFFORT You Should Work Proactively Otherwise You Cannot Reap The Fruit. This Does'ne Make You Rich Just Clicking This. But Useful To Earn Extra Money When You Find Free Time. Hey Wait. Think Well Before You Close Or You Will Loose Your Money. http://www.govindswamy-govindaswamy.blogspot.com NOTE: This Message Is Intended To Those Who Are Interested To Earn Money Through Online. Others Please Excuse. http://alt.com/go/g900909-pmem www.govindaswamy10.blogspot.com www.kavigovindan.blogspot.com www.govindaswamy1.blogspot.com www.govindaswamy-amman.blogspot.com From tdahsu at gmail.com Sat Jun 14 19:39:37 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Sat, 14 Jun 2008 16:39:37 -0700 (PDT) Subject: os.walk Value Error? References: Message-ID: On Jun 14, 7:11?pm, Larry Bates wrote: > tda... at gmail.com wrote: > > Hi, > > > I'm using os.walk as follows: > > > (basedir, pathnames, files) = os.walk("results", topdown=True) > > > and I'm getting the error: > > > ValueError: too many values to unpack > > > From my googling, that means: > > > This is the standard message when Python tries to unpack a tuple > > into fewer variables than are in the tuple. > > > From what I can see of the examples on the python site, I'm using it > > correctly. ?I have commas in my original code, and the "results" > > directory exists and is directly under the directory from which my > > script is run. > > > I'm assuming that 12 files (the number of files in the "results" > > directory) is not too many for Python to handle! ?;-) > > > Is there any other reason I might get that error? > > os.walk is a generator so you need to make it a loop target: > > for basedir, pathnames, files in os.walk("results"): > ? ? ?# > ? ? ?# Do you work inside the loop > ? ? ?# > > -Larry Thanks! From robin at alldunn.com Wed Jun 25 15:20:20 2008 From: robin at alldunn.com (Robin Dunn) Date: Wed, 25 Jun 2008 12:20:20 -0700 Subject: ANN: wxPython 2.8.8.0 Message-ID: <48629A74.2030109@alldunn.com> Announcing ---------- The 2.8.8.0 release of wxPython is now available for download at http://wxpython.org/download.php. This release has had a number of further refinements and enhancements on the stable 2.8 source tree since the previous release. On Mac OS X 10.5 (Leopard) the Python 2.5 binaries of wxPython are able to be used with either Apple's system Python, or with the Python.org version. Source code is available, as well as binaries for Python 2.3, 2.4 and 2.5, for Windows and Mac, as well some packages for various Linux distributions. A summary of changes is listed below and also at http://wxpython.org/recentchanges.php. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit Microsoft Windows, most Linux or other Unix-like systems using GTK2, and Mac OS X 10.3+, in most cases the native widgets are used on each platform to provide a 100% native look and feel for the application. Changes in 2.8.8.0 ------------------ Added the PlateButton class from Cody Precord. Added wx.PyEvtHandler, which supports overriding the ProcessEvent method in derived classes. Instances of this class can be pushed onto the event handler chain of a window in order to hook into the event processing algorithm, and its ProcessEvent method will be called for every event sent to the window. With much help from Anthony Tuininga the code generated by the img2py tool is now cleaner, simpler and smaller. Instead of writing the data for the images as printable ascii with hex escapes it now uses base64 to encode the images into a string. In addition, instead of top-level functions for returning the image data and bitmaps, the embedded images now use a simple class with methods for returning the image as a bitmap, icon, or etc. By default in 2.8.x top-level aliases will be generated to make the code backward compatible with the old functional interface, but you can use -F to turn that off. In 2.9 and beyond the default will be to generate only the new class interface, but -f can be used to turn the old behavior back on. The PyEmbeddedImage class added for the new img2py support can also be used for image data that may be acquired from some other source at runtime, such as over the network or from a database. In this case pass False for isBase64 (unless the data actually is base64 encoded.) Any image type that wx.ImageFromStream can handle should be okay. See the wx.lib.embeddedimage module for details. Exposed the wx.GenericDatePickerCtrl to wxPython. On wxGTK and wxMac this is exactly the same as the normal date picker, but on wxMSW it allows you to avoid the native wx.DatePickerCtrl if so desired. Also fixed a bug that caused an assert if you tried to set the date to wx.DefaultDateTime even if wx.DP_ALLOWNONE was specified. Made a little hack in wx.lib.masked.TextCtrl that allows it to be wrapped around an already existing TextCtrl instead of always creating its own. This is useful for example with the wx.TextCtrl that is built-in to the customizable wx.combo.ComboCtrl, or with a textctrl that is part of an XRC layout. To use it you need to do a little trick like this:: existingTextCtrl = combo.GetTextCtrl() maskedCtrl = wx.lib.masked.TextCtrl.__new__(wx.lib.masked.TextCtrl) maskedCtrl.this = existingTextCtrl.this maskedCtrl.__init__(parent) Enhanced the Widget Inspection Tool with some new functionality. Added tools to the toolbar to expand and collapse the widget tree, which is very helpful for not getting lost in very large applications with many hundreds of widgets. Also added a toolbar tool for highlighting the currently selected widget or sizer in the live application. The tool will flash top-level windows and for all other items it will draw an outline around the item for a few seconds. Copied the sized_controls module to the wx.lib package as the first step of phasing out the wxaddons package. Added an implementation of wx.Window.SetDoubleBuffered on Windows. (GTK already has one, and Mac doesn't need one because everything is always double buffered by the system there.) Added a wrapper to wx.TopLevelWindow for MacGetTopLevelWindowRef to facilitate calling the Carbon APIs directly for things that are not supported in wx, similar to how we can use ctypes or PyWin32 with window.GetHandle() to do custom stuff on Windows. (On wxMac GetHandle returns the ControlRef, which is different than the WindowRef, hence the need for a 2nd method.) Here is an example to set the modified flag in the caption:: >>> import ctypes >>> carbon = ctypes.CDLL('/System/Library/Carbon.framework/Carbon') >>> carbon.SetWindowModified(frame.MacGetTopLevelWindowRef(), True) Added a new light-weight solution for embedding ActiveX controls in wxPython applications that uses ctypes and the comtypes package available from http://starship.python.net/crew/theller/comtypes/. Comtypes allows us to use and provide an interface with full dynamic dispatch abilities, much like PyWin32's COM interfaces but with much reduced external dependencies. See wx/lib/activex.py for more details. IMPORTANT: Be sure to get at least version 0.5 of comtypes, see the docstring in the wx.lib.activex module for details. The wx.lib.iewin, wx.lib.pdfwin, and wx.lib.flashwin modules were switched to use the new and improved activex module. The APIs provided by these modules should be mostly compatible with what was there before, except for how the COM events are handled. Instead of sending wx events it relies on you overriding methods with the same names as the COM events. You can either do it in a or derived class, or you can set an instance of some other class to be the event sink. See the ActiveX_IEHtmlWindow sample in the demo for an example. If you would rather continue to use the old version of these modules they are available in the wx.lib with "_old" added to the names. Added the wx.lib.resizewidget module. This module provides the ResizeWidget class, which reparents a given widget into a specialized panel that provides a resize handle for the widget. When the user drags the resize handle the widget is resized accordingly, and an event is sent to notify parents that they should recalculate their layout. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From casey.mcginty at gmail.com Fri Jun 27 21:47:43 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Fri, 27 Jun 2008 15:47:43 -1000 Subject: Help with Borg design Pattern In-Reply-To: References: Message-ID: On Fri, Jun 27, 2008 at 3:21 PM, Casey McGinty wrote: > Hi, > > I'm trying to implement a simple Borg or Singleton pattern for a class that > inherits from 'dict'. Can someone point out why this code does not work? > > class MyDict( dict ): > __state = {} > def __init__(self): > self.__dict__ = self.__state > > a = MyDict() > a['one'] = 1 > a['two'] = 2 > > print a > print MyDict() > > This looks like a good solution: class MyDict( dict ): def __new__(cls,*p,**k): if not '_instance' in cls.__dict__: cls._instance = dict.__new__(cls) return cls._instance -------------- next part -------------- An HTML attachment was scrubbed... URL: From fc14301589 at icqmail.com Fri Jun 13 03:24:58 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Fri, 13 Jun 2008 15:24:58 +0800 Subject: Debuggers Message-ID: <485220ca_1@news.tm.net.my> Hi, while testing my program I found some strange happening with pdb and pydb. I like pydb because let me restart the program and nicer features, but if errors pop up, then it will forget all variables (globals and locals gone). I've to go for pdb because it isn't affected by that problem, but also in some case pdb doesn't recognize a fix after a post-mortem restart. The funny thing is that it shows the line corrected, but pdb execute the one it put in memory. However, I think also python shell has such flaw. I'd like to know how to blank all current data and restart a program or re-import a corrected class sentence. Any other to try? I'm also prone to use Ipython, but I still miss some learning how to run a program within Ipython itself. So if I do: import myprogram myprogram.__main__ Will it run? And then the other arguments from CLI, how do I pass them in? -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 30 07:10:54 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 30 Jun 2008 13:10:54 +0200 Subject: Why is recursion so slow? In-Reply-To: References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> Message-ID: <4868bf3e$0$26061$426a34cc@news.free.fr> Dan Upton a ?crit : > On Sun, Jun 29, 2008 at 1:27 AM, Terry Reedy wrote: >> >> slix wrote: >>> Recursion is awesome for writing some functions, like searching trees >>> etc but wow how can it be THAT much slower for computing fibonacci- >>> numbers? >> The comparison below has nothing to do with recursion versus iteration. (It >> is a common myth.) You (as have others) are comparing an exponential, >> O(1.6**n), algorithm with a linear, O(n), algorithm. >> > > FWIW, though, it's entirely possible for a recursive algorithm with > the same asymptotic runtime to be wall-clock slower, just because of > all the extra work involved in setting up and tearing down stack > frames and executing call/return instructions. (If the function is > tail-recursive you can get around this, though I don't know exactly > how CPython is implemented and whether it optimizes that case.) By decision of the BDFL, based on the argument that it makes debugging harder, CPython doesn't optimize tail-recursive calls. From larry.bates at websafe.com` Thu Jun 5 15:36:17 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 05 Jun 2008 14:36:17 -0500 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: References: Message-ID: Gabriel Rossetti wrote: > Hello everyone, > > I had read somewhere that it is preferred to use > self.__class__.attribute over ClassName.attribute to access class (aka > static) attributes. I had done this and it seamed to work, until I > subclassed a class using this technique and from there on things started > screwing up. I finally tracked it down to self.__class__.attribute! What > was happening is that the child classes each over-rode the class > attribute at their level, and the parent's was never set, so while I was > thinking that I had indeed a class attribute set in the parent, it was > the child's that was set, and every child had it's own instance! Since > it was a locking mechanism, lots of fun to debug... So, I suggest never > using self.__class__.attribute, unless you don't mind it's children > overriding it, but if you want a truly top-level class attribute, use > ClassName.attribute everywhere! > > I wish books and tutorials mentioned this explicitly.... > > Gabriel If you define a class instance variable with the same name as the class attribute, how would Python be able to distinguish the two? That is a feature not a problem. Getter looks for instance attribute, if one is not found it looks for a class attribute, and upwards. This behavior is used by Zope to do all sorts of neat stuff. -Larry Bates From alexnbryan at gmail.com Tue Jun 10 23:07:25 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 10 Jun 2008 20:07:25 -0700 (PDT) Subject: problems with opening files due to file's path In-Reply-To: References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> Message-ID: <17769178.post@talk.nabble.com> I don't think you understand it doesn't matter how the variable gets there, the same code is run regardless, I have no problem with the GUI, but you asked, and so I told you. the code os.startfile(.... is run if there is a GUI or it is a console app. Carsten Haese-2 wrote: > > Alexnb wrote: >> Okay, I don't understand how it is too vague, but here: >> > > [snip a bunch of irrelevant examples...] >> >> Did I clarify? > > No. Earlier you wrote: > >>> On 2008-06-11, Alexnb wrote: >>>> I am using GUI, Tkinter to be exact. But regardless of how the >>>> path gets there, it needs to opened correctly. > > This implies that the file doesn't get opened correctly if the file name > is entered/chosen in the GUI. Yet, the examples you posted don't contain > any GUI code whatsoever. They merely demonstrate that you don't have a > firm grasp on how backslashes in string literals are treated. > > So, this begs the question, do you actually have any GUI code that is > failing, or are you just worried, given the problems you had with string > literals, that the GUI code you have yet to write will fail in the same > way? > > If this is the case, you should just write the GUI code and try it. It > might just work. Backslashes entered into a GUI text box are not treated > the same as backslashes in a Python string literal. > > If, on the other hand, you do have some GUI code for getting the file > name from the user, and that code is failing, then please, show us THAT > CODE and show us how it's failing. > > -- > Carsten Haese > http://informixdb.sourceforge.net > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17769178.html Sent from the Python - python-list mailing list archive at Nabble.com. From kyosohma at gmail.com Thu Jun 19 13:18:08 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 19 Jun 2008 10:18:08 -0700 (PDT) Subject: Simple wxPython SetLabel question References: <005654a8-3406-4063-8e06-d7cf567b96d6@z66g2000hsc.googlegroups.com> Message-ID: <6b412f33-55c8-42af-a25f-929e013a9be4@u6g2000prc.googlegroups.com> On Jun 19, 5:25?am, dp_pearce wrote: > Thank you very much C?dric. I thought it would be something very > straight forward. Just an FYI. There's also a wxPython specific mailing list that I highly recommend. You can learn a lot just reading other people issues and how they get them fixed. Here's the link: http://wxpython.org/maillist.php ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org From mdw at distorted.org.uk Wed Jun 18 06:26:33 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Wed, 18 Jun 2008 10:26:33 +0000 (UTC) Subject: Multiprecision arithmetic library question. References: Message-ID: Michael Press wrote: > I already compiled and installed the GNU multiprecision library > on Mac OS X, and link to it in C programs. > How do I link to the library from Python? You know that Python already supports multiprecision integer arithmetic, right? If you desperately want GMP, though, there's the gmpy module (q.g.). -- [mdw] From ubershmekel at gmail.com Wed Jun 18 02:47:56 2008 From: ubershmekel at gmail.com (Yuvgo0ogle GreeGma1l) Date: Wed, 18 Jun 2008 09:47:56 +0300 Subject: import this Message-ID: <9d153b7c0806172347w1dbc31edkcf94ff34d39e9b11@mail.gmail.com> This guy posted himself singing "import this" aka The Zen Of Python by Tim Peters... http://www.youtube.com/watch?v=kYB72Qa6F9I -- Yuv www.BasementPhilosophy.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From goldnery at gmail.com Wed Jun 25 13:47:41 2008 From: goldnery at gmail.com (Gandalf) Date: Wed, 25 Jun 2008 10:47:41 -0700 (PDT) Subject: Notice For All pyHook users Message-ID: <7e8718e7-2c75-4120-9ba3-dbd1669100f5@a1g2000hsb.googlegroups.com> If you want to compile your program the new py2exe release 0.6.8 wont work! the pyhook function will be ignored you'll have to uninstall the 0.6.8 version and to install the 0.6.6 instead it took me 2 days to find the solution. maybe some day someone will bump the same problem and find this message through google From goldnery at gmail.com Thu Jun 12 22:40:35 2008 From: goldnery at gmail.com (Gandalf) Date: Thu, 12 Jun 2008 19:40:35 -0700 (PDT) Subject: Charset (hopefully for the last time I ask) References: <9a899d5a-fb53-4fd7-8e61-89a04a35c780@d77g2000hsb.googlegroups.com> Message-ID: <1b9e3fab-f938-4e5b-9957-3e9afcd58b99@m36g2000hse.googlegroups.com> OK it did worked! I just should have been encoding to cp1255 search=cnrl.GetValue() search= search.encode("cp1255") cur.execute('select * from hebrew_words where word like ?', ['%'+search+'%']) Thank you! you are the best From google at mrabarnett.plus.com Wed Jun 25 12:05:19 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 25 Jun 2008 09:05:19 -0700 (PDT) Subject: Problems with file IO in a thread, and shutil References: Message-ID: On Jun 25, 4:11?pm, Roopesh wrote: > Hi, > > I have a multithreaded application. There are two threads, T1 and T2. > Suppose that there are two folders A, B. ?Thread T1 fetches data from > network and creates files in folder A and after creating each file, it > moves the file to folder B, using shutil.move(). > > Thread T2, takes files from folder B and processes it. > Note: Only the thread T1 has access to the files in folder A. > > psuedo code > ========= > class T1(thread): > ? ?def run(): > ? ? ?self.download() > > ? def download(): > ? ? ?data = from_network > ? ? ?filename = os.path.join ( "A", "file1") > > ? ? ?f = open ( filename, "w") > ? ? ?for d in data: > ? ? ? ? f.write ( d + "\n" ) > ? ? ?f.flush() > ? ? ?f.close() > > ? ? shutil.move(os.path.join ( "A", "file1"), ?os.path.join("B", > "file1")) > > class T2(thread): > ? run() > ? ? ? process(listdir(os.path.join("B"))) > > All the files has similar contents. But in some cases(very rare), when > thread T1 tries to move the newly created file from folder A to folder > B, an exception occurs (on shutil.move()). > > The exception is WindowsError(32, 'The process cannot access the file > because it is being used by another process'). I looked inside the > shutil.move. What I found was due to this WindowsError, the usual > os.rename() inside shutil.move() fails and the file is copied using > copy2(src, dst). Finally os.unlink() also failed. (So though copying > occurred, deleting the source file failed) > > I am not getting why this error comes. Has anyone faced similar > situation? Please help me. > > Thanks and Regards > Roopesh Do you have any anti-virus/anti-spyware software installed? (If not, why not? :-)) It might be that your anti-virus/anti-spyware software is seeing the new file appear and scanning it. If that happens just when shutil.move() attempts to move it then the move will fail. You could have your code wait for a while and then try again. From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 16 05:29:09 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 16 Jun 2008 11:29:09 +0200 Subject: NoneType Error In-Reply-To: References: Message-ID: <48563265$0$24303$426a74cc@news.free.fr> Gabriel Genellina a ?crit : > En Sun, 15 Jun 2008 05:35:18 -0300, Maryam Saeedi escribi?: (snip) > It appears that you want to catch all exceptions, just use Exception for that: > try: > ... > except Exception: > ... > Hem... That's definitively *not* an a good advice here IMHO. A catch-all may be useful near a program's 'top-level' to handle any other unhandled exception in a more user-friendly way (ie : log the error, warns whoever is in charge, try to cleanly dispose of resources / data / whatever so we don't break anything, and display a nice and visible error message to the user), but anywhere else you really want to know *exactly* which exception(s) you're expecting to handle here and let the other propagate. From sweeneym at acm.org Mon Jun 16 22:38:31 2008 From: sweeneym at acm.org (sweeneym at acm.org) Date: Mon, 16 Jun 2008 19:38:31 -0700 (PDT) Subject: Simple and safe evaluator References: <1de31143-7d8e-42e9-ae9d-8b0a0274ddc3@e53g2000hsa.googlegroups.com> Message-ID: On Jun 17, 8:02 am, bvdp wrote: > Thanks. That was easy :) > > > The change to the _ast version is left as an exercise to the reader ;) > > And I have absolutely no idea on how to do this. I can't even find the > _ast import file on my system. I'm assuming that the _ast definitions > are buried in the C part of python, but that is just a silly guess. > > Bob. If you just need numeric expressions with a small number of functions, I would suggest checking the expression string first with a simple regular expression, then using the standard eval() to evaluate the result. This blocks the attacks mentioned above, and is simple to implement. This will not work if you want to allow string values in expressions though. import re def safe_eval( expr, safe_cmds=[] ): toks = re.split( r'([a-zA-Z_\.]+|.)', expr ) bad = [t for t in toks if len(t)>1 and t not in safe_cmds] if not bad: return eval( expr ) >>> safe_eval( "abs(5*-77+33.1) + (int(405.3) * 5.7e-12)", 'int float sum abs'.split() ) 351.9000000023085 >>> safe_eval( "abs(5*-77+33.1) + (int(405.3) * 5.7e-12)" ) >>> safe_eval( "open('thesis.tex').write('')" ) >>> Mike. From cfbolz at gmx.de Thu Jun 5 19:46:52 2008 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Fri, 06 Jun 2008 01:46:52 +0200 Subject: How "solid" is PyPy? In-Reply-To: <335dcaaa-ac21-4526-91c2-d308b8693c34@e53g2000hsa.googlegroups.com> References: <335dcaaa-ac21-4526-91c2-d308b8693c34@e53g2000hsa.googlegroups.com> Message-ID: <48487AEC.5040707@gmx.de> Hi, miller.paul.w at gmail.com wrote: > I've been looking at PyPy recently, and I see it's reached version 1.0 > (and supports language version 2.4). Given that, I was wondering what > level of backwards-compatibility one can expect from future versions, > i.e. if I run code on, say, a translated stackless PyPy now, what is > the probability that it will run unmodified on PyPy 1.x, 2.x, etc.? That's hard to say. Nobody is using PyPy in any sort of production system yet, so the PyPy team is currently focused mostly on actually becoming useful. Nobody really has a clue what sort of solutions for backward compatibility we will have. Note also that the 1.0 release is sort of oldish already (but no new release has been made). Most people just use SVN head, which is quite stable. Cheers, Carl Friedrich Bolz From basti.wiesner at gmx.net Mon Jun 23 15:46:05 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Mon, 23 Jun 2008 21:46:05 +0200 Subject: Going from Tkinter to pyQT References: Message-ID: Alex Bryan : > I had a guy on this mailing list tell me that pyQT is much better than > Tkinter, and after looking into it a bit I think he is right. However, > I can't find much on it. I want to know if there are any good books or > online tutorials that would be helpful. I doubt there is one, but if > there is one on going from Tkinter to pyQT, that would be amazing. > Well if any of you guys have any tips or suggestions on any of this I > would appreciate it. There are some tutorials mentioned in the official python wiki [1]. Then there is the PyQt wiki [2], which as a section dedicated to tutorials [3]. Moreover I absolutely recommend to read the reference gui from riverbank computing [4]. At last, you should always keep the official docs at hand. They contain plenty of good tutorials and background documents about different Qt4 techniques, that are _definitely_ worth reading. Code samples and API docs are of course kept in C++, but transferring these to Python is mostly easy, the differences are not that big. So you see, there's more than enough PyQt4 stuff out there ;) But the most important thing to do at the transition from Tk to Qt4 goes first, before you start digging any Qt4 specific document: Forget everything, you learned about GUI programming with Tk. Qt4 works complety differently! ;) [1] http://wiki.python.org/moin/PyQt [2] http://www.diotavelli.net/PyQtWiki [3] http://www.diotavelli.net/PyQtWiki/Tutorials [4] http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From Lie.1296 at gmail.com Wed Jun 18 07:11:31 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 18 Jun 2008 04:11:31 -0700 (PDT) Subject: dict order References: <4804032a-adef-4973-ae21-acc4ad2dce37@z72g2000hsb.googlegroups.com> <411fc353-dd54-4bbc-a72e-ddee66408313@c58g2000hsc.googlegroups.com> Message-ID: <1a7a2dc6-4acf-473d-a51c-4715ca9c7068@c19g2000prf.googlegroups.com> On Jun 18, 5:35?pm, cokofree... at gmail.com wrote: > On Jun 18, 12:32 pm, cokofree... at gmail.com wrote: > > > > > On Jun 18, 11:22 am, Robert Bossy wrote: > > > > Hi, > > > > I wish to know how two dict objects are compared. By browsing the > > > archives I gathered that the number of items are first compared, but if > > > the two dict objects have the same number of items, then the comparison > > > algorithm was not mentioned. > > > > Note that I'm not trying to rely on this order. I'm building a > > > domain-specific language where there's a data structure similar to > > > python dict and I need an source of inspiration for implementing > > > comparisons. > > > > Thanks > > > RB > > > I'm a little confused as to what you want. Are you asking whether two > > dictionary objects have the same keys AND values, or just the Keys? > > > As dictionaries are unordered the best technique is to go through one > > dictionary and take out a key, then see if that key exists in the > > other dictionary, and if so do they share the same values. > > > # untested 2.5 > > for keys in dict_one.items(): > > ? if keys in dict_two: > > ? ? if dict_one[keys] != dict_two[keys]: > > ? ? ? # values are different > > ? else: > > ? ? # key is not present > > > This probably isn't the most efficient way, but can quickly find > > differences... > > Whoops > > for keys, values in dict_one.items(): > ? if keys in dict_two: > ? ? if values == dict_two[keys]: > > should also work... Whoops, I think I misunderstood the question. If what you're asking whether two dictionary is equal (equality comparison, rather than sorting comparison). You could do something like this: a = [...] b = [...] s = set() for bk, bv in b.iteritems(): s.add((bk, bv)) for ak, av in a.iteritems(): if not((ak, av) in s): print 'Difference Found!' From moneymakecash2 at gmail.com Mon Jun 9 17:21:15 2008 From: moneymakecash2 at gmail.com (MERLIN) Date: Mon, 9 Jun 2008 14:21:15 -0700 (PDT) Subject: CREDIT CARD Message-ID: <664371be-bdfa-46f2-9a38-b88c87673c44@z24g2000prf.googlegroups.com> ------------------------------------------------------------ http://geocities.com/fixedratecreditcard http://geocities.com/mortgagesoftware1 http://geocities.com/hostingmanagedweb http://geocities.com/compareonlinetrading http://geocities.com/helpdesksoftware From bignose+hates-spam at benfinney.id.au Fri Jun 13 20:43:32 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 14 Jun 2008 10:43:32 +1000 Subject: importing part of a module without executing the rest References: Message-ID: <87y758dex7.fsf@benfinney.id.au> krishna.000.k at gmail.com writes: > file1.py > ---------- > a = 20 > from abc import * > print "Should this be printed when 'a' is alone imported from this > module" > > file2.py > ---------- > from file1 import a > print a > > file2.py is used in a context where 'from abc import *' statement > doesn't make sense but it can make sense of (and requires) 'a'. > But it seems we can't import just a part of the module and expect the > rest to not be executed. > Executing python file2.py executes the 'from abc ...' and the print > statement following it in file1.py. That's right. That's what 'import' is documented to do. Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace ? ? to ``initialize'' a Python-coded module meansto execute the module's body. > Can't I just import 'a' into this name scope without touching the > rest of the statements in the module (file1 in this case). If so, > what the rationale behind such logic in the module 'import' > mechanism of python? The purpose of dividing code into separate modules is to have all the code in those modules executed by an 'import' statement. If you want some code to be executed under some circumstances and other code not executed, they need to be separated somehow. > Don't I have any solution other than packaging those parts in > file1.py (a = 20 and the rest of the statements) into different > modules? Let me turn that around: What are you actually trying to do, and how does that conflict with separating code that seems (from your description) conceptually separate anyway? One possible answer could be to define a module-level function. This would mean that at 'import' time, the 'def' statement is executed and the function defined, but the code inside it is not executed until you call the function at some later time. This also has the beneficial effect of defining a specific interface for using that code. Whether that's appropriate to your situation is impossible to say without knowing what you are trying to do. -- \ ?Never do anything against conscience even if the state | `\ demands it.? ?Albert Einstein | _o__) | Ben Finney From apardon at forel.vub.ac.be Mon Jun 9 07:40:54 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 9 Jun 2008 11:40:54 GMT Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> Message-ID: On 2008-06-07, David wrote: > Would it be possible for a 3rd-party threading library to an > 'interruptible' version of Queue? > > The same methods as the normal Queue, but when you call a new .kill() > method on the queue, all the threads locking on the queue get a > "QueueKilled" exception thrown. I have done something similar. The idea was that threads had to open a queue before they could access it. If the last thread who had the queue open in write mode, closed the queue, a reader trying to get an element from an empty queue would have an "EOInformation" exception raised. -- Antoon Pardon From omer at no-log.org Thu Jun 26 07:39:09 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Thu, 26 Jun 2008 13:39:09 +0200 Subject: extend getattr() In-Reply-To: <0d1da457-b026-4e38-824b-c8cbde172bf7@m36g2000hse.googlegroups.com> References: <0d1da457-b026-4e38-824b-c8cbde172bf7@m36g2000hse.googlegroups.com> Message-ID: <200806261339.09527.omer@no-log.org> Le Thursday 26 June 2008 13:06:53 Rotlaus, vous avez ?crit?: > Hello, > > lets assume i have some classes: > > class A(object): > def __init__(self): > b = B() > > class B(object): > def __init__(self): > c = C() > note you're just defining some local variables here, should be self.b = B() and self.c = C(). > class C(object): > def __init__(self): > pass > > and now i wanna do something like this: > > a=A() > c=getattr(a, 'b.c') > > I know this doesn't work, but what can i do to get this or a similar > functionality to get it work for this sample and for even more nested > classes? > You could do it manually: c = getattr(getattr(a, 'b'), 'c') or make it automatic: def get_dotted_attr (obj, dotted_attr) : for attr in dotted_attr.split('.') : obj = getattr(obj, attr) return obj a = A() print 'a.b.c = %s' % get_dotted_attr(a, 'b.c') -- C?dric Lucantis From danb_83 at yahoo.com Mon Jun 16 23:43:55 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Mon, 16 Jun 2008 20:43:55 -0700 (PDT) Subject: Does '!=' equivelent to 'is not' References: Message-ID: <6f86763c-6583-4c7c-b866-0cae21aeebaf@g16g2000pri.googlegroups.com> On Jun 16, 10:29?pm, pirata wrote: > I'm a bit confusing about whether "is not" equivelent to "!=" > > if a != b: > ? ... > > if a is not b: > ? ... > > What's the difference between "is not" and "!=" or they are the same thing? "is not" is the logical negation of the "is" operator, while "!=" is the logical negation of the "==" operator. The difference is equality versus identity. >>> a = [1, 2, 3] >>> b = [1, 2, 3] >>> a == b True >>> a is b False From alexnbryan at gmail.com Tue Jun 10 13:54:03 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 10 Jun 2008 10:54:03 -0700 (PDT) Subject: problems with opening files due to file's path In-Reply-To: References: <17759531.post@talk.nabble.com> Message-ID: <17761126.post@talk.nabble.com> Hey thanks!, both the raw and the double backslashes worked. You are a gentleman and a scholar. Mike Driscoll wrote: > > On Jun 10, 11:45 am, Alexnb wrote: >> Gerhard H?ring wrote: >> >> > Alexnb wrote: >> >> Okay, so what I want my program to do it open a file, a music file in >> >> specific, and for this we will say it is an .mp3. Well, I am using the >> >> system() command from the os class. [...] >> >> >> system("\"C:\Documents and Settings\Alex\My Documents\My >> >> Music\Rhapsody\Bryanbros\Weezer\(2001)\04 - Island In The Sun.wma\"") >> >> [...] >> >> > Try os.startfile() instead. It should work better. >> >> > -- Gerhard >> >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> No, it didn't work, but it gave me some interesting feedback when I ran >> it >> in the shell. Heres what it told me: >> >> >>> os.startfile("C:\Documents and Settings\Alex\My Documents\My >> >>> Music\Rhapsody\Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm >> >>> Yours.wma") >> >> Traceback (most recent call last): >> File "", line 1, in >> os.startfile("C:\Documents and Settings\Alex\My Documents\My >> Music\Rhapsody\Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm >> Yours.wma") >> >> WindowsError: [Error 2] The system cannot find the file specified: >> "C:\\Documents and Settings\\Alex\\My Documents\\My >> Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\x01 - I'm >> Yours.wma" >> >> See it made each backslash into two, and the one by the parenthesis and >> the >> 0 turned into an x.... >> -- >> View this message in >> context:http://www.nabble.com/problems-with-opening-files-due-to-file%27s-pat... >> Sent from the Python - python-list mailing list archive at Nabble.com. > > Yeah. You need to either double all the backslashes or make it a raw > string by adding an "r" to the beginning, like so: > > os.startfile(r'C:\path\to\my\file') > > HTH > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17761126.html Sent from the Python - python-list mailing list archive at Nabble.com. From szrRE at szromanMO.comVE Mon Jun 2 01:45:25 2008 From: szrRE at szromanMO.comVE (szr) Date: Sun, 1 Jun 2008 22:45:25 -0700 Subject: The Importance of Terminology's Quality References: <4840ab73$0$90274$14726298@news.sunsite.dk> <4841f0aa$0$90274$14726298@news.sunsite.dk> <48432b01$0$90272$14726298@news.sunsite.dk> Message-ID: Arne Vajh?j wrote: > szr wrote: >> Arne Vajh?j wrote: >>> szr wrote: >>>> Peter Duniho wrote: >>>>> On Fri, 30 May 2008 22:40:03 -0700, szr >>>>> wrote: >>>>>> Arne Vajh?j wrote: >>>>>>> Stephan Bour wrote: >>>>>>>> Lew wrote: >>>>>>>> } John Thingstad wrote: >>>>>>>> } > Perl is solidly based in the UNIX world on awk, sed, } > >>>>>>>> bash and C. I don't like the style, but many do. >>>>>>>> } >>>>>>>> } Please exclude the Java newsgroups from this discussion. >>>>>>>> >>>>>>>> Did it ever occur to you that you don't speak for entire news >>>>>>>> groups? >>>>>>> Did it occur to you that there are nothing about Java in the >>>>>>> above ? >>>>>> Looking at the original post, it doesn't appear to be about any >>>>>> specific language. >>>>> Indeed. That suggests it's probably off-topic in most, if not >>>>> all, of the newsgroups to which it was posted, inasmuch as they >>>>> exist for topics specific to a given programming language. >>>> Perhaps - comp.programming might of been a better place, but not >>>> all people who follow groups for specific languages follow a >>>> general group like that - but let me ask you something. What is it >>>> you really have against discussing topics with people of >>>> neighboring groups? Keep in mind you don't have to read anything >>>> you do not want to read. [1] >>> I very much doubt that the original thread is relevant for the Java >>> group. >>> >>> But the subthread Lew commente don was about Perl and Unix. That is >>> clearly off topic. >> >> I agree with and understand what you are saying in general, but >> still, isn't it possible that were are people in the java group (and >> others) who might of been following the thread, only to discover >> (probably not right away) that someone decided to remove the group >> they were reading the thread from? I know I would not like that, >> even if it wasn't on topic at the branch. >> >> Personally, I find it very annoying to have to switch news groups in >> order to resume a thread and weed my way down the thread to where it >> left off before it was cut off from the previous group. > > I am relative tolerant towards threads that are a bit off topic, if > the S/N ratio overall is good. Agreed. [...] If a thread, that is cross-posted, branches off on a tangent that has nothing to do with one or more groups what so ever, then yes, it makes sense to prune the 'newsgroup:' list / set follow ups, but in this case, someone made one mention or so of 'Perl', which was being used as an example, and someone (lew) moved to have the Java group removed. There was little reason to cut off the thread, when people very well may have been following it, over the utterance of one word, which was being used as an example. The bulk of the thread had to do with general programming, and suddenly writing the name of a language doesn't mean it's way off on a tangent. I hope this clears up some waters. Regards. -- szr From cfbolz at gmx.de Thu Jun 5 19:46:52 2008 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Fri, 06 Jun 2008 01:46:52 +0200 Subject: How "solid" is PyPy? In-Reply-To: <335dcaaa-ac21-4526-91c2-d308b8693c34@e53g2000hsa.googlegroups.com> References: <335dcaaa-ac21-4526-91c2-d308b8693c34@e53g2000hsa.googlegroups.com> Message-ID: <48487AEC.5040707@gmx.de> Hi, miller.paul.w at gmail.com wrote: > I've been looking at PyPy recently, and I see it's reached version 1.0 > (and supports language version 2.4). Given that, I was wondering what > level of backwards-compatibility one can expect from future versions, > i.e. if I run code on, say, a translated stackless PyPy now, what is > the probability that it will run unmodified on PyPy 1.x, 2.x, etc.? That's hard to say. Nobody is using PyPy in any sort of production system yet, so the PyPy team is currently focused mostly on actually becoming useful. Nobody really has a clue what sort of solutions for backward compatibility we will have. Note also that the 1.0 release is sort of oldish already (but no new release has been made). Most people just use SVN head, which is quite stable. Cheers, Carl Friedrich Bolz From sturlamolden at yahoo.no Wed Jun 4 10:07:44 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 4 Jun 2008 07:07:44 -0700 (PDT) Subject: How to perform a nonblocking read from a process References: <15c889d4-3e06-4ffd-a86e-10cfa87d3bc5@k37g2000hsf.googlegroups.com> <618bd3d7-1b49-48f5-84b4-e32934ce727c@g16g2000pri.googlegroups.com> Message-ID: <712e3834-2a62-4f98-ad8d-0d1bd8c73c05@z72g2000hsb.googlegroups.com> On Jun 4, 8:45 am, rdab... at gmail.com wrote: > I've to admit I'm a newbie to this kind of programming... > what if I have to run thousands of these commands...it doesn't make > sense to create > thousands of threads.. > Is there a way that above mentioned piece of code be made to worked... Are you planning on doing thousands of simultaneous asynchronous I/O calls? How many processes are you communicating with? Take a look at the twisted framwork (twistedmatrix.org) or perhaps i/o completion ports on Windows (e.g. win32file.CreateIoCompletionPort in PyWin32). But if you need that king of scalability, I suggest you start by reconsidering the design. If you are communicating with only one process, you don't need thousands of threads, just one. Keep the thread idle until you need it again. Here is a simple worker thread that allows you to do multiple, different function calls in a background thread (you can shut it down by passing None to setTask). import threading import Queue class WorkerThread(threading.Thread): def __init__(self): self.taskQueue = Queue.Queue(0) self.resQueue = Queue.Queue(0) self.setDaemon(True) def run(self): while 1: fun, args, kwarg = self.taskQueue.get() if (fun is None): break self.resQueue.put(fun(*args,**kwarg)) def setTask(self, fun, *args, **kwarg): self.taskQueue.set((fun, args, kwarg)) def getResult(self): return self.resQueue.get() def probeResult(self): return not self.resQueue.empty() Rewrite of your examples: from subprocess import * p2 = Popen('python',stdin=PIPE,stdout=PIPE,universal_newlines=True) worker = WorkerThread() for i in range(10): worker.setTask(p2.stdin.write, 'print 10'+'\n') worker.setTask(p2.stdout.readline) worker.getResult() # wait for write to finish o,e = worker.getResult() # wait for read to finish print o,e from subprocess import * p2 = Popen('python',stdin=PIPE,stdout=PIPE,universal_newlines=True) writer = WorkerThread() reader = WorkerThread() for i in range(10): writer.setTask(p2.stdin.write, 'print 10'+'\n') reader.setTask(p2.stdout.readline) o,e = reader.getResult() # wait for read to finish print o,e From chrispoliquin at gmail.com Wed Jun 18 11:12:16 2008 From: chrispoliquin at gmail.com (chrispoliquin at gmail.com) Date: Wed, 18 Jun 2008 08:12:16 -0700 (PDT) Subject: urllib (54, 'Connection reset by peer') error References: <92ecee86-ba92-4f14-b4f8-05064ef5406c@f63g2000hsf.googlegroups.com> Message-ID: Thanks for the help. The error handling worked to a certain extent but after a while the server does seem to stop responding to my requests. I have a list of about 7,000 links to pages I want to parse the HTML of (it's basically a web crawler) but after a certain number of urlretrieve() or urlopen() calls the server just stops responding. Anyone know of a way to get around this? I don't own the server so I can't make any modifications on that side. From info at egenix.com Mon Jun 16 06:12:54 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Mon, 16 Jun 2008 12:12:54 +0200 Subject: ANN: eGenix mxODBC Connect Database Interface for Python 0.9.1 (beta) Message-ID: <48563CA6.1090202@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com mxODBC Connect Database Interface for Python Version 0.9.1 (beta) Our new client-server product for connecting Python applications to relational databases - on all major platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mxODBC-Connect-0.9.1-beta.html ________________________________________________________________________ INTRODUCTION The mxODBC Connect Database Interface for Python allows users to easily connect Python applications to all major databases on the market today in a highly portable and convenient way. This makes mxODBC Connect the ideal basis for writing cross-platform database programs and utilities in Python. mxODBC Connect extends our eGenix mx Python Extension series with a new client-server based product, that removes the need to install and configure ODBC drivers on the client side. This greatly simplifies setup and configuration of database driven client applications, while at the same time making the network communication between client and database server more efficient and more secure. * About Python: Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. * About eGenix: eGenix is a consulting and software product company focused on providing professional quality services and products to Python users and developers (http://www.egenix.com/). ________________________________________________________________________ HOW IT WORKS mxODBC Connect consists of two parts: a server installation which typically runs directly on the database server and a client Python package which is installed on the client machine that runs the Python application. The server part uses our high-performance database adapter mxODBC to connect to the database server. The client package communicates with the server part over a TCP/IP network, optionally using SSL encryption, advanced authentication and access controls - a feature that many database drivers fail to deliver. By separating the client application database interface from the server and using mxODBC Connect, you gain several benefits: * high portability and flexibility * centralized configuration and administration * added security * automatic fail-over * scalability * lower costs For more information, please have a look at the product page: http://www.egenix.com/products/python/mxODBCConnect/ ________________________________________________________________________ NEWS mxODBC Connect 0.9 is a public beta release of our new mxODBC Connect product. If you would like to participate in the beta, please see our beta program page: http://www.egenix.com/products/python/mxODBCConnect/beta.html *SPECIAL OFFER* In order to make participation in the beta program more interesting for our users, we will be giving out *free discount coupons* to all participants who report back bugs in the product. ________________________________________________________________________ DOWNLOADS The download archives as well as instructions for installation and configuration of the product can be found on the product page: http://www.egenix.com/products/python/mxODBCConnect/ _______________________________________________________________________ SUPPORT Commercial support for this product is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jun 16 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania 20 days to go :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From jonrob at fedoraproject.org Sun Jun 22 07:52:11 2008 From: jonrob at fedoraproject.org (Jonathan Roberts) Date: Sun, 22 Jun 2008 12:52:11 +0100 Subject: Learning Python in a group In-Reply-To: <18c1e6480806220422x5d06c54byd23b249bb699691f@mail.gmail.com> References: <507738ef0806220343r3e9ea053neeec0baf0ccfdbe6@mail.gmail.com> <18c1e6480806220422x5d06c54byd23b249bb699691f@mail.gmail.com> Message-ID: <507738ef0806220452s74358615v44518469cf3b5f45@mail.gmail.com> > If you want people to meet with you (in person) as a mentor you should > probably ask on your local Python or Linux users group mailing list. We're not really too worried about doing it in person - mostly because the people doing it so far are all at least 1000 miles away from each other :) Best, Jon > -- > http://mail.python.org/mailman/listinfo/python-list > From tommy.nordgren at comhem.se Thu Jun 19 07:48:44 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Thu, 19 Jun 2008 13:48:44 +0200 Subject: Python-3.0b1 build fails on Linux : _gestalt In-Reply-To: <6bupftF3d2d0kU1@mid.dfncis.de> References: <6bupftF3d2d0kU1@mid.dfncis.de> Message-ID: <071F3423-3EE0-49D5-BD2F-8DCD9A764D65@comhem.se> On 19 jun 2008, at 12.07, Helmut Jarausch wrote: > Hi, > > trying to build Python-3.0b1 on my Gentoo Linux box fails with > > Failed to find the necessary bits to build these modules: > _gestalt > > Looking at setup.py it seems that module '_gestalt' > is only needed on Darwin but my build on Linux fails > nevertheless. > > Thanks for any hints, > > Helmut Jarausch > > Lehrstuhl fuer Numerische Mathematik > RWTH - Aachen University > D 52056 Aachen, Germany > -- > http://mail.python.org/mailman/listinfo/python-list Have you run the configure script? This might happen if you have copied the directory from a machine with Darwin/Mac OS X ----------------------------------- See the amazing new SF reel: Invasion of the man eating cucumbers from outer space. On congratulations for a fantastic parody, the producer replies : "What parody?" Tommy Nordgren tommy.nordgren at comhem.se From gherron at islandtraining.com Wed Jun 11 11:54:19 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 11 Jun 2008 08:54:19 -0700 Subject: How to find duplicate 3d points? In-Reply-To: References: Message-ID: <484FF52B.7080403@islandtraining.com> oprah.chopra at gmail.com wrote: > I have a large data file of upto 1 million x,y,z coordinates of > points. I want to identify which points are within 0.01 mm from each > other. I can compare the distance from each point to every other > point , but this takes 1 million * 1 million operations, or forever! > > Any quick way to do it, perhaps by inserting just the integer portion > of the coordinates into an array, and checking if the integer has > already been defined before inserting a new point? > -- > http://mail.python.org/mailman/listinfo/python-list > There is a whole field of Math/CS research on problems like this called Computational Geometry. It provides many algorithms for many geometric problems, including things like this. In particular, to categorize a list of points and find the NearestNeighbor, I'd suggest a KD-tree. I believe this would turn your problem from O(N^2) to O(N log n) or so. Happy google-ing and good luck. Gary Herron From gagsl-py2 at yahoo.com.ar Wed Jun 18 18:09:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Jun 2008 19:09:14 -0300 Subject: Getting Python exit code when calling Python script from Java program References: Message-ID: En Wed, 18 Jun 2008 08:09:58 -0300, A.T.Hofkamp escribi?: > On 2008-06-18, Quill_Patricia at emc.com wrote: >> picking up 0. On investigation it turned out that the exit value being >> read is from python.exe process, not from the Python script. Is there >> any way I can obtain the return value of a python script from a Java > > This is not what I see happening here: > > x.py: > import sys > sys.exit(138) > > % python2.4 x.py > % echo $? > 138 > > as you can see, the mechanism works at my Linux system. It works fine on Windows too, the OS she appears to be using: C:\TEMP>python x.py C:\TEMP>echo %ERRORLEVEL% 138 -- Gabriel Genellina From root at sys1.org Mon Jun 23 10:54:29 2008 From: root at sys1.org (Andreu) Date: Mon, 23 Jun 2008 16:54:29 +0200 Subject: String question References: Message-ID: Wow...about ten seconds to get a kind response .... Thanks Tim. Andrew. Tim Golden wrote: > Andreu wrote: >> I want to split a sentence and assign each word to a variable. >> In Ruby I can do it as: >> >> v1,v2,v3,v4,v5 = str1.split >> >> Which will be the Python equivalent ? Thanks. > > That would be: > > str1 = "The quick brown fox jumps" > v1, v2, v3, v4, v5 = str1.split () > > TJG From Lie.1296 at gmail.com Sun Jun 29 06:20:19 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 29 Jun 2008 03:20:19 -0700 (PDT) Subject: What is "@" used for ? References: Message-ID: On Jun 29, 3:39?pm, gops wrote: > Hi. > > I am noob in python. while reading some source code I came across , > this funny thing called @ in some function , > > def administrator(method): > ? ? @functools.wraps(method) > ? ? def wrapper(self, *args, **kwargs): > ? ? ? ? user = users.get_current_user() > ? ? ? ? if not user: > ? ? ? ? ? ? if self.request.method == "GET": > > self.redirect(users.create_login_url(self.request.uri)) > ? ? ? ? ? ? ? ? return > ? ? ? ? ? ? raise web.HTTPError(403) > ? ? ? ? elif not users.is_current_user_admin(): > ? ? ? ? ? ? raise web.HTTPError(403) > ? ? ? ? else: > ? ? ? ? ? ? return method(self, *args, **kwargs) > ? ? return wrapper > > now what is that "@" used for ? I tried to google , but it just omits > the "@" and not at all useful for me(funny!! :D) > > It will be enough if you can just tell me some link where i can look > for it.. > > Thank you in advance. :D @ is decorator. It's a syntax sugar, see this example: class A(object): @decorate def blah(self): print 'blah' is the same as: class A(object): def blah(self): print 'blah' blah = decorate(blah) Now you know the name, I guess google will help you find the rest of the explanation. From ayushi.mehra at gmail.com Mon Jun 16 01:14:30 2008 From: ayushi.mehra at gmail.com (Ayushi Mehra) Date: Sun, 15 Jun 2008 22:14:30 -0700 (PDT) Subject: Samsung SyncMaster 940 NW Monitors Message-ID: Samsung SyncMaster 940 NW Monitors inch, LCD, Colour monitor consumes 38 watts of power per hour, has digital user controls and a maximum resolution of 1280x1024 dpi. The screen is flat with anti-glare and anti-static coating. Its other features like MagicTune, MagicBright and MagicSpeed. It is a wide screen monitor with 5ms response time and a contrast ratio of 700:1. It is available in high glossy black colour. It has DVI-D input. To buy this Samsung SyncMaster 940 NW Monitors Please visit to http://www.naaptol.com/buy-online/WO-best-deals-shopping-W664O/computers_-_peripherals/monitors/samsung__syncmaster_940_nw.html From roopesh.raj at gmail.com Mon Jun 23 01:23:02 2008 From: roopesh.raj at gmail.com (Roopesh) Date: Sun, 22 Jun 2008 22:23:02 -0700 (PDT) Subject: POP3_SSL Error Message-ID: Hi, While using poplib to fetch mails from my gmail account, I am getting the following error: Exception is POP3_SSL instance has no attribute 'sslobj' Can anyone tell me what this error means. Thanks and Regards Roopesh From google at mrabarnett.plus.com Tue Jun 3 20:08:44 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 3 Jun 2008 17:08:44 -0700 (PDT) Subject: Ideas for master's thesis References: Message-ID: On Jun 3, 10:22 pm, Larry Bugbee wrote: > > I would like to do something with this language, yet > > I don't know if there are any needs/science fields, that could be used > > as a basis for a thesis. > > Personally, I'd like to see *optional* data typing added to Python > perhaps along the lines of what was done in Pyrex. You declare the > data type when you know it, or when it matters, and skip it > otherwise. Your paper could analyze its pros and cons, analyze any > potential performance gains, and recommend how to implement it. Your > professor will suggest some additional questions. > > I suspect, if the type be known and declared, the interpreter could be > streamlined and quicker, you might get asserts for free, and perhaps, > Python becomes even more self-documenting. Perhaps I've missed it, > but I haven't seen a strong analytical case made for or against > optional data typing. Your paper? > You might want to have a look at Boo at http://boo.codehaus.org/. From kyosohma at gmail.com Mon Jun 9 12:20:31 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 9 Jun 2008 11:20:31 -0500 Subject: How to get full path to script? In-Reply-To: References: Message-ID: On Mon, Jun 9, 2008 at 11:07 AM, kj wrote: > In "Mike Driscoll" writes: > >>For my compiled scripts, I usually use this variation: > >>path = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))) > > Thanks. But why the os.path.join()? (BTW, I did read the docs > before posting, but they make no sense to me; they say that > os.path.join joins "one or more path components intelligently", > but what does it mean to join *one* component?) > > Kynn > > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. > -- > http://mail.python.org/mailman/listinfo/python-list > The idea of the join method is to create the path in an OS agnostic fashion. Linux uses forward slashes and Windows uses backward slashes to join the parts. The join method does this for you so you don't have to. I think in this case, if I had my program installed to C:\Program Files\MyProgram It would put the slashes in correctly for Windows. However, there are ways to get the default program directory in Linux and then have the os.path.join create the path correctly there too. That's the idea anyway. Hopefully that isn't more confusing than what you read. Mike From dmitrey.kroshko at scipy.org Sun Jun 15 16:24:39 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sun, 15 Jun 2008 13:24:39 -0700 (PDT) Subject: ANN: OpenOpt 0.18 (numerical optimization framework) Message-ID: Greetings, We're pleased to announce: OpenOpt 0.18 (release), free (license: BSD) optimization framework (written in Python language) with connections to lots of solvers (some are C- or Fortran-written) is available for download. Changes since previous release 0.17 (March 15, 2008): * connection to glpk MILP solver (requires cvxopt v >= 1.0) * connection to NLP solver IPOPT (requires python-ipopt wrapper installation, that is currently available for Linux only, see openopt NLP webpage for more details) * major changes for NLP/NSP solver ralg * splitting non-linear constraints can benefit for some solvers * unified text output for NLP solvers * handling of maximization problems (via p.goal = 'max' or 'maximum') * some bugfixes, lots of code cleanup Newsline: http://openopt.blogspot.com/ Homepage: http://scipy.org/scipy/scikits/wiki/OpenOpt Regards, OpenOpt developers. From gagsl-py2 at yahoo.com.ar Mon Jun 2 22:11:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 02 Jun 2008 23:11:56 -0300 Subject: Continuous Timer References: <496954360805301850u4ce63746vc8fcc84ad1b72824@mail.gmail.com> Message-ID: En Fri, 30 May 2008 22:50:13 -0300, Robert Dailey escribi?: > Reading through the Python 2.5 docs, I'm seeing a Timer class in the > threading module, however I cannot find a timer object that will > continuously call a function of my choice every XXXX amount of > milliseconds. > For example, every 1000 milliseconds I want a function named Foo to be > called. This would continue to happen until I terminate the timer in my > main > thread. Thanks for the help. Use an Event object; its wait() will provide the sleep time, and when it is set() the thread knows it has to exit. import threading import time def repeat(event, every, action): while True: event.wait(every) if event.isSet(): break action() def foo(): print "I'm bored to death..." print "creating event and thread" ev = threading.Event() t1 = threading.Thread(target=repeat, args=(ev, 1.0, foo)) print "starting thread" t1.start() print "waiting for 10 seconds in main thread" time.sleep(10) print "setting event" ev.set() print "waiting for thread to finish" t1.join() print "quit" -- Gabriel Genellina From google at mrabarnett.plus.com Sun Jun 15 19:48:42 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 15 Jun 2008 16:48:42 -0700 (PDT) Subject: please critique my thread code References: <222a1935-20dd-44a0-bc42-71a25be96d30@79g2000hsk.googlegroups.com> Message-ID: On Jun 15, 2:29 pm, wins... at cs.wisc.edu wrote: > I wrote a Python program (103 lines, below) to download developer data > from SourceForge for research about social networks. > > Please critique the code and let me know how to improve it. > > An example use of the program: > > prompt> python download.py 1 240000 > > The above command downloads data for the projects with IDs between 1 > and 240000, inclusive. As it runs, it prints status messages, with a > plus sign meaning that the project ID exists. Else, it prints a minus > sign. > > Questions: > > --- Are my setup and use of threads, the queue, and "while True" loop > correct or conventional? > > --- Should the program sleep sometimes, to be nice to the SourceForge > servers, and so they don't think this is a denial-of-service attack? > > --- Someone told me that popen is not thread-safe, and to use > mechanize. I installed it and followed an example on the web site. > There wasn't a good description of it on the web site, or I didn't > find it. Could someone explain what mechanize does? > > --- How do I choose the number of threads? I am using a MacBook Pro > 2.4GHz Intel Core 2 Duo with 4 GB 667 MHz DDR2 SDRAM, running OS > 10.5.3. > > Thank you. > > Winston > [snip] String methods are quicker than regular expressions, so don't use regular expressions if string methods are perfectly adequate. For example, you can replace: error_pattern = re.compile(".*\n\n.*", re.DOTALL) ... valid_id = not error_pattern.match(text) with: error_pattern = "\n\n" ... valid_id = error_pattern not in text From tjreedy at udel.edu Sat Jun 14 14:58:18 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 14 Jun 2008 14:58:18 -0400 Subject: Was the move to Python 2.0 as big a deal? References: <4853f365$0$11601$607ed4bc@cv.net> Message-ID: "John Salerno" wrote in message news:4853f365$0$11601$607ed4bc at cv.net... | Just curious if people put up any resistance to 2.0 like some people do | for 3.0. Was it as big of a change in the language, or was the | transition smoother? 2.0 (from BeOpen) was essentially 1.6 (final CNRI version) rebranded. A bigger change was 2.2 which introduced new-style classes, the new iterator protocol, and generators. From usenet at technicalbloke.com Thu Jun 19 03:24:43 2008 From: usenet at technicalbloke.com (Roger Heathcote) Date: Thu, 19 Jun 2008 08:24:43 +0100 Subject: please critique my thread code In-Reply-To: References: <222a1935-20dd-44a0-bc42-71a25be96d30@79g2000hsk.googlegroups.com> Message-ID: <9ZWdnVMfvdwglMfVnZ2dnUVZ8q_inZ2d@bt.com> MRAB wrote: > On Jun 15, 2:29 pm, wins... at cs.wisc.edu wrote: >> I wrote a Python program (103 lines, below) to download developer data >> from SourceForge for research about social networks. >> >> Please critique the code and let me know how to improve it. >> >> An example use of the program: >> >> prompt> python download.py 1 240000 >> >> The above command downloads data for the projects with IDs between 1 >> and 240000, inclusive. As it runs, it prints status messages, with a >> plus sign meaning that the project ID exists. Else, it prints a minus >> sign. >> >> Questions: >> >> --- Are my setup and use of threads, the queue, and "while True" loop >> correct or conventional? >> >> --- Should the program sleep sometimes, to be nice to the SourceForge >> servers, and so they don't think this is a denial-of-service attack? >> >> --- Someone told me that popen is not thread-safe, and to use >> mechanize. I installed it and followed an example on the web site. >> There wasn't a good description of it on the web site, or I didn't >> find it. Could someone explain what mechanize does? >> >> --- How do I choose the number of threads? I am using a MacBook Pro >> 2.4GHz Intel Core 2 Duo with 4 GB 667 MHz DDR2 SDRAM, running OS >> 10.5.3. >> >> Thank you. >> >> Winston >> > [snip] > String methods are quicker than regular expressions, so don't use > regular expressions if string methods are perfectly adequate. For > example, you can replace: Erm, shurely the bottleneck will be bandwidth not processor/memory?* If it isn't then - yes, you run the risk of actually DOSing their servers! Your mac will run thousands of threads comfortably but your router may not handle the thousands of TCP/IP connections you throw at it very well, especially if it is a domestic model, and sure as hell sourceforge aren't going to want more than a handfull of concurrent connections from you. Typical sourceforge page ~ 30K Project pages to read = 240000 = ~6.8 Gigabytes Maybe send their sysadmin a box of chocolates if you want to grab all that in any less than a week and not get your IP blocked! :) Roger Heathcote * Of course, stylistically, MRAB is perfectly right about not wasting CPU on regexes where string methods will do, unless you are planning on making your searches more elaborate in the future. From miller.paul.w at gmail.com Mon Jun 2 04:03:05 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Mon, 2 Jun 2008 01:03:05 -0700 (PDT) Subject: Writing HTML Message-ID: <3760e9d1-d385-4e36-8ca6-e03e48ffdfbf@c58g2000hsc.googlegroups.com> I've searched the standard library docs, and, while there are a couple options for *reading* HTML from Python, I didn't notice any for *writing* it. Does anyone have any recommendations (particularly ones not listed on PyPI)? Thanks From Protectorates at gmail.com Wed Jun 4 17:02:49 2008 From: Protectorates at gmail.com (topher) Date: Wed, 4 Jun 2008 14:02:49 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> Message-ID: On Jun 4, 2:58 pm, "Russ P." wrote: > On Jun 4, 4:29 am, NickC wrote: > > > On Jun 4, 4:09 am, "Russ P." wrote: > > > > What is it about leading underscores that bothers me? To me, they are > > > like a small pebble in your shoe while you are on a hike. Yes, you can > > > live with it, and it does no harm, but you still want to get rid of it. > > > With leading underscores, you can see *at the point of dereference* > > that the code is accessing private data. With a "this is private" > > keyword you have no idea whether you're accessing private or public > > data, because the two namespaces get conflated together. > > That is true. But with the "priv" keyword you'll discover quickly > enough that you are trying to access private data (as soon as you run > the program). And even if a "priv" keyword is added, you are still > free to use the leading underscore convention if you wish. > > The idea of being able to discern properties of an object by its name > alone is something that is not normally done in programming in > general. Yes, of course you should choose identifiers to be > descriptive of what they represent in the real world, but you don't > use names like "intCount," "floatWeight," or "MyClassMyObject" would > you? Why not? That would tell you the type of the object at the "point > of dereferencing," wouldn't it? Sounds familiar. http://en.wikipedia.org/wiki/Hungarian_notation From deveeshree02 at gmail.com Mon Jun 9 11:29:10 2008 From: deveeshree02 at gmail.com (deveeshree) Date: Mon, 9 Jun 2008 08:29:10 -0700 (PDT) Subject: ANYONE CAN POST ANY TOPIC!! UPLOAD & EDIT FILES, INVITE FRIENDS!!! Message-ID: ANYONE CAN POST ANY TOPIC!! UPLOAD & EDIT FILES, INVITE FRIENDS!!! Welcoming you to ENJOY my Group ?ENJOY?. Please Click this Link: http://groups.google.com/group/enjoy00 From fuzzyman at gmail.com Tue Jun 10 17:41:28 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Tue, 10 Jun 2008 14:41:28 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <6e6df35e-e641-44d9-9f56-c0732306eec2@q27g2000prf.googlegroups.com> <13db98b5-ed2e-45ef-97ec-ad3caeeed10e@j1g2000prb.googlegroups.com> Message-ID: <074caf4a-de1e-4290-b688-30148786952c@z72g2000hsb.googlegroups.com> On Jun 10, 2:03?am, Rhamphoryncus wrote: > On Jun 9, 2:52 pm, Fuzzyman wrote: > > > > > On Jun 9, 9:20 pm, Rhamphoryncus wrote: > > > > On Jun 9, 5:33 am, Antoon Pardon wrote: > > > > > On 2008-06-07, Rhamphoryncus wrote: > > > > > > On Jun 6, 12:44 pm, The Pythonista wrote: > > > > >> It's always been my understanding that you can't forcibly kill a thread > > > > >> in Python (at least not in a portable way). ?The best you can do is > > > > >> politely ask it to die, IIRC. > > > > > > Inherently, the best you can do in most languages is ask them politely > > > > > to die. ?Otherwise you'll leave locks and various other datastructures > > > > > in an inconvenient state, which is too complex to handle correctly. > > > > > The exception is certain functional languages, which aren't capable of > > > > > having threads and complex state in the same sense. > > > > > Well it would of course depend on what is considered asking politely? > > > > > If one thread could cause an exception being thrown in an other thread, > > > > would this be considered a polite way to ask? Would it be considered > > > > an acceptable way? > > > > The exception must not be raised until a point explicitly designed as > > > safe is hit. ?Otherwise, any function that manipulates data you'll > > > still use will potentially be buggered. ?Consider sys.stdout: codecs, > > > buffering, lots to go wrong. > > > Java and .NET both have ways of killing threads. They both work by > > raising a 'ThreadAbort' (or similar) exception in the target thread. > > In early implementations they both suffered from a similar problem. > > You could protect locks (etc) by having a finally block that would > > release all resources as needed - but what happens if the thread abort > > exception is raised *inside* the finally block? > > > Java responded by deprecating thread aborting. .NET responded by > > ensuring that a thread abort exception would never be raised inside a > > finally block - if that happened the exception would only be raised > > once the code has left the finally block. > > > Aborting threads in .NET can be extremely useful. Politely asking a > > thread to die is no good if the task the thread is executing is > > extremely coarse grained - it may not be able to respond to the > > request for some time. If your code is structured correctly > > (performing a long running background calculation for example) then > > you may *know* that you can kill it without problems, but Python has > > no native API to do this. > > So how does .NET deal with the sys.stdout corruption? ?Does it? > That has never been an issue for us. > If you've carefully written your code to use only safe primitives and > local state (discarded if interrupted) then yes, it could be > interruptible. ?At this point you could specially mark that block of > code as safe, leaving the vast majority of other code unsafe by > default. ?Then again, since you're going to the trouble of carefully > designing and auditing your code you could just make it cancellable > like blocking I/O should be - just by polling a flag at key points > (and you're CPU-bound anyway, so it's not expensive.) > > The only place I know of that you *need* arbitrary interruption is > hitting CTRL-C in the interactive interpreter. ?At this point it's a > debugging tool though, so the risk of weirdness is acceptable. We use background threads for long running calculations that we know are safe to abort. Resources that need protecting we do with finally blocks which the thread abort honours. The calculation is 'coarse grained' (it can call into .NET APIs that can take a relatively long time to return) - so polling for exit wouldn't work anyway. We also run user code and can't expect their code to poll for exit conditions. This system works fine for us. We had fun syncing results back when the calculation terminates (race conditions if a new one needs to start just as the old one ends) - but that is the fun of threads in the first place and nothing to do with how we terminate calculations early. Michael Foord http://www.ironpythoninaction.com/ From john.dohn.john at gmail.com Fri Jun 6 06:30:12 2008 From: john.dohn.john at gmail.com (John Dohn) Date: Fri, 6 Jun 2008 22:30:12 +1200 Subject: How to kill a thread? Message-ID: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> Hi there, How can I kill a threading.Thread subclass from MainThread? My threads are waiting for data in Queue.get() method: class MyThread(threading.Thread): def run(self): while True: data = queue.get() # <- here it waits most of the time ... process data >From the main thread I start several working threads: thr = MyThread() thr.start() ... feed the queue and at the end for each thread I'd like to do something like thr.kill() or thr.stop() or thr.destroy() or ... you got the point. I can't figure out how. Is there a way to do it? Thanks! JD -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at gmail.com Tue Jun 3 15:03:38 2008 From: cwitts at gmail.com (Chris) Date: Tue, 3 Jun 2008 12:03:38 -0700 (PDT) Subject: New variable? References: <18105511-7ae1-45e9-8c43-f34c1c4f5aeb@c58g2000hsc.googlegroups.com> Message-ID: <0dabbe7c-5754-4b2a-ae69-e92939fa682b@r66g2000hsg.googlegroups.com> On Jun 3, 8:40?pm, tmallen wrote: > What's the proper way to instantiate a new variable? x = ""? You don't need to pre-declare your variables. Just assign them as you need them and they will take the correct type. From grante at visi.com Sat Jun 14 21:59:32 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 14 Jun 2008 20:59:32 -0500 Subject: Creating a TCP/IP connection on already-networked computers References: <4853f269$0$11615$607ed4bc@cv.net> <4854123f$0$5017$607ed4bc@cv.net> <485413d0$0$4997$607ed4bc@cv.net> <485425b2$0$11631$607ed4bc@cv.net> <4854730e$0$11637$607ed4bc@cv.net> Message-ID: On 2008-06-15, John Salerno wrote: > Grant Edwards wrote: > >> If the two computers are in no way connected via any type of >> network, then the two programs won't be able to talk to each >> other. >> >> The programs can't create a network, they can only use one that >> already exists. > > But isn't that the point of the program, to create a network between the > two computers? No. For the two programs to work, the network must already exist and be properly configured. In this seinse, a "network" is a mechanism which programs can use to establish connections with each other. > Isn't that what the host and port are used for, to open a > connection? Yes, but a connection and a network aren't the same. When you pick up the phone and dial it, a connection between your phone and the phone your calling is set up. You dialing the phone isn't creating a telephone phone network -- it's using the existing telephone network to create a connection. In the case of the telephones, the "network" is the wires, the central office switches (and associated software), and the interconnecting trunks. In your house, the "network" is the wires and router and cable modem and network cards (and the associated configuration data). Your "home network" may or may not have a connection to the outside world. > (Just to clarify, when I say "in no way connected", I don't > mean not connected to the internet in general. I know they > need access to the internet for any kind of networking program > to work at all.) No, the two computers don't need to be connected to the internet in general. You could set up a network that consists entirely of those two computers and nothing else. Applications on those two computers could still communication with each other. -- Grant Edwards grante Yow! Why don't you at ever enter and CONTESTS, visi.com Marvin?? Don't you know your own ZIPCODE? From celoserpa at gmail.com Mon Jun 9 14:32:00 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Mon, 9 Jun 2008 15:32:00 -0300 Subject: Using ElementTree as backend for a chat web application issues Message-ID: <1e5bcefd0806091132p78f42109t1edb5e5acfaadb43@mail.gmail.com> Hello list, I've built a chat with a front-end Ajax client and backend usign ElementTree to persist the data. The problem is that the xml structure I use to persist some of the global configuration of the application usually gets corrupted, for example, let's say the structure is something like: In some circunstances I could not yet discover (it seems random) when I edit/save the structure, the structure gets corrupted, elementree seems to get lost in its internal "cursor", usually something like this happens: id="3"/> Pretty strange, and it drives the whole application unusable. I don't know if the concurrent nature of the application (multiple users using the client at almost the same time and sending data to the server which in turn must save the data to the same global.xml file) has something to do with it - I don't know if ElementTree is suitable for this kind of thing. How to hanlde this concurrent issue? My code seems to work ok, as when the XML doesn't get corrupted, all the features of the chat work nicely. I can show the code here, but it is too big and I don't have a clue where this problem would be sitted. It is simple, it just uses the parse method of elementree to read the xml and the write method to write, nothing fancy. If someone could "smell" what could be the cause of this problem and tell me, I would be grateful. -------------- next part -------------- An HTML attachment was scrubbed... URL: From torriem at gmail.com Sat Jun 21 19:20:02 2008 From: torriem at gmail.com (Michael Torrie) Date: Sat, 21 Jun 2008 17:20:02 -0600 Subject: Fast and easy GUI prototyping with Python In-Reply-To: References: <9c349bf0-ef63-4463-bd4e-cdbe331b58c3@z66g2000hsc.googlegroups.com> Message-ID: <485D8CA2.9030804@gmail.com> erokar at gmail.com wrote: > 2) The Qt vs. .NET API. I have no experience with Qt's API and a > rudimentary experience with the .NET API (seems powerfull but also big > and complex). Qt's API is very very good. Easy to use and extremely powerful. Note that in Python a number of Qt's APIs are not used in favor of Python native apis for things like file and socket I/O, IPC, Threads, and so forth. Additionally, PyQT does allow you the flexibility to move to other platforms. That need may not exist for you now, but it never makes sense to me to needlessly lock yourself down. As far as GUI design goes, Qt and SWF would be on par, likely. It's a bit of a misnomer to be comparing Qt to the .NET API. In IronPython you can of course leverage all the class libraries in the CLR, but most python programmers prefer to use python native libraries wherever possible. If you follow that, then it's SWF that compares to Qt. I've not used VS 2008's SWF gui designer, but of all the designers I've seen so far, Qt's Designer is the best I've ever used. I don't ever use code generation (GUIs should be created from the XML definitions), so integration with an IDE is not a concern for me. One issue about Qt is licensing, which could completely kill it for you. Although technically PyQt would insulate you from this issue to a point, TrollTech will not license Qt for your use in a non-GPL project if you began developing the project using the GPL version of Qt. From ng at invalid.fr Wed Jun 25 07:34:06 2008 From: ng at invalid.fr (Nicolas Girard) Date: 25 Jun 2008 11:34:06 GMT Subject: Wrapping a method twice Message-ID: <48622d2e$0$6051$9a6e19ea@unlimited.newshosting.com> Hi all, given the following code: --- def append(method,bottom): def wrapped(*args, **kwargs): res = method(*args, **kwargs) return bottom(res,*args, **kwargs) setattr(method.im_class,method.__name__,wrapped) def prepend(method,top): def wrapped(*args, **kwargs): top(*args, **kwargs) return method(*args, **kwargs) setattr(method.im_class,method.__name__,wrapped) def test(): class C: def f(self): print "f" def pre(self): print "pre" def post(res,self): print "post" prepend(C.f,pre) append(C.f,post) C().f() --- how comes that test() only outputs: pre f rather than what I expected: pre f post Thanks very much in advance, cheers, Nicolas From alexnbryan at gmail.com Tue Jun 24 00:13:45 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Mon, 23 Jun 2008 23:13:45 -0500 Subject: Sending information to a website Message-ID: Okay, so what I want to do is connect to dictionary.com and send the website a word, and later receive the definition. But for now, I want to focus on sending the word. A good guy from this mailing list said I should look into the code and then figure out what the word you want to be defined is called by the website. In other words, what is the name of the word the user inputs. Okay, so using the firebug extension I got the code that the search field on the website uses. here is that code.
> > > The construct [abc] does not match a whole word but only one char, so ? > > [^table] means "any char which is not t, a, b, l or e". > > > Anyway the inside table word won't match your pattern, as there are '<' > > and '>' in it, and these chars have to be escaped when used as simple text. > > So this should work: > > > re.compile(r'.*') > > ? ? ? ? ? ? ? ? ? ? ^ this is to avoid matching a tag name starting with > > ? ? ? ? ? ? ? ? ? ? table > > (like ) > > Doesn't work - for example it matches '
' > (and in fact if the html contains any number of tables it's going > to match the string starting at the start of the first table and > ending at the end of the last one.) > Try something like: re.compile(r'.*?', re.DOTALL) From wizzardx at gmail.com Sun Jun 8 09:20:01 2008 From: wizzardx at gmail.com (David) Date: Sun, 8 Jun 2008 15:20:01 +0200 Subject: Code correctness, and testing strategies In-Reply-To: <87hcc4jk4l.fsf@benfinney.id.au> References: <18c1e6480805240534k1da68fc8rfbace233f0de6e40@mail.gmail.com> <87hcc4jk4l.fsf@benfinney.id.au> Message-ID: <18c1e6480806080620v6ce0f416tece28a9f18722593@mail.gmail.com> Thanks for your informative reply. On Sun, Jun 8, 2008 at 12:28 PM, Ben Finney wrote: > David writes: > [...] > >> My problem is that I haven't run the app once yet during development >> :-/ > > That might be an artifact of doing bottom-up implementation > exclusively, leading to a system with working parts that are only > integrated into a whole late in the process. > I did do it in a mostly top-down way, but didn't stop the BDD process to actually run the app :-) It sounds like what you are suggesting is something like this: 1) Following BDD, get a skeleton app working Then, your BDD process gets a few extra steps: Old steps: 1) Write a test which fails for [new feature] 2) Write code for [new feature] to pass the test 3) Refactor if needed New steps: 4) Run the app like an end-user, and see that it works for the [new feature] 5) Write an automated test which does (4), and verifies the [new feature] is working correctly Does this mean that you leave out the formal 'integration' and 'systems' testing steps? By actually running the app you are doing those things more or less. Could you also leave out the unit tests, and just write automated acceptance tests? I guess that would have problems if you wanted to re-use code in other apps. Or, if acceptance tests break then it's harder to see which code is causing the problem. Also, if you had to implement a few "user stories" to get your app into a skeleton state, do you need to go back and write all the missing acceptance tests? I have a few problems understanding how to write automated acceptance tests. Perhaps you can reply with a few URLs where I can read more about this :-) 1) services If your app starts, and keeps running indefinitely, then how do you write acceptance tests for it? Does your acceptance tests need to interact with it from the outside, by manipulating databases, system time, restarting the service, etc? I presume also that acceptance tests need to treat your app as a black box, so they can only check your apps output (log files, database changes, etc), and not the state of objects etc directly. 2) User interfaces How do you write an acceptance test for user interfaces? For unit tests you can mock wx or gtk, but for the 'real' app, that has to be harder. Would you use specialised testing frameworks that understand X events or use accessibility/dcop/etc interaction? 3) Hard-to-reproduce cases. How do you write acceptance tests for hard-to-reproduce cases where you had to use mock objects for your unit tests? ... In cases like the above, would you instead: - Have a doc with instructions for yourself/testers/qa to manually check features that can't be automatically tested - Use 'top-down' integration tests, where you mock parts of the system so that that features can be automatically tested. - Some combination of the above [...] >> Is it worth the time to write integration tests for small apps, or >> should I leave that for larger apps? > > There is a threshold below which setting up automated build > infrastructure is too much overhead for the value of the system being > tested. There is no 'build' process (yet), since the app is 100% Python. But I will be making a Debian installer a bit later. My current 'build' setup is something like this: 1) Make an app (usually C++, shell-script, Python, or mixed) 2) Debianise it (add a debian subdirectory, with control files so Debian build tools know how to build binaries from my source, and how they should be installed & uninstalled). 3) When there are new versions, manually test the new version, build a binary debian installer (usually in a Debian Stable chroot with debian tools), on my Debian Unstable dev box, and upload the deb file (and updated Debian repo listing files) to a 'development' or 'unstable' branch on our internal Debian mirror. 4) Install the new app on a Debian Stable testing box, run it, and manually check that the new logic works 5) Move the new version to our Debian repo's live release, from where it will be installed into production. If I adopt BDD, my updated plan was to use it during app development and maintenance, but not for later testing. Do you suggest that after building a .deb in the chroot, the app should also be automatically installed under a chroot & acceptance tests run on my dev machine? Or should I package the acceptance tests along with the app, so that they can be (manually) run on test servers before going into production? Or do both? I've considered setting up a centralised build server at work, but currently I'm the only dev which actually builds & packages software, so it wouldn't be very useful. We do have other devs (PHP mostly), but they don't even use version control :-/. When they have new versions (on their shared PHP dev & testing servers), I copy it into my version control, confirm the changed files with them, build an installer, and upload onto our mirror, so it can be installed onto other boxes. David. From paddy3118 at googlemail.com Thu Jun 19 23:39:36 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 19 Jun 2008 20:39:36 -0700 (PDT) Subject: Pattern Matching Over Python Lists References: <21a9c996-75ff-4f7c-b7e9-c94247f65674@c58g2000hsc.googlegroups.com> <87ej6w6ql6.fsf@internal.daycos.com> <61ea5c70-4352-4d2f-a0ef-62eb76ba933a@m36g2000hse.googlegroups.com> <0796be8f-647c-4d19-86e5-e2472fb2daa3@34g2000hsh.googlegroups.com> Message-ID: On Jun 20, 1:44?am, Chris wrote: > Thanks for your help. Those weren't quite what I was looking for, but > I ended up figuring it out on my own. Turns out you can actually > search nested Python lists using simple regular expressions. Strange? How do you match nested '[' ... ']' brackets? - Paddy. From dullrich at sprynet.com Thu Jun 26 14:26:55 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 26 Jun 2008 13:26:55 -0500 Subject: ask for a RE pattern to match TABLE in html References: <6a4f17690806260653i136681bdsabe0f6bb1dfab67b@mail.gmail.com> Message-ID: In article , C?dric Lucantis wrote: > Le Thursday 26 June 2008 15:53:06 oyster, vous avez ?crit?: > > that is, there is no TABLE tag between a TABLE, for example > > something with out table tag
> > what is the RE pattern? thanks > > > > the following is not right > > [^table]*? > > The construct [abc] does not match a whole word but only one char, so > [^table] means "any char which is not t, a, b, l or e". > > Anyway the inside table word won't match your pattern, as there are '<' > and '>' in it, and these chars have to be escaped when used as simple text. > So this should work: > > re.compile(r'.*') > ^ this is to avoid matching a tag name starting with > table > (like ) Doesn't work - for example it matches '
' (and in fact if the html contains any number of tables it's going to match the string starting at the start of the first table and ending at the end of the last one.) -- David C. Ullrich From wizzardx at gmail.com Sun Jun 22 06:14:55 2008 From: wizzardx at gmail.com (David) Date: Sun, 22 Jun 2008 12:14:55 +0200 Subject: Storing value with limits in object In-Reply-To: References: Message-ID: <18c1e6480806220314i1e0af4cel7c7cbc1acad49b09@mail.gmail.com> On Sun, Jun 22, 2008 at 11:44 AM, Josip wrote: > I'm trying to limit a value stored by object (either int or float): > > class Limited(object): > def __init__(self, value, min, max): > self.min, self.max = min, max > self.n = value > def set_n(self,value): > if value < self.min: # boundary check > self.n = self.min > if value > self.max: > self.n = self.max > else: > self.n = value > n = property(lambda self : self._value, set_n) > > This works, except I would like the class to behave like built-in types, so > I can use it like this: > > a = Limited(7, 0, 10) > b = math.sin(a) > > So that object itself returns it's value (which is stored in a.n). Is this > possible? > Not with normal vars, because = is a rebinding operator in Python, rather than assignment. You can do (close to) the above with object properties. David. From fuzzyman at gmail.com Thu Jun 5 09:26:54 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Thu, 5 Jun 2008 06:26:54 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> Message-ID: On Jun 3, 6:54 pm, sturlamolden wrote: > On May 24, 3:41 pm, Sh4wn wrote: > > > first, python is one of my fav languages, and i'll definitely keep > > developing with it. But, there's 1 one thing what I -really- miss: > > data hiding. I know member vars are private when you prefix them with > > 2 underscores, but I hate prefixing my vars, I'd rather add a keyword > > before it. > > Python has no data hiding because C++ has (void *). > > Python underscores does some name mangling, but does not attempt any > data hiding. > > Python and C has about the same approach to data hiding. It is well > tried, and works equally well in both languages: > > # this is mine, keep your filthy paws off!!! > > Irresponsible programmers should not be allowed near a computer > anyway. If you use data hiding to protect your code from yourself, > what you really need is some time off to reconsider your career. So, you are stating that no API programmer using Python *ever* has a valid or genuine reason for wanting (even if he can't have it) genuine 'hiding' of internal state or members from consumers of his (or her...) API? Michael Foord http://www.ironpythoninaction.com/ From eliben at gmail.com Mon Jun 9 07:06:54 2008 From: eliben at gmail.com (eliben) Date: Mon, 9 Jun 2008 04:06:54 -0700 (PDT) Subject: Access to CAN-Bus References: <484cd469$0$28520$3b214f66@aconews.univie.ac.at> Message-ID: On Jun 9, 8:57 am, Thin Myrna wrote: > I'd like to access some drive hardware via CAN bus from Python under Linux > (sending rec'ing PDOs). Googling around I couldn't find a Python package, > but people who said that they are doing this, though. I guess they are > using their home brewn software. > > Any pointer to > - such software (anyone willing to share his experience?) > - how to write such software? > > Under Windows, I guess, I could use some COM or ctypes functionality to > access the hardware vendor's hardware. What if I wanted to access such > hardware from Linux? Is there a package that allows that in a vendor (who > doesn't support Linux) independent way? > > Many thanks in advance > Thin I don't think this can be done in a vendor independent way, because as far as I know there is no standard for CAN drivers. It all depends on the card you have and what its maker supplies. It usually works as follows: the car maker supplies a DLL file with some examples of calling it from C or Visual Basic (for Windows systems). Maybe the DLL is downloadable from the company's website. You can easily ruse this DLL from Python, with the excellent 'ctypes' module. I've had some dealings with DLLs from various scripting languages, and I can tell you with confidence that nothing comes close to the ease of use and functionality of ctypes. From koblas at gmail.com Thu Jun 5 11:44:18 2008 From: koblas at gmail.com (koblas) Date: Thu, 5 Jun 2008 08:44:18 -0700 (PDT) Subject: Import removing first module component References: <75481b47-87ec-4a84-8063-7abbdb286d62@u6g2000prc.googlegroups.com> Message-ID: On Jun 4, 2:48?pm, "David C. Ullrich" wrote: > In article > <75481b47-87ec-4a84-8063-7abbdb286... at u6g2000prc.googlegroups.com>, > > ?koblas wrote: > > Have the following line: > > ? ? ? ? import notewave.runner.LMTP > > > Yeilding the following error: > > ? ? ? ? ImportError: No module named runner.LMTP > > > For the life of me I don't understand why the first component > > "notewave" is being stripped off, when the import is happening. > > Does notewave contain a _module_ named runner.LMTP ? > Probably not, since the error message says there's no > such module. > > > Thanks, > > -- > David C. Ullrich The following exist: .../notewave/runner/LMTP.py inside of LMTP.py there is: class LMTPRunner(Runner) : Another person pointed out that I should check on the __init__.py and make sure lmtp is defined in the __all__ block. I didn't have an __init__.py at that level of the tree, which must have been causing problems, but clearly I don't understand the full inheritance of __init__.py and sub-directories. From bruno.desthuilliers at gmail.com Thu Jun 5 15:44:43 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Thu, 5 Jun 2008 12:44:43 -0700 (PDT) Subject: ClassName.attribute vs self.__class__.attribute References: Message-ID: <25e0de62-4c63-4545-8684-69a410639807@i76g2000hsf.googlegroups.com> On 5 juin, 17:40, Gabriel Rossetti wrote: > Hello everyone, > > I had read somewhere that it is preferred to use > self.__class__.attribute over ClassName.attribute to access class (aka > static) attributes. It's even prefered to use self.attribute, unless you know you have both an instance and a class attribute by the same name (but then if you need to know which one you're accessing then you have a serious design problem). > I had done this and it seamed to work, until I > subclassed a class using this technique and from there on things started > screwing up. I finally tracked it down to self.__class__.attribute! What > was happening is that the child classes each over-rode the class > attribute at their level, Which is why it's prefered to access the attribute from the class (or more simply from the instance which will get them from the class) - a subclass may have extremly good reasons to have it's own instance of the attribute. > and the parent's was never set, This is another problem. > so while I was > thinking that I had indeed a class attribute set in the parent, it was > the child's that was set, and every child had it's own instance! Since > it was a locking mechanism, lots of fun to debug... I can well believe it, and you do have my whole sympathy. > So, I suggest never > using self.__class__.attribute, unless you don't mind it's children > overriding it, but if you want a truly top-level class attribute, use > ClassName.attribute everywhere! I would not have expressed it that way. My own experience is that, most of the time, you do know when it's ok for the subclasses to have their own instance of the attribute and when it's not, so in the (very rare) cases it's not ok you use __name_mangling. Now I'd say that *unknowingly* overriding an attribute of your own base class when you didn't expect it to happen is mostly a sign that there's something you don't (didn't ?) quite get wrt/ lookup / assignment / namespace etc rules in Python. > I wish books and tutorials mentioned this explicitly.... Possibly. OTHO, if you understand Python's lookup (name resolution) rules, the difference between MyBaseClass.attrib and self.__class__.attrib should be obvious. But this surely could be a good example in a tutorial !-) From patrick.m.bouffard at gmail.com Tue Jun 10 10:04:24 2008 From: patrick.m.bouffard at gmail.com (Patrick Bouffard) Date: Tue, 10 Jun 2008 14:04:24 +0000 (UTC) Subject: Determining which things in 'from package import *' are actually used Message-ID: I have a fairly large library of Python code, where 'from package import *' is used rather liberally, and it's not uncommon for more than one of these to appear in any given module. What I'd like to be able to do is to clean my code up a bit and turn each of the 'from package import *' statements into 'from package import thing_1, thing_2, ..., thing_n', where only thing_i's that are actually _used_ in the module are imported. In this way I hope to make my code a bit more understandable by future civilizations. :) (it needs all the help it can get!) Does anyone know of a package/recipe/whatever that does something like this automatically, even in limited cases? Ideally it should be accomplished only by looking at the source, or at most, importing the module. TIA, -Pat From maric at aristote.info Mon Jun 30 18:21:28 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 1 Jul 2008 00:21:28 +0200 Subject: List Performance In-Reply-To: References: <42358e0b-a351-4862-8f6a-1938eedeff6c@s21g2000prm.googlegroups.com> <200806301609.56831.maric@aristote.info> Message-ID: <200807010021.29250.maric@aristote.info> Le Monday 30 June 2008 22:21:35 Terry Reedy, vous avez ?crit?: > > Well, as I posted few days ago, one could envisage, as a pure python > > optimization for dealing with long list, to replace an algorithm with a > > lot of append by something like this : > > > > mark = object() > > > > datas = [ mark ] * expected_size > > datas = [None] * expected_size > has been a standard idiom since before object() existed ;-) > and works fine *unless* one wants to add None explicitly > and have that be different from 'unused'. Yes, in fact I used a marker because it I thought of it primarily as outbound for the list (like \0 for strings in C), but it doesnt' matter what is the object you put in the list, if you know at every moment its size. A subclass of list will indeed have to override most of the methods of its parent (not just some as I assumed before), using extend for reallocation with some sort of iterator with size, as it work in my previous example with xrange, something like that : >>>[31]: class iter_with_len(object) : def __init__(self, size, obj=None) : self.size = size self.obj = obj def __len__(self) : return self.size def __iter__(self) : return itertools.repeat(self.obj, len(self)) ....: ....: -- _____________ Maric Michaud From veeramanierd at gmail.com Sat Jun 14 03:55:35 2008 From: veeramanierd at gmail.com (pink) Date: Sat, 14 Jun 2008 00:55:35 -0700 (PDT) Subject: ######THEY DO DIFFERENT THINGS TO GET HERE######### Message-ID: <18acafd3-185e-4afd-b264-5f08e08fc5d2@q27g2000prf.googlegroups.com> Hi girls and friends...... earn more money in my site its really very different you want like it.... see it ..... www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com From info at egenix.com Wed Jun 18 12:27:17 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Wed, 18 Jun 2008 18:27:17 +0200 Subject: ANN: eGenix mx Base Distribution 3.1.0 Message-ID: <48593765.4080206@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com mx Base Distribution Version 3.1.0 Open Source Python extensions providing important and useful services for Python programmers. This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mx-Base-Distribution-3.1.0-GA.html ________________________________________________________________________ ABOUT The eGenix.com mx Base Distribution for Python is a collection of professional quality software tools which enhance Python's usability in many important areas such as fast text searching, date/time processing and high speed data types. The tools have a proven record of being portable across many Unix and Windows platforms. You can write applications which use the tools on Windows and then run them on Unix platforms without change due to the consistent platform independent interfaces. Contents of the distribution: * mxDateTime - Date/Time Library for Python * mxTextTools - Fast Text Parsing and Processing Tools for Python * mxProxy - Object Access Control for Python * mxBeeBase - On-disk B+Tree Based Database Kit for Python * mxURL - Flexible URL Data-Type for Python * mxUID - Fast Universal Identifiers for Python * mxStack - Fast and Memory-Efficient Stack Type for Python * mxQueue - Fast and Memory-Efficient Queue Type for Python * mxTools - Fast Everyday Helpers for Python All available packages have proven their stability and usefulness in many mission critical applications and various commercial settings all around the world. * About Python: Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. * About eGenix: eGenix is a consulting and software product company focused on providing professional quality services and products to Python users and developers (http://www.egenix.com/). ________________________________________________________________________ NEWS The 3.1.0 release of the eGenix mx Base Distribution has a number of enhancements over the previous version 3.0.0. Apart from a few minor bug fixes, it provides a few new features: Some highlights: * mxTools now has a new mx.Tools.dlopen() function which allow loading shared libraries explicitly and from a specific path. This allows working around problems with not being able to dynamically set LD_LIBRARY_PATH on Unix platforms. * mxTools can be configured to expose a new API called mx.Tools.setproctitle() which allows setting the process title on Unix platforms. * mxBeeBase comes with a new on-disk dictionary version called BeeFixedLengthStringDict, which allows using keys with embedded \0 characters. * mxSetup, our Python distutils extension, can now build prebuilt archives that no longer require the "... build --skip ..." command to skip the build process. The uninstall command now also works for prebuilt archives and the bdist_prebuilt command has been enhanced to be able to build pure Python distributions as well. * mxSetup now also works together with setuptools to e.g. build and install the packages as eggs. Run setup.py with --use-setuptools to enable this support. For a more detailed description of changes, please see the respective package documentation on our web-site. As always, we are providing pre-compiled versions of the package for the most popular Python platforms. For all others, you can compile the package from source using "python setup.py install". ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the packages can be found on the eGenix mx Base Distribution page: http://www.egenix.com/products/python/mxBase/ ________________________________________________________________________ LICENSE The eGenix mx Base package is distributed under the eGenix.com Public License 1.1.0 which is a CNRI Python License style Open Source license. You can use the package in both commercial and non-commercial settings without fee or charge. The package comes with full source code ________________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jun 18 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania 18 days to go :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From larry.bates at websafe.com` Sat Jun 14 10:36:48 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 14 Jun 2008 09:36:48 -0500 Subject: Platform independent code? In-Reply-To: References: Message-ID: saneman wrote: > I have read that Python is a platform independent language. But on this > page: > > http://docs.python.org/tut/node4.html#SECTION004220000000000000000 > > it seems that making a python script executable is platform dependant: > > 2.2.2 Executable Python Scripts > On BSD'ish Unix systems, Python scripts can be made directly executable, > like shell scripts, by putting the line > > > #! /usr/bin/env python > (assuming that the interpreter is on the user's PATH) at the beginning of > the script and giving the file an executable mode. The "#!" must be the > first two characters of the file. On some platforms, this first line must > end with a Unix-style line ending ("\n"), not a Mac OS ("\r") or Windows > ("\r\n") line ending. Note that the hash, or pound, character, "#", is used > to start a comment in Python. > > The script can be given an executable mode, or permission, using the chmod > command: > > > $ chmod +x myscript.py > > > > Are there any guidelines (API'S) that gurantees that the python code will be > platform independent? > > Generally you have to stay away from platform "dependent" constructs. Esamples: 1) Use os.path methods everywhere in your code so you won't need to worry about os.path.sep (slash or backslash). 2) Use lowest common denominator when naming files to make your scripts work cross platform. 3) Stay away from os-specific calls/interfaces when possible. Manipulating file permissions, etc is always os-specific. 4) Use config files instead of relying on registry in Windows. 5) Stay away from code that depends on 32/64 bit objects or endian-ness of storage (struct objects). This is machine specific not OS specific but still counts. 6) If you have GUI, use something like wxWindows which provides cross platform GUI support. 7) Be careful using non-Python libraries (C-libraries) should be done with care to make sure that the library is available for all target operating systems. 8) using os.system or the subsystem module must be done with much care and probably won't be cross platform compatible. Hope the suggestions help. -Larry From bedouglas at earthlink.net Fri Jun 13 17:09:17 2008 From: bedouglas at earthlink.net (bruce) Date: Fri, 13 Jun 2008 14:09:17 -0700 Subject: python screen scraping/parsing In-Reply-To: Message-ID: <20dc01c8cd99$be86e120$0301a8c0@tmesa.com> Hi Paul... Thanks for the reply. Came to the same conclusion a few minutes before I saw your email. Another question: tr=d.xpath(foo) gets me an array of nodes. is there a way for me to then iterate through the node tr[x] to see if a child node exists??? "d" is a document object, while "tr" would be a node object?, or would i convert the "tr[x]" to a string, and then feed that into the libxml2dom.parseString()... thanks -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of Paul Boddie Sent: Friday, June 13, 2008 12:49 PM To: python-list at python.org Subject: Re: python screen scraping/parsing On 13 Jun, 20:10, "bruce" wrote: > > url ="http://www.pricegrabber.com/rating_summary.php/page=1" [...] > tr = > "/html/body/div[@id='pgSiteContainer']/div[@id='pgPageContent']/table[2]/tbo > dy/tr[4]" > > tr_=d.xpath(tr) [...] > my issue appears to be related to the last "tbody", or tbody/tr[4]... > > if i leave off the tbody, i can display data, as the tr_ is an array with > data... Yes, I can confirm this. > with the "tbody" it appears that the tr_ array is not defined, or it has no > data... however, i can use the DOM tool with firefox to observe the fact > that the "tbody" is there... Yes, but the DOM tool in Firefox probably inserts virtual nodes for its own purposes. Remember that it has to do a lot of other stuff like implement CSS rendering and DOM event models. You can confirm that there really is no tbody by printing the result of this... d.xpath("/html/body/div[@id='pgSiteContainer']/ div[@id='pgPageContent']/table[2]")[0].toString() This should fetch the second table in a single element list and then obviously give you the only element of that list. You'll see that the raw HTML doesn't have any tbody tags at all. Paul -- http://mail.python.org/mailman/listinfo/python-list From stdenton at sbcglobal.net Sun Jun 1 11:40:09 2008 From: stdenton at sbcglobal.net (Sam Denton) Date: Sun, 01 Jun 2008 10:40:09 -0500 Subject: Integrating a code generator into IDLE Message-ID: Code generators seem to be popular in Python. (http://www.google.com/search?q=python+code-generator) I have one that I'd like to integrate into IDLE. Ideally, I'd like to (1) have a new file type show up when I use the File/Open dialog, and (2) have a function key that lets me run my generator against the file, just like F5 lets me run my Python code; ideally, I'd like to re-purpose the F5 key to be file-type aware. I've got a simple extension written that uses the F6 key to "compile" my files, but two goals I've listed seem a bit beyond me. Does anyone have any advice/pointers? Or is one or both ideas impractical? Thanks! From theo at van-werkhoven.nl.invalid Sun Jun 8 16:57:00 2008 From: theo at van-werkhoven.nl.invalid (Theo v. Werkhoven) Date: Sun, 8 Jun 2008 22:57:00 +0200 Subject: time.clock() or Windows bug? References: Message-ID: The carbonbased lifeform Nick Craig-Wood inspired comp.lang.python with: > Theo v. Werkhoven wrote: >> Output: >> Sample 1, at 0.0 seconds from start; Output power is: 8.967 dBm > [snip] >> Sample 17, at 105.7 seconds from start; Output power is: 9.147 dBm >> Sample 18, at 112.4 seconds from start; Output power is: 9.284 dBm >> Sample 19, at 119.0 seconds from start; Output power is: 9.013 dBm >> Sample 20, at 125.6 seconds from start; Output power is: 8.952 dBm >> Sample 21, at 91852.8 seconds from start; Output power is: 9.102 dBm >> Sample 22, at 91862.7 seconds from start; Output power is: 9.289 dBm >> Sample 23, at 145.4 seconds from start; Output power is: 9.245 dBm >> Sample 24, at 152.0 seconds from start; Output power is: 8.936 dBm > [snip] >> But look at the timestamps of samples 21, 22 and 43. >> What is causing this? >> I've replaced the time.clock() with time.time(), and that seems to >> solve the problem, but I would like to know if it's something I >> misunderstand or if it's a problem with the platform (Windows Server >> 2003) or the time.clock() function. > > time.clock() uses QueryPerformanceCounter under windows. There are > some known problems with that (eg with Dual core AMD processors). > > See http://msdn.microsoft.com/en-us/library/ms644904.aspx > > And in particular > > On a multiprocessor computer, it should not matter which processor > is called. However, you can get different results on different > processors due to bugs in the basic input/output system (BIOS) or > the hardware abstraction layer (HAL). To specify processor > affinity for a thread, use the SetThreadAffinityMask function. Alright, that explains that then. > I would have said time.time is what you want to use anyway though > because under unix time.clock() returns the elapsed CPU time which is > not what you want at all! You're right, using fuctions that do not work cross platform isn't smart. Cheers for the explanation Nick Theo -- theo at van-werkhoven.nl ICQ:277217131 SuSE Linux linuxcounter.org: 99872 Jabber:muadib at jabber.xs4all.nl AMD XP3000+ 1024MB "ik _heb_ niets tegen Microsoft, ik heb iets tegen de uitwassen *van* Microsoft" From brian_vanderburg2 at yahoo.com Wed Jun 18 02:53:15 2008 From: brian_vanderburg2 at yahoo.com (Allen) Date: Wed, 18 Jun 2008 02:53:15 -0400 Subject: Ternary operator alternative in Ptyhon In-Reply-To: References: Message-ID: kretik wrote: > I'm sure this is a popular one, but after Googling for a while I > couldn't figure out how to pull this off. > > Let's say I have this initializer on a class: > > def __init__(self, **params): > > I'd like to short-circuit the assignment of class field values passed in > this dictionary to something like this: > > self.SomeField = \ > params.has_key("mykey") ? params["mykey"] : None) > > Obviously I know this is not actual Python syntax, but what would be the > equivalent? I'm trying to avoid this, basically: > > if params.has_key("mykey"): > self.SomeField = params["mykey"] > else: > self.SomeField = None > > This is not a big deal of course, but I guess my main goal is to try and > figure out of I'm not missing something more esoteric in the language > that lets me do this. > > Thanks in advance. The syntax is a bit different, but: result = (true_value if condition else false_value) is how it is in Pytthon: self.SomeField = (params['mykey'] if params.has_key('mykey') else None) Brian Vanderburg II From rtiago at gmail.com Sat Jun 21 14:16:40 2008 From: rtiago at gmail.com (Ricardo Tiago) Date: Sat, 21 Jun 2008 20:16:40 +0200 Subject: SSL Message-ID: <8ed7d4b30806211116o7561f720j8c3c9f16eb1433c2@mail.gmail.com> Hi, Is it possible to access a https site using a certificate and keeping the session alive like it happens in the browsers? I'm doing a command line app that needs to access a https site to retrieve information but using the httplib, each time i make a request it asks for the pem pass phrase. Thanks, Ricardo -------------- next part -------------- An HTML attachment was scrubbed... URL: From yxs035 at gmail.com Mon Jun 30 05:10:48 2008 From: yxs035 at gmail.com (yxs035 at gmail.com) Date: Mon, 30 Jun 2008 02:10:48 -0700 (PDT) Subject: Jaeger LeCoultre Master Control 1000 Hours - Jaeger LeCoultre Watches Message-ID: Jaeger LeCoultre Master Control 1000 Hours - Jaeger LeCoultre Watches Luxury Gift : http://www.luxury-gift.org Jaeger LeCoultre Watches : http://www.luxury-gift.org/Watches/jaeger-lecoultre-watches.html Jaeger LeCoultre Master Control 1000 Hours : http://www.luxury-gift.org/Watches/Jaeger-LeCoultre-Master-Control-1000-Hours.html Jaeger LeCoultre Master Control 1000 Hours series contain the following items, each item is the perfect marriage of function and design. Jaeger LeCoultre Master Control 1000 Hours are finely copied, you don't need to worry about the quality. We believe that no matter what you're looking for in a watch, our Jaeger LeCoultre Master Control 1000 Hours will exceed your expectations. Explore the World of Brand Watches & Handbags It is a well-known fact that a watch you wear not just serves as a faithful time keeping device,but is also associated with your social status.style and evenframe of mind.If you intend tomake a wise choice as for purchasing awatch just right for you,devote your attention to awide range of high quality brand watches . Jaeger LeCoultre Master Control 1000 Hours All Products : Jaeger LeCoultre Master Geographic 142.240.927SB, Jaeger LeCoultre Master Geographic 142.81.20 (q1428120), Jaeger LeCoultre Master Grande Memovox 146.34.4a (q146344a), Jaeger LeCoultre Master Grande Memovox 146.64.8A (q146648A) 95%, Jaeger LeCoultre Master Memovox 144.24.70 (q1442470), Jaeger LeCoultre Master Memovox 144.24.20 (q1442420), Jaeger LeCoultre Master Eight Days 160.24.20 (q1602420), Jaeger LeCoultre Master Eight Days 160.84.20 (q1608420), Jaeger LeCoultre Master Geographic 142.84.70 (q1428470), Jaeger LeCoultre Master Geographic 142.84.20 (q1428420), Jaeger LeCoultre Master Perpetual 149.34.4A (q149344a) USED 99%, Jaeger LeCoultre Master Reserve de Marche 148.84.04 (q1488404), Jaeger LeCoultre Master Reserve de Marche 148.24.01 (q1482401), Jaeger LeCoultre Master Reserve de Marche 148.84.03 (q1488403), Jaeger LeCoultre Master Reveil 141.24.20 (q1412420), Jaeger LeCoultre Master Tourbillon 165.24.20 (q1652420), Jaeger LeCoultre Master Tourbillon 165.84.20 (q1658420), Jaeger LeCoultre Master Tourbillon 165.81.20 (q1658120), Jaeger LeCoultre Master Tourbillon 165.64.50 (q1656450), Jaeger LeCoultre Master Ultra Thin 145.35.70, Jaeger LeCoultre Master Ultra Thin 145.85.04 (q1458504), Jaeger LeCoultre Master Ultra Thin 145.64.80 (q1456480), Jaeger LeCoultre Master Ultra Thin 145.84.04 (q1458404), Jaeger LeCoultre Master Ultra Thin 145.24.04 (q1452404), Jaeger LeCoultre Master Ultra Thin 145.25.04 (q1452504), Jaeger LeCoultre Master Ultra Thin 145.85.70 (q1458570), Jaeger LeCoultre Master Control 1000 Hours WebSite Link : http://www.luxury-gift.org/Watches/Jaeger-LeCoultre-Master-Control-1000-Hours.html From duncan.booth at invalid.invalid Fri Jun 20 03:31:19 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Jun 2008 07:31:19 GMT Subject: advanced listcomprehenions? References: Message-ID: Terry Reedy wrote: >> [['Fizz', 'Buzz', 'FizzBuzz', str(i)][62/(pow(i, 4, 15) + 1)%4] for i >> in xrange(1, 101)] > > These make the lookup table variable, so it has to be recalculated for > each i. > So what? Mark Wooding was posting about mathematical elegance and came up with that really neat pow() call. If runtime came into it then one of the previous solutions or (as Mark already said) a straightforward sometable[i% 15] is going beat something like this hands-down. This is coding for fun not profit. -- Duncan Booth http://kupuguy.blogspot.com From kyosohma at gmail.com Wed Jun 18 08:52:39 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 18 Jun 2008 05:52:39 -0700 (PDT) Subject: Google Module? References: <1cbf2da8-4e64-4d15-9617-bdbb42648057@f36g2000hsa.googlegroups.com> Message-ID: <453cc218-9721-4802-8ccf-b296feae9a9e@p25g2000hsf.googlegroups.com> On Jun 18, 2:54?am, JulianMontez wrote: > Just started learning Python and wanted to make a program that would > retrieve files that were indexed by Google. These files can be > filtered by their extensions, nothing too difficult. :) > > I wanted to know if there was a module that would allow me to access > the API easily within Python. I don't think that pyGoogle works > anymore (supposedly the SOAP API was discontinued). > > Thanks in advance! You're probably looking for the gdata module: http://code.google.com/p/gdata-python-client/ It hooks into most of Google's APIs. Mike From aweraw at gmail.com Fri Jun 13 05:34:04 2008 From: aweraw at gmail.com (Aidan) Date: Fri, 13 Jun 2008 19:34:04 +1000 Subject: boolian logic In-Reply-To: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> References: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> Message-ID: marc wyburn wrote: > HI all, I'm a bit stuck with how to work out boolian logic. > > I'd like to say if A is not equal to B, C or D: > do something. > > I've tried > > if not var == A or B or C: > and various permutations but can't seem to get my head around it. I'm > pretty sure I need to know what is calulated first i.e the not or the > 'OR/AND's > > thanks, Marc. You mean like a ternary operation? >>> True and 1 or 0 1 >>> False and 1 or 0 0 This of course depends on the 'true' result also being true.. it fails if it is false... if that's not what you mean, then maybe this is what you want if not var==A or not var==B or not var==C: # do something From n.emami at gmail.com Fri Jun 13 03:37:44 2008 From: n.emami at gmail.com (Nader) Date: Fri, 13 Jun 2008 00:37:44 -0700 (PDT) Subject: Checking list by using of exception Message-ID: <3bdcc52d-2432-4b28-8188-bf7c811859d1@d45g2000hsc.googlegroups.com> Hello, I read some files name from a directory and then I put these name in a list. I will check whether it is empty or not, and I would do it with an exception. With if statement it is very simple: If list_of_files != "" : # this can be if list_of_files != []: get the files elas: there is no file But with exception, I can write something as: try: list_of_files != [] get the files except ValueError: Print " there is no file" What can the first statement be inside 'try' if I don't want to use if statement? Maybe my understandig of exception is enough to got it. Would somebody explain me about this? Regards, Nader try and except in a dircMaybe this quetion will be simple enough for you. From asmodai at in-nomine.org Mon Jun 16 10:05:01 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 16 Jun 2008 16:05:01 +0200 Subject: Who is using python-ldap with Python 1.5.x and 2.0-2.2? In-Reply-To: <6h7ii5-l9m.ln1@nb2.stroeder.com> References: <6h7ii5-l9m.ln1@nb2.stroeder.com> Message-ID: <20080616140501.GC64377@nexus.in-nomine.org> -On [20080616 15:55], Michael Str?der (michael at stroeder.com) wrote: >I'd like to hear from the Python community whether support for Python >version prior to 2.3 is still needed in python-ldap. Please tell me >which Python version you're using and why it'd be important for you to >have python-ldap updates still supporting it. Not that I use python-ldap at work, but our lowest Python version is 2.3 and we're working towards making 2.5 the default. Hopefully that helps you for versions used. :) -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B But the time has come when all good things shall pass... From jamitwidme at gmail.com Thu Jun 26 10:41:27 2008 From: jamitwidme at gmail.com (jamitwidme at gmail.com) Date: Thu, 26 Jun 2008 07:41:27 -0700 (PDT) Subject: ConfigParser: Can I read(ConfigParser.get()) a configuration file and use it to call a funciton? Message-ID: <34b51593-d787-4f12-9cc2-473d3832ff0d@k37g2000hsf.googlegroups.com> Hello. I am a novice programmer and have a question I have a configuration file(configuration.cfg) I read this from reading.py using ConfigParser When I use ConfigParser.get() function, it returns a string. I want to call a function that has the same name as the string from the configuration file. configuration.cfg --------------------------------------- [1234] title: abcd function: efgh --------------------------------------- reading.py -------------------------------------------------------- import ConfigParser def efgh(): print 'blah' config = ConfigParser.ConfigParser() config.read('configuration.cfg') fcn = config.get('1234','function') type(fcn) print fcn -------------------------------------------------------- efgh Is there any way to call efgh() ? One way I know is using if statement if fcn == 'efgh': efgh() But I am going to have many functions to call, so I want to avoid this. Thank you for your help From maxm at mxm.dk Wed Jun 4 09:11:53 2008 From: maxm at mxm.dk (Max M) Date: Wed, 04 Jun 2008 15:11:53 +0200 Subject: Handling some isolated iso-8859-1 characters In-Reply-To: References: Message-ID: Daniel Mahoney skrev: > The interesting patch is the string that reads "=?iso-8859-1?Q?Ana=EFs?=". > An HTML rendering of what this string should look would be "Anaïs". There is a mention of email headers and unicode in the end of this article: http://mxm-mad-science.blogspot.com/2008/03/python-unicode-lessons-from-school-of.html -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From giuott at gmail.com Mon Jun 23 00:58:25 2008 From: giuott at gmail.com (Giuseppe Ottaviano) Date: Sun, 22 Jun 2008 21:58:25 -0700 Subject: Bind compiled code to name? In-Reply-To: <485EB8F5.4080503@v.loewis.de> References: <485e9aea$0$637$9b622d9e@news.freenet.de> <485EB8F5.4080503@v.loewis.de> Message-ID: <380957DB-676C-498E-AE57-D14E67E0AB68@gmail.com> > class D:pass > d = D() > exec source_code in d.__dict__ > print d.some_name > > Notice that this will also give you d.__builtins__, which you might > want to del afterwards. If you want to mimic an import you can also do this: import types D = types.ModuleType('D') exec source_code in D.__dict__ print D.some_name This way D is a module (don't know if there are real differences with the class approach, though) From socyl at 987jk.com.invalid Sun Jun 8 13:03:52 2008 From: socyl at 987jk.com.invalid (kj) Date: Sun, 8 Jun 2008 17:03:52 +0000 (UTC) Subject: How to get full path to script? Message-ID: How can a script know its absolute path? (__file__ only gives the path it was used to invoke the script.) Basically, I'm looking for the Python equivalent of Perl's FindBin. The point of all this is to make the scripts location the reference point for the location of other files, as part of a self-contained distribution. TIA! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From kyosohma at gmail.com Mon Jun 2 16:28:12 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 2 Jun 2008 13:28:12 -0700 (PDT) Subject: platypus in page header References: Message-ID: <90b1c701-a316-4577-8bf8-fddfa12e4ee8@d77g2000hsb.googlegroups.com> On Jun 2, 1:16?pm, Laszlo Nagy wrote: > Is it possible to use platypus in page header and footer? I need to > create a document with long paragraphs but also I need to put tables and > images in page header and multi line info in page footer with alignment etc. > > Thanks, > > ? ?Laszlo From looking at the docs, it sounds like you could do that, if you create your flowables correctly. You should probably ask over on the reportlab user's list though. Those guys would almost certainly know: http://two.pairlist.net/mailman/listinfo/reportlab-users Mike From ks.mathiesen at gmail.com Mon Jun 23 06:28:50 2008 From: ks.mathiesen at gmail.com (Knut Saua Mathiesen) Date: Mon, 23 Jun 2008 12:28:50 +0200 Subject: Sending arrays of a structure as an argument via ctypes Message-ID: <97a99e230806230328x761454a3i49a850c386db283a@mail.gmail.com> Hi there. I am reprogrammed my astar* path finding algorithm in C to make it quicker. I am now trying to make python use this C extension, however I keep getting "Segmentation fault". Some of the C stuff: typedef struct Point { int x; int y; } Point; typedef struct Node { Point pos; int cost; int g; int obstacle; struct Node* parent; } Node; void astar(Node map[], Point from, Point to) { (...) } main () { (...) Node map[maptotal]; (...) astar(map, createPoint(0,0), createPoint(50,50)); } Now I am by no means a C programmer, this is basicly the first "bigger than hello-world" program, but I have got it working in C. What I am now trying to do is to make the map using python, and send it to my astar C function using ctypes. Basicly I've rewritten my structures in python: class Point(Structure): _fields_ = [("x", c_int), ("y", c_int)] def __repr__(self): return "" % (self.x, self.y) class Node(Structure): def __repr__(self): return "" % (self.pos.x, self.pos.y) Node._fields_ = [('pos', Point), ('cost', c_int), ('g', c_int), ('obstacle', c_int), ('parent',POINTER(Node))] And after that, this is how I am trying to call it: self.astar = astarlib.astar self.astar.argtypes = [Node * self.maptotal, Point, Point] self.astar.restype = None self.nodes = (Node * self.maptotal)() for i in range(self.mapwidth): for i2 in range(self.mapheight): self.nodes[i2 * self.mapwidth + i] = Node(Point(i, i2)) self.astar(self.nodes, Point(5,6), Point(6,6)) When I call the self.astar function it segfaults. And what I think I've done wrong is the self.nodes part, but I can't find any good documentation on it. Any help? :p From lucaberto at libero.it Fri Jun 6 06:01:24 2008 From: lucaberto at libero.it (luca72) Date: Fri, 6 Jun 2008 03:01:24 -0700 (PDT) Subject: import cherrypy2 References: <0853b1cc-33bb-416e-9b2e-0fa146ede1c1@79g2000hsk.googlegroups.com> <7c00f301-5d49-4f49-98fd-d0f5e72aa135@c65g2000hsa.googlegroups.com> Message-ID: <85a8b572-3a54-43c4-bc7c-d554888697d5@m45g2000hsb.googlegroups.com> No i haven't install lino but if frmp the python of this computer i make import cherrypy2 i import it without problem this is the python path: luca72 at linux-z0ta:~> python Python 2.5.1 (r251:54863, Jan 10 2008, 18:00:49) [GCC 4.2.1 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import cherrypy2 >>> import sys >>> sys.path ['', '/usr/lib64/python2.5/site-packages/setuptools-0.6c7-py2.5.egg', '/usr/lib64/python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg', '/ usr/lib64/python2.5/site-packages/TurboKid-1.0.4-py2.5.egg', '/usr/ lib64/python2.5/site-packages/TurboJson-1.1.2-py2.5.egg', '/usr/lib64/ python2.5/site-packages/TurboCheetah-1.0-py2.5.egg', '/usr/lib64/ python2.5/site-packages/simplejson-1.8.1-py2.5-linux-x86_64.egg', '/ usr/lib64/python2.5/site-packages/RuleDispatch-0.5a0.dev_r2306-py2.5- linux-x86_64.egg', '/usr/lib64/python2.5/site-packages/ PasteScript-1.6.2-py2.5.egg', '/usr/lib64/python2.5/site-packages/ FormEncode-1.0.1-py2.5.egg', '/usr/lib64/python2.5/site-packages/ DecoratorTools-1.7-py2.5.egg', '/usr/lib64/python2.5/site-packages/ configobj-4.5.2-py2.5.egg', '/usr/lib64/python2.5/site-packages/ CherryPy-2.3.0-py2.5.egg', '/usr/lib64/python2.5/site-packages/ kid-0.9.6-py2.5.egg', '/usr/lib64/python2.5/site-packages/ Cheetah-2.0.1-py2.5-linux-x86_64.egg', '/usr/lib64/python2.5/site- packages/PyProtocols-1.0a0dev_r2302-py2.5-linux-x86_64.egg', '/usr/ lib64/python2.5/site-packages/PasteDeploy-1.3.1-py2.5.egg', '/usr/ lib64/python2.5/site-packages/Paste-1.6-py2.5.egg', '/usr/local/lib64/ python2.5/site-packages/pagedemo1-1.0-py2.5.egg', '/usr/lib/ python25.zip', '/usr/lib64/python2.5', '/usr/lib64/python2.5/plat- linux2', '/usr/lib64/python2.5/lib-tk', '/usr/lib64/python2.5/lib- dynload', '/usr/lib64/python2.5/site-packages', '/usr/lib64/python2.5/ site-packages/Numeric', '/usr/lib64/python2.5/site-packages/PIL', '/ usr/lib64/python2.5/site-packages/gtk-2.0', '/usr/lib64/python2.5/site- packages/wx-2.8-gtk2-unicode', '/usr/local/lib64/python2.5/site- packages'] >>> Regards Luca From zookog at gmail.com Thu Jun 26 12:56:00 2008 From: zookog at gmail.com (zooko) Date: Thu, 26 Jun 2008 09:56:00 -0700 (PDT) Subject: Is there any way to find out sizeof an object References: <2338ccaf-d653-403a-9630-c06e7df98184@m73g2000hsh.googlegroups.com> Message-ID: Here are a few little tools that I developed to do this kind of thing: http://allmydata.org/trac/pyutil/browser/pyutil/pyutil/memutil.py Regards, Zooko From geoff.bache at jeppesen.com Thu Jun 26 11:52:58 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Thu, 26 Jun 2008 08:52:58 -0700 (PDT) Subject: Windows process ownership trouble References: <3fcf363f-3685-4b7b-8ba5-1ffc32e58af7@m44g2000hsc.googlegroups.com> <990516b7-f7ef-464a-97d0-fd55a0354ab4@y21g2000hsf.googlegroups.com> Message-ID: <33847c9a-a816-48a1-a8c9-4209db9bf0b5@e53g2000hsa.googlegroups.com> Tim, Unfortunately my previous message was premature, it seems your workaround doesn't work either on my system (Windows XP, Python 2.5.1) I get the following printed out Traceback (most recent call last): File "C:\TextTest\processown.py", line 12, in os.remove ("filename") WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'filename' close failed: [Errno 9] Bad file descriptor Any ideas? Geoff From Robert.Bossy at jouy.inra.fr Wed Jun 18 11:42:50 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 18 Jun 2008 17:42:50 +0200 Subject: Looking for lots of words in lots of files In-Reply-To: <48592C15.1020402@jouy.inra.fr> References: <48592C15.1020402@jouy.inra.fr> Message-ID: <48592CFA.4090701@jouy.inra.fr> I forgot to mention another way: put one thousand monkeys to work on it. ;) RB Robert Bossy wrote: > brad wrote: >> Just wondering if anyone has ever solved this efficiently... not >> looking for specific solutions tho... just ideas. >> >> I have one thousand words and one thousand files. I need to read the >> files to see if some of the words are in the files. I can stop >> reading a file once I find 10 of the words in it. It's easy for me to >> do this with a few dozen words, but a thousand words is too large for >> an RE and too inefficient to loop, etc. Any suggestions? > The quick answer would be: > grep -F -f WORDLIST FILE1 FILE2 ... FILE1000 > where WORDLIST is a file containing the thousand words, one per line. > > The more interesting answers would be to use either a suffix tree or > an Aho-Corasick graph. > > - The suffix tree is a representation of the target string (your > files) that allows to search quickly for a word. Your problem would > then be solved by 1) building a suffix tree for your files, and 2) > search for each word sequentially in the suffix tree. > > - The Aho-Corasick graph is a representation of the query word list > that allows fast scanning of the words on a target string. Your > problem would then be solved by 1) building an Aho-Corasick graph for > the list of words, and 2) scan sequentially each file. > > The preference for using either one or the other depends on some > details of your problems: the expected size of target files, the rate > of overlaps between words in your list (are there common prefixes), > will you repeat the operation with another word list or another set of > files, etc. Personally, I'd lean towards Aho-Corasick, it is a matter > of taste; the kind of applications that comes to my mind makes it more > practical. > > Btw, the `grep -F -f` combo builds an Aho-Corasick graph. Also you can > find modules for building both data structures in the python package > index. > > Cheers, > RB > -- > http://mail.python.org/mailman/listinfo/python-list > From igouy2 at yahoo.com Mon Jun 2 23:57:29 2008 From: igouy2 at yahoo.com (Isaac Gouy) Date: Mon, 2 Jun 2008 20:57:29 -0700 (PDT) Subject: libgtop gtop.proc_time(pid) examples? Message-ID: <88c63066-97f0-42c6-a7a0-c72e67f6ef9f@27g2000hsf.googlegroups.com> Please show an example of using the Python libgtop wrapper to get process time information, or say where such examples can be found. From ToshiBoy at gmail.com Sat Jun 28 00:30:25 2008 From: ToshiBoy at gmail.com (ToshiBoy) Date: Fri, 27 Jun 2008 21:30:25 -0700 (PDT) Subject: this is simple... Message-ID: I am a newbie... and the first to admit it... but this has me stuffed: I have two lists A and B that are both defined as range(1,27) I want to find the entries that are valid for A = BxB so here is my code: A = range(1,27) B = range(1,27) for b in B: if b*b in A: print b else: B.remove(b) I get, as expected 1,4,9,16,25 printed out being the only members of B where the condition is true, but when I print B I get: [1, 2, 3, 4, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25] 1 to 5 is correct, but why doesn't the remove method remove 7 and above? What am I doing wrong here? From jonrob at fedoraproject.org Sun Jun 22 13:02:20 2008 From: jonrob at fedoraproject.org (Jonathan Roberts) Date: Sun, 22 Jun 2008 18:02:20 +0100 Subject: Learning Python in a group In-Reply-To: <18c1e6480806220511s5117aef4gb4ec93bceb44a0ac@mail.gmail.com> References: <507738ef0806220343r3e9ea053neeec0baf0ccfdbe6@mail.gmail.com> <18c1e6480806220422x5d06c54byd23b249bb699691f@mail.gmail.com> <507738ef0806220452s74358615v44518469cf3b5f45@mail.gmail.com> <18c1e6480806220511s5117aef4gb4ec93bceb44a0ac@mail.gmail.com> Message-ID: <507738ef0806221002x6ebc0c90k621c891f711e44ca@mail.gmail.com> > I'm sure that many (myself included) would be happy to help out, but > due to timezone differences, working hours, etc you may only get > responses up to 24 hours (or more) later. Awesome, heh I'm sure we'll have questions for the list in good time :) > > What needs does your (non-face-to-face) group have that would not be > met by posting questions to the Python Tutor list? > > http://mail.python.org/mailman/listinfo/tutor > > Perhaps you and your co-learners can sign up to that list, and > coordinate with that list's users to use your wiki, messaging > services, etc? Actually, I hadn't seen that list before but I've just signed up for it and it sounds really interesting! The big difference really is that I'd like to try and build something a little more personal, where we have a group of people who can contact each other in real time and have regular meeting times as well as being able to find each other in between meetings too. I think this kind of consistent relationship is probably quite conducive to learning, and I think others would probably agree :) > Personally I learned Python from the Python docs (starting with the > tutorial), practice, and Google. Dive Into Python is good too. Yeah, I think we're definitely going to be making use of these resources, and then just using each other as support as we wade through the material and inevitably get stuck in places! Thanks for your help :) Best, Jon From basti.wiesner at gmx.net Mon Jun 9 16:06:23 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Mon, 09 Jun 2008 22:06:23 +0200 Subject: Web Crawler - Python or Perl? References: <484D7329.6060107@behnel.de> <1a91e16d-ccfc-487a-80fc-4d9992455eb9@p25g2000hsf.googlegroups.com> Message-ID: subeen at Montag 09 Juni 2008 20:21: > On Jun 10, 12:15 am, Stefan Behnel wrote: >> subeen wrote: >> > can use urllib2 module and/or beautiful soup for developing crawler >> >> Not if you care about a) speed and/or b) memory efficiency. >> >> http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/ >> >> Stefan > > ya, beautiful soup is slower. so it's better to use urllib2 for > fetching data and regular expressions for parsing data. BeautifulSoup is implemented on regular expressions. I doubt, that you can achieve a great performance gain by using plain regular expressions, and even if, this gain is certainly not worth the effort. Parsing markup with regular expressions is hard, and the result will most likely not be as fast and as memory-efficient as lxml.html. I personally am absolutely happy with lxml.html. It's fast, memory efficient, yet powerful and easy to use. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From hrnilesh.cyntel at gmail.com Thu Jun 19 23:19:49 2008 From: hrnilesh.cyntel at gmail.com (careerbirds) Date: Thu, 19 Jun 2008 20:19:49 -0700 (PDT) Subject: =?windows-1252?Q?20=2D6=2D2008_=96walkin=2CIT_FRESHER=2CIT_EXP_OPENINGS?= Message-ID: <27f56e0a-1c5b-4b47-9b34-bba427fc21ec@u6g2000prc.googlegroups.com> 20-6-2008 ?walkin,IT FRESHER,IT EXP OPENINGS http://www.hotjobseeker.com/ * Oracle Apps Techno Functional Consultant http://www.hotjobseeker.com/ * J2EE TECHNICAL ASSOCIATES AT PROKARMA AT HYDERABAD http://www.hotjobseeker.com/ * BEA-Weblogic-Application Server Admin http://www.hotjobseeker.com/ * Datastage Developer -ASAP Infosystems Pvt Ltd http://www.hotjobseeker.com/ * Cognos Developer -ASAP Infosystems Pvt Ltd http://www.hotjobseeker.com/ * Javascript expert $1600-2600/month, ASP.NET, work remotely at home http://www.hotjobseeker.com/ * Web Developer -Digital Pixel Inc. http://www.hotjobseeker.com/ * My SQL DBA with valid B1 visa (4+ yrs exp) http://www.hotjobseeker.com/ * AS400 Professionals http://www.hotjobseeker.com/ * Sr Cognos Professionals http://www.hotjobseeker.com/ * EAI Developer / EAI Sr.Java Developer - 3 Years to 7 Years http://www.hotjobseeker.com/ * Oracle,PL/SQL Developers/Consultant http://www.hotjobseeker.com/ * Sr. PHP Programmers - Immediate Openings http://www.hotjobseeker.com/ * Oracle Apps -Functional -SCM/HRMS/Financials-Onsite Oppurtunities http://www.hotjobseeker.com/ * Urgent Opening- Sybase Developers http://www.hotjobseeker.com/ * Sr. SEO/SEO Executive http://www.hotjobseeker.com/ * Designers Required at Harbinger Group Pune http://www.hotjobseeker.com/ * Software Developer - Java/J2EE http://www.hotjobseeker.com/ * TECH SUPPORT EXECUTIVE http://www.hotjobseeker.com/ * HR Trainee / HR Coordinator http://www.hotjobseeker.com/ * Customer Support Executive http://www.hotjobseeker.com/ * help desk executive -InKnowTech Private Limited http://www.hotjobseeker.com/ * Sales & Service Engineer (Electronic) http://www.hotjobseeker.com/ * Web Content Writer/Developer http://www.hotjobseeker.com/ * VBA Developer -US Headquartered http://www.hotjobseeker.com/ * RECRUITMENT EXECUTIVES/ RECRUITERS http://www.hotjobseeker.com/ * Application Software Engg/Php developer http://www.hotjobseeker.com/ * Tele Calling Executive -Insync http://www.hotjobseeker.com/ * Operations Support Executive -NETCRADLE INDIA http://www.hotjobseeker.com/ * (0-1 Years) Walk-In @ "AMBARA SOFTWARE" : CSR : On 25-30 May 2008, Male Candidates Only http://www.hotjobseeker.com/ * (FRESHERS & EXPERIENCED) Walk-In @ "TIMESJOBS" : ITES Job Fair : On 24, 25 May 2008 http://www.hotjobseeker.com/ * Walk-In @ "PCS TECHNOLOGY" : Server Support : Chennai : On 24, 26 May 2008 http://www.hotjobseeker.com/ * Walk-In @ "TCS" : Multiple Skills : Kochi / Pune / Hyderabad / Chennai : On 24, 25 May 2008 http://www.hotjobseeker.com/ * (FRESHERS) Walk-In @ "NATIONAL INSTRUMENTS" : On 6, 7 Jun 2008, BE / B.Tech : Last Date - 4 Jun 2008 http://www.hotjobseeker.com/ * (FRESHERS) Walk-In @ "LIONBRIDGE TECHNOLOGIES" : From Monday to Friday http://www.hotjobseeker.com/ * Artech Infosystems Walk-in for Freshers: Weekdays http://www.hotjobseeker.com/ NOTE FROM ADMIN: http://www.hotjobseeker.com/ http://finance.groups.yahoo.com/group/hotjobseeker/ $Some of these requirements may not suit your eligibility criteria , Do not delete this mail straight way. It may help few of your friends or classmates who are struggling to find more opportunities. Kindly forward this mail to them. We want you to join this revolution by helping fellow job seekers. Please forward this mail to other groups, Orkut friends,face book friends,yahoo mailing list,google talk members, College groups etc... http://finance.groups.yahoo.com/group/hotjobseeker/ All of our sections are updated daily with mails .Apply to all eligible requirements as soon as possible. This mail is neither spam nor unsolicited. You received this message because you are a member of http://www.hotjobseeker.com from the World's Biggest Job Group. please send this mail to your mailing list http://finance.groups.yahoo.com/group/hotjobseeker/ From omer at no-log.org Mon Jun 30 10:06:42 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Mon, 30 Jun 2008 16:06:42 +0200 Subject: List Performance In-Reply-To: <2eydnaP-saOZQfXVnZ2dnUVZ_qvinZ2d@comcast.com> References: <42358e0b-a351-4862-8f6a-1938eedeff6c@s21g2000prm.googlegroups.com> <2eydnaP-saOZQfXVnZ2dnUVZ_qvinZ2d@comcast.com> Message-ID: <200806301606.42499.omer@no-log.org> Le Monday 30 June 2008 15:13:30 Larry Bates, vous avez ?crit?: > Peter Otten wrote: > > Ampedesign wrote: > >> If I happen to have a list that contains over 50,000 items, will the > >> size of the list severely impact the performance of appending to the > >> list? > > > > No. > > > > $ python -m timeit -n20000 -s"items = []" "items.append(42)" > > 20000 loops, best of 3: 0.554 usec per loop > > $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" > > 20000 loops, best of 3: 0.529 usec per loop > > > > http://wiki.python.org/moin/TimeComplexity > > > > Peter > > Peter, > > So its actually faster to append to a long list than an empty one? That > certainly would not have been intuitively obvious now would it? > That test only demonstrates that it's faster to append to a 1 million items list than an empty one (and this on a particular platform with a particular python version). Different sizes may give different result. I guess this is because of some internal optimisations (items are probably allocated by chunks, so sometimes append() involves a realloc, sometimes not). So the only thing you should remember is that list.append() has a complexity of O(1), and thus should be considered a constant time operation for any length. Just be aware of the note: [1] = These operations rely on the "Amortized" part of "Amortized Worst Case". Individual actions may take surprisingly long, depending on the history of the container. Also note that 50000 items is a lot for a human being, not for a modern computer. -- C?dric Lucantis From geonomica at gmail.com Mon Jun 30 12:13:42 2008 From: geonomica at gmail.com (gianluca) Date: Mon, 30 Jun 2008 09:13:42 -0700 (PDT) Subject: ctypes - swig - pointer Message-ID: I've a problem with dll function colled with python/ctypes. My functions (C) requred a typedef int "value_type" in tree different way: same as value_type; - mydll.foo1(value_type) same as *value_type; - mydll.foo2(*value_type) same as **value_type; - mydll.foo3(**value_type) How can pass it in python. If i do that: rules=POINTER(value_type) opr=rsl.StrengthOfRules(rules,10) R=POINTER(rules) I've this exception: Traceback (most recent call last): File "C:\temp\cRSL.py", line 49, in opr=rsl.StrengthOfRules(rules,10) #/* Creates a table of rules strengths. */ ArgumentError: argument 1: : Don't know how to convert parameter 1 I've tried with swig (cpointer.i) olso but the library don't work correctly and rules look empty. I need help. Could anybody give mi it? gima From grante at visi.com Sat Jun 14 17:47:58 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 14 Jun 2008 16:47:58 -0500 Subject: Making wxPython a standard module? References: <6bidd7F3bg8usU1@mid.uni-berlin.de> <87fxrfx0h0.fsf@physik.rwth-aachen.de> Message-ID: On 2008-06-14, Paul McNett

wrote: > Grant Edwards wrote: >> On 2008-06-14, Torsten Bronger wrote: >> >>>> I've never used any of the designers, but I agree 100% that >>>> wxPython code is nasty ugly. wxPython has a very un-Pythonic >>>> API that's is, IMO, difficult to use. >>> I know that such requests may start a never-ending thread but >>> I'd really like to know what you mean with this. >> >> [...] >> >> Well, if we want this thread to be never ending, I'd better put >> a little dramatic hyperbole into my answer, so here goes... ;) > > (blatant self-promotion warning: I'm one of the founders of Dabo, and it > sounds like you may like to take a look at it, given your comments below) Yes! Dabo was the other one I was trying to remember. The last time I looked Dabo appeared to be catching on better than wax was. > But in the end, wxPython is the best GUI toolkit for Python, > by far, I've been using it for 9 years. :) I can pretty much always make it work, and the result looks native to Windows users and "native enough" to Linux users... -- Grant Edwards grante Yow! I'm rated PG-34!! at visi.com From tdahsu at gmail.com Fri Jun 6 14:22:07 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Fri, 6 Jun 2008 11:22:07 -0700 (PDT) Subject: File-writing not working in Windows? References: <80a7b951-591b-41a2-b76c-f97d75db0dad@25g2000hsx.googlegroups.com> <08442be2-13c0-44fc-add4-4907c1202f96@r66g2000hsg.googlegroups.com> Message-ID: <300fece5-da15-4323-9b3a-f49b90d9c74b@34g2000hsh.googlegroups.com> On Jun 6, 11:35?am, jay graves wrote: > On Jun 6, 10:18 am, tda... at gmail.com wrote: > > > > This code works PERFECTLY in Linux. ?Where I have a match in the file > > I'm processing, it gets cut out from the start of the match until the > > end of the match, and written to the temporary file in tempdir. > > It does not work in Windows. ?It does not create or write to the > > temporary file AT ALL. ?It creates the tempdir directory with no > > problem. > > In general, I don't use string concatenation when building paths. > Especially on scripts that are meant to run on multiple platforms. > > > Here's the kicker: it works perfectly in Windows if Windows is running > > in VMware on a Linux host! ?(I assume that that's because VMware is > > passing some call to the host.) > > probably a red herring. > > > Can anyone tell me what it is that I'm missing which would prevent the > > file from being created on Windows natively? > > Get rid of the 'posix' check and use os.path.join to create > 'tempfileName' and see if it works. > > HTH. > ... > Jay Graves Jay, Thank you for your answer. I have researched os.path.join. I have changed the code to read as follows: if (self.checkbox25.GetValue() == False): initialFileName = self.Info[x][0] + "_tmp_" + fileName + ".txt" tempfileName = os.path.join("proctemp", initialFileName) else: initialFileName = self.Info[x][0] + "_xyz.txt" tempfileName = os.path.join("proctemp", initialFileName) this still works in Linux; it does not work in Windows. I am thinking that the "g.open(tempFileName, 'a')" command is the issue. Is there anything different about opening a file in Windows? Does Windows understand "append", or would I have to do control checks for seeing if the file is created and then appending? From mensanator at aol.com Fri Jun 6 13:50:25 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 6 Jun 2008 10:50:25 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> Message-ID: On Jun 6, 1:44?am, "Terry Reedy" wrote: > "Mensanator" wrote in message > > news:bbd90051-36be-4378-9a27-2a47a5471d12 at a1g2000hsb.googlegroups.com... > | On Jun 5, 10:42?pm, John Salerno wrote: > | > Is it possible to write a list comprehension for this so as to produce > a > | > list of two-item tuples? > | > > | > base_scores = range(8, 19) > | > score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] > | > print zip(base_scores, score_costs) > | > > | > I can't think of how the structure of the list comprehension would work > | > in this case, because it seems to require iteration over two separate > | > sequences to produce each item in the tuple. > > Which is exactly the purpose of zip, or its specialization enumerate! Aren't you overlooking the fact that zip() truncates the output to the shorter length iterable? And since the OP foolishly hardcoded his range bounds, zip(base_scores,score_cost) will silently return the wrong answer if the base_count list grows. Surely enumerate() wasn't added to Python with no intention of ever being used. > > | > zip seems to work fine anyway, but my immediate instinct was to try a > | > list comprehension (until I couldn't figure out how!). And I wasn't > sure > | > if list comps were capable of doing everything a zip could do. > | > | base_scores = range(8, 19) > | score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] > | print zip(base_scores, score_costs) > | > | s = [(i+8,j) for i,j in enumerate( [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3])] > | print s > | > | ##>>> > | ##[(8, 0), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, > | 2), (16, 2), (17, 3), (18, 3)] > | ##[(8, 0), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, > | 2), (16, 2), (17, 3), (18, 3)] > | ##>>> > > Of course, enumerate(iterable) is just a facade over zip(itertools.count(), > iterable) But if all I'm using itertools for is the count() function, why would I go to the trouble of importing it when I can simply use enumerate()? Is it a couple orders of magnitude faster? From frank at chagford.com Mon Jun 9 10:21:28 2008 From: frank at chagford.com (Frank Millman) Date: Mon, 9 Jun 2008 07:21:28 -0700 (PDT) Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> <41de7980-749a-4f46-add1-12010b6e95d9@b1g2000hsg.googlegroups.com> Message-ID: <8f9b0c13-9b90-4352-acbc-ec15a9e2f8bc@f63g2000hsf.googlegroups.com> On Jun 9, 4:06?pm, Frank Millman wrote: > > Thanks for the reply, Mel. I don't quite understand what you mean. As so often happens, after I sent my reply I re-read your post and I think I understand what you are getting at. One problem with my approach is that I am truncating the result down to the desired scale factor every time I create a new instance. This could result in a loss of precision if I chain a series of instances together in a calculation. I think that what you are suggesting avoids this problem. I will read your message again carefully. I think it will lead to a rethink of my approach. Thanks again Frank P.S. Despite my earlier reply to Paul, I have not abandoned the idea of using my Number class as opposed to the standard Decimal class. I did a simple test of creating two instances and adding them together, using both methods, and timing them. Decimal came out 6 times slower than Number. Is that important? Don't know, but it might be. From 42flicks at gmail.com Tue Jun 10 22:14:25 2008 From: 42flicks at gmail.com (Mike) Date: Wed, 11 Jun 2008 14:14:25 +1200 Subject: Dynamic HTML from Python Script In-Reply-To: References: <484f151c$0$5009$607ed4bc@cv.net> Message-ID: <2b54d4370806101914i4af29d96mcb0807e8342cd892@mail.gmail.com> Web.py also springs to mind, I'd say it's worth looking at. Well, in that case you could simply append the new output to a static file > every 10 seconds, or whenever there is new output. That way, you just need > to refresh the static file in your browser to see updates... Given what I > understand of your situation, that's how I'd do it. >From your requirements this sounds like the best solution. At least while you investigate further. -------------- next part -------------- An HTML attachment was scrubbed... URL: From qgallet at gmail.com Thu Jun 5 10:02:16 2008 From: qgallet at gmail.com (Quentin Gallet-Gilles) Date: Thu, 5 Jun 2008 16:02:16 +0200 Subject: No subject In-Reply-To: <000c01c8c712$347dd660$1300a8c0@Home> References: <000c01c8c712$347dd660$1300a8c0@Home> Message-ID: <8b943f2b0806050702n6bd5480dj7a1a9c5a9993a678@mail.gmail.com> I don't want to spoil the fun, so I'll just say that "range" is the key here. Quentin On Thu, Jun 5, 2008 at 3:43 PM, garywood wrote: > Hi there. So I have a challenge in the Python book I am using (python > programming for the absolute beginner) that tells me to improve an ask_number() > function, so that it can be called with a step value, and I havn't > been able to find out yet what's meant by a step value, but i'll keep > looking of course. I'd just be grateful if someone could illimunate > this for me. > > > def ask_number(question, low, high): > """Ask for a number within a range.""" > response = None > while response not in range(low, high): > response = int(raw_input(question)) > return response > > Thanks in advance. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eliben at gmail.com Mon Jun 23 00:28:26 2008 From: eliben at gmail.com (eliben) Date: Sun, 22 Jun 2008 21:28:26 -0700 (PDT) Subject: Pattern Matching Over Python Lists References: <21a9c996-75ff-4f7c-b7e9-c94247f65674@c58g2000hsc.googlegroups.com> <87ej6w6ql6.fsf@internal.daycos.com> <61ea5c70-4352-4d2f-a0ef-62eb76ba933a@m36g2000hse.googlegroups.com> <6e31e7ef-3eea-4edc-88bc-471e78dbb46c@i76g2000hsf.googlegroups.com> <1379d69a-af3f-4e06-8bd4-b85e0213399a@g16g2000pri.googlegroups.com> <111101c1-d096-481a-94a5-5af1844b8e55@t54g2000hsg.googlegroups.com> Message-ID: <34de545e-05a1-4a57-8f73-dc27a813c3e7@m44g2000hsc.googlegroups.com> > Fair enough. To help you understand the method I used, I'll give you > this hint. It's true that regex on works on strings. However, is there > any way to convert arbitrarily complex data structures to string > representations? You don't need to be an experienced Python user to > answer to this ;) As Paddy noted before, your solution has a problem, Regexes can't match nested parenthesis, so I think your method will have a problem with nested lists, unless your actual inputs are much simpler than the general case. Eli From kib2 at free.fr Mon Jun 23 13:35:28 2008 From: kib2 at free.fr (kib2) Date: Mon, 23 Jun 2008 19:35:28 +0200 Subject: Going from Tkinter to pyQT In-Reply-To: References: Message-ID: <485fdf24$0$1305$426a74cc@news.free.fr> Alex Bryan a ?crit : > I had a guy on this mailing list tell me that pyQT is much better than > Tkinter, and after looking into it a bit I think he is right. However, I > can't find much on it. I want to know if there are any good books or > online tutorials that would be helpful. I doubt there is one, but if > there is one on going from Tkinter to pyQT, that would be amazing. Well > if any of you guys have any tips or suggestions on any of this I would > appreciate it. Hi Alex, Check Mark Summerfield's book on PyQt4 : http://www.qtrac.eu/pyqtbook.html Other links : http://www.rkblog.rk.edu.pl/w/p/python/ From danb_83 at yahoo.com Thu Jun 19 23:26:17 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Thu, 19 Jun 2008 20:26:17 -0700 (PDT) Subject: At long last... References: Message-ID: On Jun 19, 9:24?pm, Carl Banks wrote: > On Jun 19, 10:17 pm, Terry Reedy wrote: > > > Carl Banks wrote: > > > Tuples will have an index method in Python 2.6. > > > > I promise I won't indiscriminately use tuples for homogenous data. > > > Honest. ?Scout's honor. ?Cross my heart. > > > Use them as you want. ?This change came about because .index was > > included in the 3.0 Sequence ABC (abstract base class) and tuple was > > included as a sequence, so .... something had to give. ?The result was > > tuple getting the full suite of immutable sequence methods. ?And then > > there was no good reason to not backport ;-). > > The last time I needed index on a tuple was in fact for partially non- > homogenous data. ?I forget why, but I needed to treat arguments after > a certain value different from the front arguments. ?So I wanted to do > something like: > > def something(*args): > ? ? firstspecial = args.index(0) > > 'Cept I couldn't. Why didn't you just use a list inside the tuple? From gagsl-py2 at yahoo.com.ar Tue Jun 3 21:46:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 03 Jun 2008 22:46:06 -0300 Subject: printf in python References: <261cbf38-6f0d-4525-9b4a-11ddbb910b66@d45g2000hsc.googlegroups.com> <183dfd01-68a5-4ae8-a04a-c3689d77003e@m3g2000hsc.googlegroups.com> <0f7b7836-ed92-4a02-9eba-4ff7fe4a94cd@m36g2000hse.googlegroups.com> Message-ID: En Tue, 03 Jun 2008 10:28:57 -0300, gianluca escribi?: >> > > On Mon, 2 Jun 2008 00:32:33 -0700 (PDT), gianluca >> >> > > declaimed the following in comp.lang.python: >> >> > > > Hy, I've a problem with may python library generated with swig >> from C >> > > > code. I works and I can access all function but a sim?ple >> function >> > > > that print a string don't work's. >> > > > The function is like this: >> > > > int PrintTEST() >> > > > { >> > > > printf("TEST "); >> > > > return 1; >> > > > } > > I know!! I'm bore!! But I need help indeed!! > I'm looking inside lib_wrap.c generated by swig. In the wrap function > there is no printf function. If is this the problem how can I do to > resolve it? Generated swig code is... uhm, ugly at least, and rather undebuggable. I'd try to avoid it. Another alternative is Cython: I've not actually used it myself, but I've seen good reports from it. If your library is written in C (not C++), you may use directly ctypes from inside Python. -- Gabriel Genellina From fc14301589 at icqmail.com Sun Jun 15 05:45:12 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Sun, 15 Jun 2008 17:45:12 +0800 Subject: Hard to understand 'eval' References: <485381e7_2@news.tm.net.my> Message-ID: <4854e4a7_2@news.tm.net.my> On 06:34, domenica 15 giugno 2008 Dennis Lee Bieber wrote: >> for nn in stn_items: > I already see a syntax error when viewing that in Agent... A missing > indent level under the "for" The program don't complain wrong indentation, I mostly sure a wrong copy-paste error. Error doesn't come up there. > . You also don't need the continue if you change the second if into elif. > My mistake, I thought that was improving the loop. is it an if....elif....elif probing only the first matching case and drop the remaining checks? > And what type of structure is "cfl"? You got close, that's a dictionary of dictionaries and I'm trying to updating it. > wonder what this mysterious _append() function is supposed to be doing; Append() is a conventional name regarding a file logging. There would be an option to set a quota of bytes size. > Huh... I presume you mean to convert from a text decimal it isn't so, the function look at the string to see if ending by K or M, which means Kbytes or Mbytes. It'll return the decimal conversion. If the value is set as boolean value, then it will do appending to the log when it True or stop appending when there's a quota. def _append(c, v): RE_BYTE= re.compile(r'^[\d]+(k|m)?$',re.I) # any number of digit followed by 0 or 1 (k or m), case insensitive chkbool(v) if isinstance(v,bool): c['append']= v return c if RE_BYTE.match(value): k= 1024; M= k * k; v= int(value[:-1]) if value[-1:] == 'k': v= v * k if value[-1:] == 'm': v= v * m c['append']= v return c All the code could be download at my web site ;) But this here it's a bit new concept. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From alexnbryan at gmail.com Sun Jun 29 16:04:04 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sun, 29 Jun 2008 13:04:04 -0700 (PDT) Subject: using urllib2 In-Reply-To: <18184170.post@talk.nabble.com> References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> <25d97d35-6d28-43ef-9e54-d8ae7a03bc8f@b1g2000hsg.googlegroups.com> <27fbd1c7-6735-4fb0-9758-726b2fd8b86e@m3g2000hsc.googlegroups.com> <18184087.post@talk.nabble.com> <18184170.post@talk.nabble.com> Message-ID: <18184788.post@talk.nabble.com> Okay, now I ran in it the shell, and this is what happened: >>> for tabs in soup.findAll('table', {'class': 'luna-Ent'}): ... tabs.findAll('td')[-1].contents[-1].string ... u' ' u' ' u' ' u' ' u' ' u'not complex or compound; single. ' u' ' u' ' u' ' u' ' u' ' u'inconsequential or rudimentary. ' u'unlearned; ignorant. ' u' ' u'unsophisticated; naive; credulous. ' u' ' u'not mixed. ' u' ' u'not mixed. ' u' ' u' ' u' ' u' ' u'). ' u' ' u'(of a lens) having two optical surfaces only. ' u'an ignorant, foolish, or gullible person. ' u'something simple, unmixed, or uncompounded. ' u'cords for controlling the warp threads in forming the shed on draw-looms. ' u'a person of humble origins; commoner. ' u' ' >>> However, the definitions are there. I printed the actual soup and they were there in the format they always were in. So what is the deal!?! >>> soup.findAll('table', {'class': 'luna-Ent'}) [
1.easy to understand, deal with, use, etc.: a simple matter; simple tools.
See there is the first one in the shell, I mean it is there, but the for loop can't find it. I am wondering, because the above soup.findAll('table'..etc. makes it a list. Do you think that has anything to do with the problem? Alexnb wrote: > > Actually after looking at this, the code is preactically the same, except > the definitions. So what COULD be going wrong here? > > Also, I ran the program and decided to print the whole list of definitions > straight off BeautifulSoup, and I got an interesting result: > > What word would you like to define: simple > [u' ', u' ', u' ', u' ', u' ', u'not complex or compound; single. > > those are the first 5 definitions. and later on, it does the same thing. > it only sees a space, any ideas? > > Alexnb wrote: >> >> Okay, so i've hit a new snag and can't seem to figure out what is wrong. >> What is happening is the first 4 definitions of the word "simple" don't >> show up. The html is basicly the same, with the exception of noun turning >> into adj. Ill paste the html of the word cheese, and then the one for >> simple, and the code I am using to do the work. >> >> line of html for the 2nd def of cheese: >> >>
2.> valign="top">a definite mass of this substance, often in the shape of a >> wheel or cylinder.
>> >> line of html for the 2nd def of simple: >> >>
2.> valign="top">not elaborate or artificial; plain: a simple style. >>
>> >> code: >> >> import urllib >> from BeautifulSoup import BeautifulSoup >> >> >> def get_defs(term): >> soup = >> BeautifulSoup(urllib.urlopen('http://dictionary.reference.com/search?q=%s' >> % term)) >> >> for tabs in soup.findAll('table', {'class': 'luna-Ent'}): >> yield tabs.findAll('td')[-1].contents[-1].string >> >> word = raw_input("What word would you like to define: ") >> >> mainList = list(get_defs(word)) >> >> n=0 >> q = 1 >> >> for x in mainList: >> print str(q)+". "+str(mainList[n]) >> q=q+1 >> n=n+1 >> >> Now, I don't think it is the italics because one of the definitions that >> worked had them in it in the same format. Any Ideas??! >> >> >> Jeff McNeil-2 wrote: >>> >>> On Jun 29, 12:50?pm, Alexnb wrote: >>>> No I figured it out. I guess I never knew that you aren't supposed to >>>> split a >>>> url like "http://www.goo\ >>>> gle.com" But I did and it gave me all those errors. Anyway, I had a >>>> question. On the original code you had this for loop: >>>> >>>> for tabs in soup.findAll('table', {'class': 'luna-Ent'}): >>>> ? ? ? ? yield tabs.findAll('td')[-1].contents[-1].string >>>> >>>> I hate to be a pain, but I was looking at the BeautifulSoup docs, and >>>> found >>>> the findAll thing. But I want to know why you put "for tabs," also why >>>> you >>>> need the "'table', {'class': 'luna-Ent'}):" Like why the curly braces >>>> and >>>> whatnot? >>>> >>>> Jeff McNeil-2 wrote: >>>> >>>> > On Jun 27, 10:26?pm, Alexnb wrote: >>>> >> Okay, so I copied your code(and just so you know I am on a mac right >>>> now >>>> >> and >>>> >> i am using pydev in eclipse), and I got these errors, any idea what >>>> is >>>> >> up? >>>> >>>> >> Traceback (most recent call last): >>>> >> ? File >>>> >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", >>>> >> line 14, in >>>> >> ? ? print list(get_defs("cheese")) >>>> >> ? File >>>> >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", >>>> >> line 9, in get_defs >>>> >> ? ? dictionary.reference.com/search?q=%s' % term)) >>>> >> ? File >>>> >> >>>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >>>> lib.py", >>>> >> line 82, in urlopen >>>> >> ? ? return opener.open(url) >>>> >> ? File >>>> >> >>>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >>>> lib.py", >>>> >> line 190, in open >>>> >> ? ? return getattr(self, name)(url) >>>> >> ? File >>>> >> >>>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >>>> lib.py", >>>> >> line 325, in open_http >>>> >> ? ? h.endheaders() >>>> >> ? File >>>> >> >>>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >>>> plib.py", >>>> >> line 856, in endheaders >>>> >> ? ? self._send_output() >>>> >> ? File >>>> >> >>>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >>>> plib.py", >>>> >> line 728, in _send_output >>>> >> ? ? self.send(msg) >>>> >> ? File >>>> >> >>>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >>>> plib.py", >>>> >> line 695, in send >>>> >> ? ? self.connect() >>>> >> ? File >>>> >> >>>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >>>> plib.py", >>>> >> line 663, in connect >>>> >> ? ? socket.SOCK_STREAM): >>>> >> IOError: [Errno socket error] (8, 'nodename nor servname provided, >>>> or not >>>> >> known') >>>> >>>> >> Sorry if it is hard to read. >>>> >>>> >> Jeff McNeil-2 wrote: >>>> >>>> >> > Well, what about pulling that data out using Beautiful soup? If >>>> you >>>> >> > know the table name and whatnot, try something like this: >>>> >>>> >> > #!/usr/bin/python >>>> >>>> >> > import urllib >>>> >> > from BeautifulSoup import BeautifulSoup >>>> >>>> >> > def get_defs(term): >>>> >> > ? ? soup = BeautifulSoup(urllib.urlopen('http:// >>>> >> > dictionary.reference.com/search?q=%s' % term)) >>>> >>>> >> > ? ? for tabs in soup.findAll('table', {'class': 'luna-Ent'}): >>>> >> > ? ? ? ? yield tabs.findAll('td')[-1].contents[-1].string >>>> >>>> >> > print list(get_defs("frog")) >>>> >>>> >> > jeff at martian:~$ python test.py >>>> >> > [u'any tailless, stout-bodied amphibian of the order Anura, >>>> including >>>> >> > the smooth, moist-skinned frog species that live in a damp or >>>> >> > semiaquatic habitat and the warty, drier-skinned toad species that >>>> are >>>> >> > mostly terrestrial as adults. ', u' ', u' ', u'a French person or >>>> a >>>> >> > person of French descent. ', u'a small holder made of heavy >>>> material, >>>> >> > placed in a bowl or vase to hold flower stems in position. ', u'a >>>> >> > recessed panel on one of the larger faces of a brick or the like. >>>> ', >>>> >> > u' ', u'to hunt and catch frogs. ', u'French or Frenchlike. ', >>>> u'an >>>> >> > ornamental fastening for the front of a coat, consisting of a >>>> button >>>> >> > and a loop through which it passes. ', u'a sheath suspended from a >>>> >> > belt and supporting a scabbard. ', u'a device at the intersection >>>> of >>>> >> > two tracks to permit the wheels and flanges on one track to cross >>>> or >>>> >> > branch from the other. ', u'a triangular mass of elastic, horny >>>> >> > substance in the middle of the sole of the foot of a horse or >>>> related >>>> >> > animal. '] >>>> >>>> >> > HTH, >>>> >>>> >> > Jeff >>>> >>>> >> > On Jun 27, 7:28?pm, Alexnb wrote: >>>> >> >> I have read that multiple times. It is hard to understand but it >>>> did >>>> >> help >>>> >> >> a >>>> >> >> little. But I found a bit of a work-around for now which is not >>>> what I >>>> >> >> ultimately want. However, even when I can get to the page I want >>>> lets >>>> >> >> say, >>>> >> >> "Http://dictionary.reference.com/browse/cheese", I look on >>>> firebug, >>>> >> and >>>> >> >> extension and see the definition in javascript, >>>> >>>> >> >> >>>> >> >> >>>> >> >> >>>> >> >> >>>> >> >> >>>> >>>> >> >> Jeff McNeil-2 wrote: >>>> >>>> >> >> > the problem being that if I use code like this to get the html >>>> of >>>> >> that >>>> >>>> >> >> > page in python: >>>> >>>> >> >> > response = urllib2.urlopen("the webiste....") >>>> >> >> > html = response.read() >>>> >> >> > print html >>>> >>>> >> >> > then, I get a bunch of stuff, but it doesn't show me the code >>>> with >>>> >> the >>>> >> >> > table that the definition is in. So I am asking how do I access >>>> this >>>> >> >> > javascript. Also, if someone could point me to a better >>>> reference >>>> >> than >>>> >> >> the >>>> >> >> > last one, because that really doesn't tell me much, whether it >>>> be a >>>> >> >> book >>>> >> >> > or anything. >>>> >>>> >> >> > I stumbled across this a while back: >>>> >> >> >http://www.voidspace.org.uk/python/articles/urllib2.shtml. >>>> >> >> > It covers quite a bit. The urllib2 module is pretty >>>> straightforward >>>> >> >> > once you've used it a few times. ?Some of the class naming and >>>> >> whatnot >>>> >> >> > takes a bit of getting used to (I found that to be the most >>>> >> confusing >>>> >> >> > bit). >>>> >>>> >> >> > On Jun 27, 1:41 pm, Alexnb wrote: >>>> >> >> >> Okay, I tried to follow that, and it is kinda hard. But since >>>> you >>>> >> >> >> obviously >>>> >> >> >> know what you are doing, where did you learn this? Or where >>>> can I >>>> >> >> learn >>>> >> >> >> this? >>>> >>>> >> >> >> Maric Michaud wrote: >>>> >>>> >> >> >> > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit : >>>> >> >> >> >> I have never used the urllib or the urllib2. I really have >>>> >> looked >>>> >> >> >> online >>>> >> >> >> >> for help on this issue, and mailing lists, but I can't >>>> figure >>>> >> out >>>> >> >> my >>>> >> >> >> >> problem because people haven't been helping me, which is >>>> why I >>>> >> am >>>> >> >> >> here! >>>> >> >> >> >> :]. >>>> >> >> >> >> Okay, so basically I want to be able to submit a word to >>>> >> >> >> dictionary.com >>>> >> >> >> >> and >>>> >> >> >> >> then get the definitions. However, to start off learning >>>> >> urllib2, I >>>> >> >> >> just >>>> >> >> >> >> want to do a simple google search. Before you get mad, what >>>> I >>>> >> have >>>> >> >> >> found >>>> >> >> >> >> on >>>> >> >> >> >> urllib2 hasn't helped me. Anyway, How would you go about >>>> doing >>>> >> >> this. >>>> >> >> >> No, >>>> >> >> >> >> I >>>> >> >> >> >> did not post the html, but I mean if you want, right click >>>> on >>>> >> your >>>> >> >> >> >> browser >>>> >> >> >> >> and hit view source of the google homepage. Basically what >>>> I >>>> >> want >>>> >> >> to >>>> >> >> >> know >>>> >> >> >> >> is how to submit the values(the search term) and then >>>> search for >>>> >> >> that >>>> >> >> >> >> value. Heres what I know: >>>> >>>> >> >> >> >> import urllib2 >>>> >> >> >> >> response = urllib2.urlopen("http://www.google.com/") >>>> >> >> >> >> html = response.read() >>>> >> >> >> >> print html >>>> >>>> >> >> >> >> Now I know that all this does is print the source, but >>>> thats >>>> >> about >>>> >> >> all >>>> >> >> >> I >>>> >> >> >> >> know. I know it may be a lot to ask to have someone >>>> show/help >>>> >> me, >>>> >> >> but >>>> >> >> >> I >>>> >> >> >> >> really would appreciate it. >>>> >>>> >> >> >> > This example is for google, of course using pygoogle is >>>> easier in >>>> >> >> this >>>> >> >> >> > case, >>>> >> >> >> > but this is a valid example for the general case : >>>> >>>> >> >> >> >>>>[207]: import urllib, urllib2 >>>> >>>> >> >> >> > You need to trick the server with an imaginary User-Agent. >>>> >>>> >> >> >> >>>>[208]: def google_search(terms) : >>>> >> >> >> > ? ? return >>>> >> >> >> >>>> urllib2.urlopen(urllib2.Request("http://www.google.com/search?" >>>> >> >> >> > + >>>> >> >> >> > urllib.urlencode({'hl':'fr', 'q':terms}), >>>> >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? >>>> >> >> ?headers={'User-Agent':'MyNav >>>> >> >> >> > 1.0 >>>> >> >> >> > (compatible; MSIE 6.0; Linux'}) >>>> >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ).read() >>>> >> >> >> > ? ?.....: >>>> >>>> >> >> >> >>>>[212]: res = google_search("python & co") >>>> >>>> >> >> >> > Now you got the whole html response, you'll have to parse it >>>> to >>>> >> >> recover >>>> >> >> >> > datas, >>>> >> >> >> > a quick & dirty try on google response page : >>>> >>>> >> >> >> >>>>[213]: import re >>>> >>>> >> >> >> >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

>>> >> >> >> class=r>.*?

', >>>> >> >> >> > res) ] >>>> >> >> >> > ...[229]: >>>> >> >> >> > ['Python Gallery', >>>> >> >> >> > ?'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie >>>> des >>>> >> Monty >>>> >> >> >> ...', >>>> >> >> >> > ?'Re: os x, panther, python & co: msg#00041', >>>> >> >> >> > ?'Re: os x, panther, python & co: msg#00040', >>>> >> >> >> > ?'Cardiff Web Site Design, Professional web site design >>>> services >>>> >> >> ...', >>>> >> >> >> > ?'Python Properties', >>>> >> >> >> > ?'Frees < Programs < Python < Bin-Co', >>>> >> >> >> > ?'Torb: an interface between Tcl and CORBA', >>>> >> >> >> > ?'Royal Python Morphs', >>>> >> >> >> > ?'Python & Co'] >>>> >>>> >> >> >> > -- >>>> >> >> >> > _____________ >>>> >>>> >> >> >> > Maric Michaud >>>> >> >> >> > -- >>>> >> >> >> >http://mail.python.org/mailman/listinfo/python-list >>>> >>>> >> >> >> -- >>>> >> >> >> View this message in >>>> >>>> >> context:http://www.nabble.com/using-urllib2-tp18150669p18160312.html >>>> >> >> >> Sent from the Python - python-list mailing list archive at >>>> >> Nabble.com. >>>> >>>> >> >> > -- >>>> >> >> >http://mail.python.org/mailman/listinfo/python-list >>>> >>>> >> >> -- >>>> >> >> View this message in >>>> >> >> >>>> context:http://www.nabble.com/using-urllib2-tp18150669p18165634.html >>>> >> >> Sent from the Python - python-list mailing list archive at >>>> Nabble.com. >>>> >>>> >> > -- >>>> >> >http://mail.python.org/mailman/listinfo/python-list >>>> >>>> >> -- >>>> >> View this message in... >>>> >>>> read more ? >>> >>> The definitions were embedded in tables with a 'luna-Ent' class. I >>> pulled all of the tables with that class out, and then returned the >>> string value of td containing the actual definition. The findAll >>> method takes an optional dictionary, thus the {}. >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >> >> > > -- View this message in context: http://www.nabble.com/using-urllib2-tp18150669p18184788.html Sent from the Python - python-list mailing list archive at Nabble.com. From mwilson at the-wire.com Sat Jun 28 00:48:47 2008 From: mwilson at the-wire.com (Mel) Date: Sat, 28 Jun 2008 00:48:47 -0400 Subject: this is simple... References: Message-ID: ToshiBoy wrote: > I have two lists A and B that are both defined as range(1,27) I want > to find the entries that are valid for A = BxB [ ... ] > I get, as expected 1,4,9,16,25 printed out being the only members of B > where the condition is true, but when I print B I get: > > [1, 2, 3, 4, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25] > > 1 to 5 is correct, but why doesn't the remove method remove 7 and > above? What am I doing wrong here? Try this: A = range(1,27) B = range(1,27) C = [] for b in B: print "Trying", b if b*b in A: print b C.append (b) else: print "Removing", b B.remove(b) print 'B', B print 'C', C The essential problem is that your `B.remove`s are pulling the rug out from under your `for b in B:`. There are ways to mess with B while you iterate. Running though B backwards will do: `for b in B[::-1]:`, or iterating over a copy of B: `for b in B[:]:` or `for b in list(B):`. Leaving B alone and building up the desired items in C is probably simplest. Mel. From dlists.cad at gmail.com Wed Jun 18 15:41:44 2008 From: dlists.cad at gmail.com (dlists.cad at gmail.com) Date: Wed, 18 Jun 2008 12:41:44 -0700 (PDT) Subject: Function argument conformity check References: <0efa09ce-dbf9-4699-b87c-34c2c3b271f0@34g2000hsh.googlegroups.com> Message-ID: <9577cf2e-4440-4d97-b8e8-1dbc00bfca68@34g2000hsh.googlegroups.com> On Jun 18, 3:13 pm, C?dric Lucantis wrote: > Hi, > > Le Wednesday 18 June 2008 20:19:12 dlists.... at gmail.com, vous avez ?crit : > > > Hi. I am looking for a way to check if some given set of (*args, > > **kwds) conforms to the argument specification of a given function, > > without calling that function. > > > For example, given the function foo: > > def foo(a, b, c): pass > > > and some tuple args and some dict kwds, is there a way to tell if i > > _could_ call foo(*args, **kwds) without getting an exception for those > > arguments? I am hoping there is a way to do this without actually > > writing out the argument logic python uses. > > Each function object is associated to a code object which you can get with > foo.func_code. Two of this object's attributes will help you: co_argcount and > co_varnames. The first is the number of arguments of the function, and the > second a list of all the local variables names, including the arguments > (which are always the first items of the list). When some arguments have > default values, they are stored in foo.func_defaults (and these arguments are > always after non-default args in the co_argnames list). > > Finally, it seems that some flags are set in code.co_flags if the function > accepts varargs like *args, **kwargs, but I don't know where these are > defined. > > Note that I never found any doc about that and merely guessed it by playing > with func objects, so consider all this possibly wrong or subject to change. > > -- > C?dric Lucantis I am aware of these attributes, although you can get them all in a more organized form using the getfullargspec function in the inspect module from the standard library. The problem is that using these attributes, I would essentially have to re-write the logic python uses when calling a function with a given set of arguments. I was hoping there is a way to get at that logic without rewriting it. From sjmachin at lexicon.net Fri Jun 13 07:23:38 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 13 Jun 2008 04:23:38 -0700 (PDT) Subject: using re module to find References: <5aeb32bd-923f-4b98-952b-06097ac8479d@v1g2000pra.googlegroups.com> Message-ID: <79634319-52e5-48ba-a379-aa24049842c9@2g2000hsn.googlegroups.com> On Jun 13, 6:23 pm, anton wrote: > John Machin lexicon.net> writes: > > > > > On Jun 12, 7:11 pm, anton wrote: > > > Hi, > > > > I want to replace all occourences of " by \" in a string. > > > > But I want to leave all occourences of \" as they are. > > > > The following should happen: > > > > this I want " while I dont want this \" > > ... cut text off > > > > > What you want is: > > > >> import re > > >> text = r'frob this " avoid this \", OK?' > > >>> text > > 'frob this " avoid this \\", OK?' > > >> re.sub(r'(? > frob this \\" avoid this \\", OK?' > > > HTH, > > John > > -- > >http://mail.python.org/mailman/listinfo/python-list > > First.. thanks John. > > The whole problem is discussed in > > http://docs.python.org/dev/howto/regex.html#the-backslash-plague > > in the section "The Backslash Plague" > > Unfortunately this is *NOT* mentioned in the standard > python documentation of the re module. Yes, and there's more to driving a car in heavy traffic than you will find in the manufacturer's manual. > > Another thing which will always remain strange to me, is that > even if in the python doc of raw string: > > http://docs.python.org/ref/strings.html > > its written: > "Specifically, a raw string cannot end in a single backslash" > > s=r"\\" # works fine > s=r"\" # works not (as stated) > > But both ENDS IN A SINGLE BACKSLASH ! Apply the interpretation that the first case ends in a double backslash, and move on. > > The main thing which is hard to understand is: > > If a raw string is a string which ignores backslashes, > then it should ignore them in all circumstances, Nobody defines a raw string to be a "string that ignores backslashes", so your premise is invalid. > or where could be the problem here (python parser somewhere??). Why r"\" is not a valid string token has been done to death IIRC at least twice in this newsgroup ... Cheers, John From e.yunak at gmail.com Mon Jun 23 18:26:49 2008 From: e.yunak at gmail.com (Val-Amart) Date: Mon, 23 Jun 2008 15:26:49 -0700 (PDT) Subject: Terminating processes on Windows (handles and IDs) References: <98b73a28-fa07-4eac-8f3c-aec65aa819fe@k37g2000hsf.googlegroups.com> Message-ID: <36a78f0c-cbd4-45cd-a69f-44566f47b15f@b1g2000hsg.googlegroups.com> On Jun 23, 6:33?pm, geoffbache wrote: > Hi all, > > I've always wondered why os.kill isn't supported on Windows. I found a > discussion somewhere from 2006 about this so it seems others have > wanted it, but still nothing. So I have a half-baked solution > involving calling "taskkill" on Windows Vista or "tskill" on Windows > XP via the shell. I feel there has to be a better way. > > I'm also fairly confused about when I've got an ID and when I've got a > handle. The subprocess module gives me IDs which the above programs > accept, but other ways of spawning processes give me process handles > (while referring to them as process IDs in the docs...) and I don't > know how to kill a process with these. Besides, I've found an > amazingly useful PyGTK method, gobject.child_watch_add, which does > exactly what I want on UNIX but wants process handles on Windows. So I > can't use it in conjunction with subprocess there, and if I use some > other way of spawning processes I can't clean them up later. > > Is there any way to convert one of these numbers to the other? Or to > get a process handle out of subprocess? > (There must be one down there somewhere, surely?) > > Sorry for rambling a bit, am confused. > > Regards, > Geoff Bache My way to do it is using excellent wmi module by Tim Golden, which relies on Mark Hammond's pywin32 and Windows native wmi functionality. Here is the link - http://tgolden.sc.sabren.com/python/wmi.html Maybe, there is a more elegant way of doing that, but it works for me, and i feel nice with wmi. From torriem at gmail.com Thu Jun 19 18:44:50 2008 From: torriem at gmail.com (Michael Torrie) Date: Thu, 19 Jun 2008 16:44:50 -0600 Subject: don't make it worse! - was Re: SPAM In-Reply-To: <485A0E77.2050009@gmail.com> References: <88f0c3ba-46e1-4b30-a61d-482e5ecf339a@t12g2000prg.googlegroups.com> <485A0E77.2050009@gmail.com> Message-ID: <485AE162.8050407@gmail.com> Aspersieman wrote: > SPAM Obviously. Please refrain from replying to the SPAM on this list. It just makes the problem worse. Thanks. From maric at aristote.info Wed Jun 25 17:31:00 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 25 Jun 2008 23:31:00 +0200 Subject: Freeze problem with Regular Expression In-Reply-To: References: <6cf614F3f8ocoU1@mid.individual.net> Message-ID: <200806252331.00839.maric@aristote.info> Le Wednesday 25 June 2008 18:40:08 cirfu, vous avez ?crit?: > On 25 Juni, 17:20, Kirk wrote: > > Hi All, > > the following regular expression matching seems to enter in a infinite > > loop: > > > > ################ > > import re > > text = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA) > > una ' > > re.findall('[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-z]*\s*(?:[0-9 > >] *[A-Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$', text) > > ################# > > > > No problem with perl with the same expression: > > > > ################# > > $s = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA) una > > '; > > $s =~ /[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-z]*\s*(?:[0-9]*[A- > > Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$/; > > print $1; > > ################# > > > > I've python 2.5.2 on Ubuntu 8.04. > > any idea? > > Thanks! > > > > -- > > Kirk > > what are you trying to do? This is indeed the good question. Whatever the implementation/language is, something like that can work with happiness, but I doubt you'll find one to tell you if it *should* work or if it shouldn't, my brain-embedded parser is doing some infinite loop too... That said, "[0-9|a-z|\-]" is by itself strange, pipe (|) between square brackets is the character '|', so there is no reason for it to appears twice. Very complicated regexps are always evil, and a two or three stage filtering is likely to do the job with good, or at least better, readability. But once more, what are you trying to do ? This is not even clear that regexp matching is the best tool for it. -- _____________ Maric Michaud From bob at mellowood.ca Wed Jun 11 20:15:49 2008 From: bob at mellowood.ca (bvdp) Date: Wed, 11 Jun 2008 17:15:49 -0700 Subject: Simple and safe evaluator References: Message-ID: Matimus wrote: > > The solution I posted should work and is safe. It may not seem very > readable, but it is using Pythons internal parser to parse the passed > in string into an abstract symbol tree (rather than code). Normally > Python would just use the ast internally to create code. Instead I've > written the code to do that. By avoiding anything but simple operators > and literals it is guaranteed safe. > Just wondering ... how safe would: eval(s, {"__builtins__":None}, {} ) be? From my testing it seems that it parses out numbers properly (int and float) and does simple math like +, -, **, etc. It doesn't do functions like int(), sin(), etc ... but that is fine for my puposes. Just playing a bit, it seems to give the same results as your code using ast does. I may be missing something! From __peter__ at web.de Fri Jun 20 07:12:03 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 20 Jun 2008 13:12:03 +0200 Subject: Strange re problem References: <2a0a6f87-f72e-4190-85f8-6e43821e313a@r66g2000hsg.googlegroups.com> Message-ID: TYR wrote: > OK, this ought to be simple. I'm parsing a large text file (originally > a database dump) in order to process the contents back into a SQLite3 > database. The data looks like this: > > 'AAA','PF',-17.416666666667,-145.5,'Anaa, French Polynesia','Pacific/ > Tahiti','Anaa';'AAB','AU',-26.75,141,'Arrabury, Queensland, > Australia','?','?';'AAC','EG',31.133333333333,33.8,'Al Arish, > Egypt','Africa/Cairo','El Arish International';'AAE','DZ', > 36.833333333333,8,'Annaba','Africa/Algiers','Rabah Bitat'; > > which goes on for another 308 lines. As keen and agile minds will no > doubt spot, the rows are separated by a ; so it should be simple to > parse it using a regex. So, I establish a db connection and cursor, > create the table, and open the source file. > > Then we do this: > > f = file.readlines() > biglist = re.split(';', f) > > and then iterate over the output from re.split(), inserting each set > of values into the db, and finally close the file and commit > transactions. But instead, I get this error: > > Traceback (most recent call last): > File "converter.py", line 12, in > biglist = re.split(';', f) > File "/usr/lib/python2.5/re.py", line 157, in split > return _compile(pattern, 0).split(string, maxsplit) > TypeError: expected string or buffer > > Is this because the lat and long values are integers rather than > strings? (If so, any ideas?) No, the result of f.readlines() is a list, but re.split() expects a string as the second parameter. f = file.read() biglist = re.split(";", f) should work if the file fits into memory, but you don't need regular expressions here: biglist = file.read().split(";") is just as good -- or bad, if your data contains any ";" characters. Peter From straton at lampsacos.demon.co.uk Fri Jun 27 08:23:51 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Fri, 27 Jun 2008 13:23:51 +0100 Subject: How do I unit-test a specific case of a home-rolled exception ? In-Reply-To: References: Message-ID: Peter Otten wrote: > Ken Starks wrote: > >> I have an exception class, and I want to check that >> a particular instance of it has been raised; or >> more accurately that one is raised that is equal to >> an instance I specify. >> >> In the example below, I can check that a >> 'LongRationalError' is raised, but I want >> to check that it is specifically a >> 'LongrationalError('1') or a 'LongRationalError('2') >> >> How do I do that? > > (all untested) > > try: > LongRational(1, "7") > except LongRationalError, e: > self.assertEquals(e.code, "2") > else: > self.fail() > > Alternatively you can subclass LongRationalError... > > class LongRationalError(Exception): > pass > > class LongRationalDenominatorError(LongRationalError): > pass > > class LongRationalNumeratorError(LongRationalError): > pass > > ...and then check for the specialized exception: > > self.assertRaises(LongRationalDenominatorError, LongRational, 1, "7") > > Personally, I'd probably throw a plain old TypeError for incompatible types > of both numerator and denominator. > > Peter Thanks Peter, that answers my question nicely. I rather thought I would need a try .. except structure in my unit-test itself. From jason.scheirer at gmail.com Wed Jun 25 04:28:16 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Wed, 25 Jun 2008 01:28:16 -0700 (PDT) Subject: Porn Addiction References: <0bc1d618-f140-4390-9dd0-4ade923ab054@w1g2000prd.googlegroups.com> Message-ID: <96c7b5d6-7207-4af7-bde7-49891290aed7@u36g2000prf.googlegroups.com> On Jun 24, 5:24?pm, Hughjar... at gmail.com wrote: > Help, I'm addicted to porn. I've been downloading porn online and > masturbating to it for a few years... Lately it's gotten even worse, I > spend hours and hours surfing and masturbating to it. It's taking over > my life and ruining everything.. I even missed days from work because > of this addiction. > > I'm going to the porn as a way to avoid unwanted feelings or > procrastination and then it just takes over. > > What can I do to end this horrible addiction? > > -Hugh Obviously porn is awesome and an integral part of your life, you spambot (and your responding stormbot friends). The only solution is PETABYTES OF PORN. TERRIBLE TERRIBLE PORN. From sjmachin at lexicon.net Sun Jun 29 20:18:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 29 Jun 2008 17:18:02 -0700 (PDT) Subject: Function to import module to namespace References: Message-ID: <4cea42f2-b896-43a8-b8dd-ead2a1add327@z16g2000prn.googlegroups.com> On Jun 30, 9:52 am, bvdp wrote: > Terry Reedy wrote: > > > > > > > > > > Do you mean something like this? > > > > > >>> math.__dict__.update(string.__dict__) > > >>> dir(math) > > ['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', > > > > I think this is working.... First off, 2 module files: > > funcs.py > def func1(): > print "I'm func1 in funcs.py" > > more.py > def func2(): > print "I'm func2 in 'more.py'" > > and my wonderful main program: > > xx.py > import funcs > def addnewfuncs(p): > x = __import__(p) > funcs.__dict__.update(x.__dict__) > funcs.func1() > addnewfuncs('more') > funcs.func2() > > The first problem I had was getting import to accept a variable. It > doesn't seem to, so I used __import__(). Then, I had to remember to > assign this to a variable ... and then it appears to work just fine. > > Did I miss anything in this??? You are updating with *everything* in the 'more' module, not just the functions. This includes such things as __name__, __doc__, __file__. Could have interesting side-effects. One quick silly question: why do you want to do this anyway? Sorry, *two* quick silly questions: are the add-on modules under your control, or do you want to be able to do this with arbitrary modules? [If under your control, you could insist that such modules had an __all__ attribute with appropriate contents] A third: why do you want to import into an existing namespace? Now that you know about __import__, why just not call the functions where they are? Cheers, John From enleverlesX.XmcX at XmclaveauX.com Sun Jun 1 04:46:24 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sun, 1 Jun 2008 10:46:24 +0200 Subject: Merging ordered lists In-Reply-To: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> References: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> Message-ID: <484262f8$0$866$ba4acef3@news.orange.fr> Hi! Use set (union). Example: la=[2,1,3,5,4,6] lb=[2,8,6,4,12] #compact: print list(set(la).union(set(lb))) #detail: s1 = set(la) s2 = set(lb) s3 = s1.union(s2) print list(s3) @-salutations Michel Claveau From andrei.avk at gmail.com Mon Jun 9 13:29:38 2008 From: andrei.avk at gmail.com (Rainy) Date: Mon, 9 Jun 2008 10:29:38 -0700 (PDT) Subject: Separators inside a var name Message-ID: I have a stylistic question. In most languages words in var. name are separated by underscores or cap letters, resulting in var names like var_name, VarName and varName. I don't like that very much because all 3 ways of naming look bad and/or hard to type. From what I understand, scheme can have variables like var-name. I'm curious about reasons that python chose to disallow this. Another question I have is what other languages allow this naming scheme? Were there any languages that allowed space as a separator? What would be a practical way to separate variables from keywords in that case? "some long variable name", 'just a string', or maybe using 2 spaces: one var + other var + third var ? I think being able to easy have very long names for vars that are easy to type would be a fairly significant advantage. I know I'm probably being too obsessive about this, but that didn't stop me from posting. Comments? From MyDomDom at gmail.com Sat Jun 21 07:17:49 2008 From: MyDomDom at gmail.com (dominique) Date: Sat, 21 Jun 2008 04:17:49 -0700 (PDT) Subject: How to convert a ">" into a > Message-ID: Hello All, In a wx GUI, I would like to let the user choose between >, < or =. So, I created a combobox and when the user chooses ">" for instance, I wanted to return > (the objective is to send the operator into another complex method): Example: if variable == ">": return > But this is invalid syntax. How can I transform a ">" into the > operator ie without parenthesis, so that I can load it into another function ? Thanks in advance Dominique From dananrg at yahoo.com Sun Jun 22 18:11:55 2008 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: Sun, 22 Jun 2008 15:11:55 -0700 (PDT) Subject: Getting column names from a cursor using ODBC module? References: <4fe11953-15a9-4363-819f-b54b4f05941c@y38g2000hsy.googlegroups.com> Message-ID: <0d8458af-d48e-4790-80dd-7fd7745b1c48@2g2000hsn.googlegroups.com> Thanks Chris and John. Chris, this worked perfectly with the ODBC module that ships with Python Win32: > column_names = [d[0] for d in cursor.description] John, I've never heard of pyodbc but I'll have to look into it. Thanks again. Dana From R.Brodie at rl.ac.uk Fri Jun 6 11:33:35 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 6 Jun 2008 16:33:35 +0100 Subject: cgi, parse_header and semi-colon References: Message-ID: "Sylvain" wrote in message news:b80af57f-897d-4fd1-bebc-df0782143314 at 25g2000hsx.googlegroups.com... > If we upload a file with a semi-colon (i.e : "C:/my;file.jpg") : > cgi.FieldStorage.filename returns only "my" everything after the semi- > colon is missing > > Is it a bug or i'm missing something ? I doubt it's bug in parse_header, since it's meant to split on semicolons. Whether it's a bug in one of its callers, or the client not escaping sufficiently, I couldn't say offhand. From Lie.1296 at gmail.com Tue Jun 3 07:32:39 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 3 Jun 2008 04:32:39 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> Message-ID: <8479ceec-848e-43c2-8d72-a89c5a61372f@h1g2000prh.googlegroups.com> On Jun 3, 5:07?pm, "BJ?rn Lindqvist" wrote: > On Mon, Jun 2, 2008 at 10:50 PM, Russ P. wrote: > > On Jun 2, 6:41 am, Carl Banks wrote: > > >> You are not realizing that only useful(**) thing about data hiding is > >> that some code has access to the data, other code does not. ?If you > >> "hide" data equally from everyone it's just a useless spelling change. > > > I think you're missing the point. > > > As I see it, the primary value of data hiding is that it provides > > useful information on which data and methods are intended for the > > client and which are intended for internal use. It's like putting a > > front panel on a TV set with the main controls intended for the > > viewer. > > Here's my two cents. First of all, a TV is a bad analogy compared to > reusable software libraries. Really bad analogy. A TV is a horribly > complicated device which has to be dumbed down because otherwise it > would be to hard to use for ordinary people. I think it's actually quite a good analogy, a class may get quite complicated and it may do completely different things that the public interface seems to imply. Anyway, an analogy is an analogy, don't expect it to be exactly the same as the case itself, expect it to illustrate the point well enough and ignore the differences not being illustrated. TV is a good analogy since it illustrated the point quite well, that there are some things user may freely interact, some that users should not mess with, and things that is strictly not for you. Nevertheless, with the proper knowledge and proper tools, any users could open the case and get the special screwdriver to open the TV, if all else fails, he could always get a hammer to break the casing and gone his way through. Python does not enforce data-hiding because it expect people that gone his way to ignore the warning and get the special screwdriver to be knowledgeable enough to mess with it. C/C++ expects people to use hammer to break through their casings, and in the end, since the casings has already been broken, the device may never look as beautiful as before. In python, the device may appear to look just as beautiful. > A software developers relation to a third party library is more > similar to a TV repair man trying to repair a TV than to a random > person watching TV. For a repair man, the front panel is just useless > and in the way. No, for a knowledgable man (a TV repairman), he'd try first to fix the TV without opening the case (such as seeing whether the power cable is actually plugged), and if those attempts fails (or if he already know where the damage is from the beginning), he'd then open the screws. The public interface isn't "useless and in the way". > Oh, and to continue on the TV analogy, one of the reason why a TV is > complicated is because its interface is totally different from its > implementation. Channels are just a bad abstraction for tuning the > receiver to different frequencies and for switching inputs. Merely > using a TV doesn't teach you anything about how it actually works. Why couldn't a class have interface that's completely different thing than the implementation. > KISS: Keep It Simple Stupid. And it is always simpler to not implement > the gunk needed for data hiding than to do it. By keeping things > simple you keep your code easy to implement, easy to understand and > easy to reuse. > > Data hiding sacrifices implementation simplicity supposedly to make > the interface simpler and to keep backwards compatibility. It allows > you to change implementation details without affecting the > interface. But do you really want to do that? Consider this silly Java > example: > > ? ? class Foo { > ? ? ? ? private int bar; > ? ? ? ? public int getBar() { > ? ? ? ? ? ? return bar; > ? ? ? ? } > ? ? }; > > Then for some reason you decide that hm, "bar" is not a good attribute > name so you change it to "babar". And you can do that without changing > the public interface! Woho! So now you have a public getter named > "getBar" that returns an attribute named "babar". That's in reality > just bad and whoever is maintaining the implementation is going to be > annoyed that the getters name doesn't match the attribute name. > > What would have happened without data hiding? Renaming the public > attribute "bar" to "babar" probably cause some grief for someone > reusing your library, but you would keep your implementation pure. > > What about semantic changes? Data hiding doesn't protect you against > that, so you'll have to change your interface anyway. The interface > for a car hasn't changed much in the last 100 years, but the > implementation has. How easy is it to repair a car nowadays compared > to 30 years ago? > > And data hiding as a documentation aid is just a sham. "These methods > are public so you can call them, these aren't so hands off!" A reuser > of your library *will* want to know what happens on the inside, by > trying to make stuff impossible to reach you are just making that kind > of information much harder to come by. And we expect those people is ready that the car may blow off right in their face since they have violated the lines. If they broke the lines and still think that we're guilty for his burnt face, that's their problem. > The better method is to just write proper docstrings that tell the > user what the methods do and when they can be called. > > Another good way to see how useless data hiding is, is to try and unit > test a very encapsulated library. You'll see that it is almost > impossible to write good unit tests unless you publicly export > almost everything in the code. At which point you come to realize that > all the data hiding was for naught. > > -- > mvh Bj?rn From martin at v.loewis.de Tue Jun 17 01:28:45 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 17 Jun 2008 07:28:45 +0200 Subject: PEP 372 -- Adding an ordered directory to collections In-Reply-To: <97b828d8-e64c-47db-8b8e-d403e8076756@x35g2000hsb.googlegroups.com> References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <4856e80c$0$30401$9b622d9e@news.freenet.de> <97b828d8-e64c-47db-8b8e-d403e8076756@x35g2000hsb.googlegroups.com> Message-ID: <48574B8D.6010102@v.loewis.de> > My guess is that the two main memory allocate/deallocate cases are 1) > appending a new item to the end, and 2) GC'ing the entire data > structure. I would optimize these 2 at the expense of all others. Does that include dictionary lookups? Regards, Martin From gagsl-py2 at yahoo.com.ar Wed Jun 25 18:58:48 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 25 Jun 2008 19:58:48 -0300 Subject: python script for tortoise cvs References: <8c7f10c60806190626i2dd28eacp50a4de20c2a6556d@mail.gmail.com> <5ed8a05d-81ac-4625-b4f5-8169495cb654@l42g2000hsc.googlegroups.com> Message-ID: En Tue, 24 Jun 2008 12:16:07 -0300, sandeep escribi?: > i think ur suggestions do formulate my problem.now since i know some > commands i wanted to know how can i execute cvs commands from python > or we can say how can i capture the output from the cvs command ?. Use the subprocess module py> cvsexe = r"c:\Archivos de programa\CVSNT\cvs.exe" py> import subprocess py> p = subprocess.Popen([cvsexe, "status", "dinglob.pas"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) py> output = p.communicate()[0] py> print output =================================================================== File: dinglob.pas Status: Up-to-date Working revision: 1.102 Repository revision: 1.102 /.../DINW/dinglob.pas,v Expansion option: kv Commit Identifier: 484474257304f18 Sticky Tag: (none) Sticky Date: (none) Sticky Options: (none) Merge From: (none) -- Gabriel Genellina From michele.simionato at gmail.com Mon Jun 16 05:01:13 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 16 Jun 2008 02:01:13 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> Message-ID: On Jun 16, 10:37?am, Armin Ronacher wrote: > Abstract > ======== > > This PEP proposes an ordered dictionary as a new data structure for > the ``collections`` module, called "odict" in this PEP for short. ?The > proposed API incorporates the experiences gained from working with > similar implementations that exist in various real-world applications > and other programming languages. +1, I have been waiting for an odict in the library for at least 5 years. Michele Simionato From eduardo.tessarioli at gmail.com Tue Jun 17 14:34:27 2008 From: eduardo.tessarioli at gmail.com (Eduardo Henrique Tessarioli) Date: Tue, 17 Jun 2008 15:34:27 -0300 Subject: Static memory allocation in Python Message-ID: <5868cf920806171134n33af0512j8ad93fc300fe015a@mail.gmail.com> Hi, I am running a very simple python application and I noted that the memory allocation is something like 4,5M. This is a problem in my case, because I have to run 2 thousand process at the same time. The memory I need is 100k or less. Is there any way to set this for the python process? Regards, Eduardo -------------- next part -------------- An HTML attachment was scrubbed... URL: From maric at aristote.info Tue Jun 24 04:33:07 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 24 Jun 2008 10:33:07 +0200 Subject: binary representation of an integer In-Reply-To: <14e14b5e-ce39-414a-a450-7c81baaabc3a@79g2000hsk.googlegroups.com> References: <14e14b5e-ce39-414a-a450-7c81baaabc3a@79g2000hsk.googlegroups.com> Message-ID: <200806241033.10037.maric@aristote.info> Le Tuesday 24 June 2008 10:03:58 eliben, vous avez ?crit?: > Hello, > > I'm interested in converting integers to a binary representation, > string. I.e. a desired function would produce: > > dec2bin(13) => "1101" > > The other way is easily done in Python with the int() function. > > Perl has a very efficient way to do dec2bin, because its pack/unpack > have a B format for binary representations, so it's done with: > > sub dec2bin { > my $str = unpack("B32", pack("N", shift)); > $str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros > return $str; > } > > Python's pack/unpack don't have the binary format for some reason, Yes, but I think the %b format specifier has been added to p3k but will not in python 2.x. > so > custom solutions have to be developed. One suggested in the ASPN > cookbook is: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 > However, it is very general and thus inefficient. > > What would be the quickest way to do this ? I think that for dec2bin > conversion, using hex() and then looping with a hex->bin lookup table > would be probably much faster than the general baseconvert from the > recipe. > > What do you think? Something like that, less typing with octal conversion :) >>>[8]: oct2bin = {'0':'000', '1':'001', '2':'010', '3':'011', '4':'100', '5':'101', '6':'110', '7':'111'} >>>[9]: ''.join(oct2bin[e] for e in "%o"%35).lstrip('0') ...[9]: '100011' -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 4 26 88 00 97 Mobile: +33 6 32 77 00 21 From ivan.illarionov at gmail.com Thu Jun 5 11:21:46 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 5 Jun 2008 08:21:46 -0700 (PDT) Subject: Tuples part 2 References: <6d3e6d40-63a6-40d1-8ea4-5ddf40238d8d@m44g2000hsc.googlegroups.com> <99bc30fb-532a-4c4f-9f5e-e7a18c28d2a5@z72g2000hsb.googlegroups.com> Message-ID: <0ecaaa47-3ad4-4f67-9d48-94d5d1951bc6@y21g2000hsf.googlegroups.com> On 5 ???, 18:56, Ivan Illarionov wrote: > On 5 ???, 18:19, "victor.hera... at gmail.com" > wrote: > > > > > On Jun 5, 3:49 pm, Ivan Illarionov wrote: > > > > On 5 ???, 01:57, "victor.hera... at gmail.com" > > > wrote: > > > > > Hi Everyone, > > > > > i have another question. What if i wanted to make n tuples, each with > > > > a list of coordinates. For example : > > > > > coords = list() > > > > for h in xrange(1,11,1): > > > > for i in xrange(1, 5, 1) : > > > > for j in xrange(1, 5, 1) : > > > > for k in xrange(1,2,1) : > > > > coords.append((i,j,k)) > > > > lista+str(h)= tuple coords > > > > print tuple(coords) > > > > > so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do > > > > it the way i show you above but it is not working properly. I wish you > > > > could help me with that. Thanks again, > > > >>> from itertools import repeat, izip > > > >>> coords = tuple((i,j,k) for i in xrange(1,5) for j in xrange(1,5) for k in xrange(1,2)) > > > >>> locals().update(("tuple%s" % i, coord) for i, coord in izip(xrange(1,11), repeat(coords))) > > > >>> tuple1 > > > > ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (2, 1, 1), (2, 2, 1), (2, > > > 3, 1), (2 > > > , 4, 1), (3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1), (4, 1, 1), (4, 2, > > > 1), (4, 3 > > > , 1), (4, 4, 1)) > > > > Does this help? > > > > But I don't understand why you need this? > > > > Ivan > > > Hi, > > > What i need is, for example: > > > tuple 1=((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)) > > > tuple 2=((2, 1, 1), (2, 2, 1), (2, 3, 1), (2, 4, 1)) > > > tuple 3=((3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1)) > > > and so on. Please help me and sorry for not taking the time to post my > > questions properly. > > > Victor > > Or even so: > > locals().update(("tuple_%s" % i, tuple((i,j,k) for j in range(1,5) for > k in range(1,2))) for i in range(1,5)) > > Ivan Tried to make it readable: def iter_coords(i): for j in xrange(1,5): for k in xrange(1,2): yield i, j, k def iter_vars(): for i in xrange(1, 5): yield "tuple_%s" % i, tuple(iter_coords(i)) locals().update(dict(iter_vars())) >>> tuple_1 ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)) >>> tuple_2 ((2, 1, 1), (2, 2, 1), (2, 3, 1), (2, 4, 1)) >>> tuple_3 ((3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1)) >>> tuple_4 ((4, 1, 1), (4, 2, 1), (4, 3, 1), (4, 4, 1)) Ivan From grante at visi.com Sat Jun 14 16:46:11 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 14 Jun 2008 15:46:11 -0500 Subject: Creating a TCP/IP connection on already-networked computers References: <4853f269$0$11615$607ed4bc@cv.net> <4854123f$0$5017$607ed4bc@cv.net> <485413d0$0$4997$607ed4bc@cv.net> <485425b2$0$11631$607ed4bc@cv.net> Message-ID: On 2008-06-14, John Salerno wrote: > Grant Edwards wrote: > >>> Shouldn't it be something different, since the requests are >>> coming from a different computer than the server computer? >> >> Works fine for me. When I run the client program on a machine >> different than the server program, the server program prints >> out "connected from:" and then the client machine's IP address. > > Hmm, so could the reason that the client request is shown to be coming > from the same IP address as the server machine be that they are on the > same home network? No, not for the usual value of "on the same home network". I've no idea how your home network is set up, so that's about all I can say. > I guess to truly test my question, I need to have two > computers that are completely "unrelated" to one another -- > meaning they are in no way connected via any type of network > prior to running these scripts. If the two computers are in no way connected via any type of network, then the two programs won't be able to talk to each other. The programs can't create a network, they can only use one that already exists. -- Grant Edwards grante Yow! I've got an IDEA!! at Why don't I STARE at you visi.com so HARD, you forget your SOCIAL SECURITY NUMBER!! From jschroed at gmail.com Mon Jun 9 03:27:16 2008 From: jschroed at gmail.com (John Schroeder) Date: Mon, 9 Jun 2008 00:27:16 -0700 Subject: Access to CAN-Bus In-Reply-To: <6b43jvF3a2qu9U1@mid.uni-berlin.de> References: <484cd469$0$28520$3b214f66@aconews.univie.ac.at> <6b43jvF3a2qu9U1@mid.uni-berlin.de> Message-ID: <4878ad7b0806090027ta169e8co14693a8d964801b9@mail.gmail.com> Isn't a CAN bus accessed via the COM ports (serial or parallel)? If this is the case, then you should use pySerial and/or pyParallel but you would have to define the protocol yourself. (I've used pyserial to implement a LAPB protocol.) On Mon, Jun 9, 2008 at 12:15 AM, Diez B. Roggisch wrote: > Thin Myrna schrieb: > >> I'd like to access some drive hardware via CAN bus from Python under Linux >> (sending rec'ing PDOs). Googling around I couldn't find a Python package, >> but people who said that they are doing this, though. I guess they are >> using their home brewn software. >> Any pointer to - such software (anyone willing to share his experience?) >> - how to write such software? >> >> Under Windows, I guess, I could use some COM or ctypes functionality to >> access the hardware vendor's hardware. What if I wanted to access such >> hardware from Linux? Is there a package that allows that in a vendor (who >> doesn't support Linux) independent way? >> > > I've never heard of a OS-level CAN-bus-integration. So I doubt that there > is any vendor-independent way. > > Doesn't your CAN-bus-interface have some library or driver support? > > Diez > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dan at catfolks.net Thu Jun 26 13:06:27 2008 From: dan at catfolks.net (Daniel Mahoney) Date: Thu, 26 Jun 2008 12:06:27 -0500 Subject: I Need A Placeholder References: Message-ID: On Thu, 26 Jun 2008 10:03:47 -0700, Ampedesign wrote: > I'm trying to build a try/except case, and I want to have the except > function like such: > > try: > # Do some code here > var = 1 # For example > except: > #Do nothing here > > The only problem is if I leave a comment only in the except block, I > get an error back saying that the except block is not properly > formatted, since it has no content other than a comment. > > So if anyone could suggest some code to put there as a placeholder > that would be wonderful. "pass" would work fine. try: # Do something that can throw an exception except: pass From kyosohma at gmail.com Mon Jun 9 14:00:28 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 9 Jun 2008 13:00:28 -0500 Subject: How to get full path to script? In-Reply-To: References: Message-ID: On Mon, Jun 9, 2008 at 12:42 PM, Sebastian lunar Wiesner wrote: > Mike Driscoll at Montag 09 Juni 2008 18:20: > >> On Mon, Jun 9, 2008 at 11:07 AM, kj wrote: >>> In "Mike Driscoll" >>> writes: >>> >>>>For my compiled scripts, I usually use this variation: >>> >>>>path = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))) >>> >>> Thanks. But why the os.path.join()? (BTW, I did read the docs >>> before posting, but they make no sense to me; they say that >>> os.path.join joins "one or more path components intelligently", >>> but what does it mean to join *one* component?) >>> >>> Kynn >>> >>> -- >>> NOTE: In my address everything before the first period is backwards; >>> and the last period, and everything after it, should be discarded. >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> The idea of the join method is to create the path in an OS agnostic >> fashion. Linux uses forward slashes and Windows uses backward slashes >> to join the parts. The join method does this for you so you don't have >> to. > > I guess, you didn't get his point. He seems to be aware that os.path.join > creates a path from _multiple_ strings by joining them with the correct > separator used by the underlying platform. > > But he was asking why one would invoke os.path.join on a _single_ string, as > you did in your example. I'm wondering about this, too. It doesn't make > sense to me. os.path.join doesn't convert existing separators to the > platform-specific ones. And even if it would, sys.argv[0] already contains > a correct path, so there is nothing that needs conversion. So why use it > with a _single_ argument? I'd appreciate an example, illustrating the use > of this ;) > > > -- > Freedom is always the freedom of dissenters. > (Rosa Luxemburg) > -- > http://mail.python.org/mailman/listinfo/python-list > Okay, basically the answer is that I'm kind of stupid. Months ago, the users on the wxPython group were discussing this issue and one of them posted that snippet of code to show how they worked around the issue. I thought I'd try it and it worked great, although I couldn't really follow what was happening at the time. Looking at it now, there doesn't appear to be any reason for the os.path.join part. I tried running one of my simple scripts with and without it and they return the same string. I apologize for propagating erroneous code. Mike From morton.thomas at googlemail.com Tue Jun 10 15:01:12 2008 From: morton.thomas at googlemail.com (Thomas Morton) Date: Tue, 10 Jun 2008 20:01:12 +0100 Subject: problems with opening files due to file's path References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <17761946.post@talk.nabble.com> Message-ID: <7B9AC1C9E17440AA89A4CB3937219C47@ErrantGaming> heh thanks Mike - glad im not going mad :P Just tested locally in IDLE (I know I know!) and it works for me like this: >>> test = os.path.join(os.getcwd(),"NEWS.txt") >>> test 'D:\\Python25\\NEWS.txt' >>> os.startfile(r"%s"%test) >>> And the file opens... Does the file definitely exist? Tom -------------------------------------------------- From: "Alexnb" Sent: Tuesday, June 10, 2008 7:37 PM To: Subject: Re: problems with opening files due to file's path > > No this time it perhaps gave me the worst of all heres what I entered, and > the output > >>>> startfile(r"%s"%full) ***full is the path*** > > startfile(r"%s"%full) > > WindowsError: [Error 2] The system cannot find the file specified: > '"C:\\Documents and Settings\\Alex\\My Documents\\My > Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I\'m Yours (Single)\x01 - I\'m > Yours.wma"' > > > Thomas Morton wrote: >> >> maybe try string substitution... not sure if that's really the BEST way >> to >> do it but it should work >> >> startfile(r"%s"%variable) >> >> -------------------------------------------------- >> From: "Alexnb" >> Sent: Tuesday, June 10, 2008 7:05 PM >> To: >> Subject: Re: problems with opening files due to file's path >> >>> >>> Well, now i've hit another problem, this time being that the path will >>> be >>> a >>> variable, and I can't figure out how to make startfile() make it raw >>> with >>> a >>> variable, if I put startfile(r variable), it doesn't work and >>> startfile(rvariable) obviously won't work, do you know how to make that >>> work >>> or better yet, how to take a regular string that is given and make every >>> single "\" into a double "\\"? >>> >>> Mike Driscoll wrote: >>>> >>>> On Jun 10, 11:45 am, Alexnb wrote: >>>>> Gerhard H?ring wrote: >>>>> >>>>> > Alexnb wrote: >>>>> >> Okay, so what I want my program to do it open a file, a music file >>>>> in >>>>> >> specific, and for this we will say it is an .mp3. Well, I am using >>>>> >> the >>>>> >> system() command from the os class. [...] >>>>> >>>>> >> system("\"C:\Documents and Settings\Alex\My Documents\My >>>>> >> Music\Rhapsody\Bryanbros\Weezer\(2001)\04 - Island In The >>>>> Sun.wma\"") >>>>> >> [...] >>>>> >>>>> > Try os.startfile() instead. It should work better. >>>>> >>>>> > -- Gerhard >>>>> >>>>> > -- >>>>> >http://mail.python.org/mailman/listinfo/python-list >>>>> >>>>> No, it didn't work, but it gave me some interesting feedback when I >>>>> ran >>>>> it >>>>> in the shell. Heres what it told me: >>>>> >>>>> >>> os.startfile("C:\Documents and Settings\Alex\My Documents\My >>>>> >>> Music\Rhapsody\Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm >>>>> >>> Yours.wma") >>>>> >>>>> Traceback (most recent call last): >>>>> File "", line 1, in >>>>> os.startfile("C:\Documents and Settings\Alex\My Documents\My >>>>> Music\Rhapsody\Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm >>>>> Yours.wma") >>>>> >>>>> WindowsError: [Error 2] The system cannot find the file specified: >>>>> "C:\\Documents and Settings\\Alex\\My Documents\\My >>>>> Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\x01 - I'm >>>>> Yours.wma" >>>>> >>>>> See it made each backslash into two, and the one by the parenthesis >>>>> and >>>>> the >>>>> 0 turned into an x.... >>>>> -- >>>>> View this message in >>>>> context:http://www.nabble.com/problems-with-opening-files-due-to-file%27s-pat... >>>>> Sent from the Python - python-list mailing list archive at Nabble.com. >>>> >>>> Yeah. You need to either double all the backslashes or make it a raw >>>> string by adding an "r" to the beginning, like so: >>>> >>>> os.startfile(r'C:\path\to\my\file') >>>> >>>> HTH >>>> >>>> Mike >>>> -- >>>> http://mail.python.org/mailman/listinfo/python-list >>>> >>>> >>> >>> -- >>> View this message in context: >>> http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17761338.html >>> Sent from the Python - python-list mailing list archive at Nabble.com. >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -- > View this message in context: > http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17761946.html > Sent from the Python - python-list mailing list archive at Nabble.com. > > -- > http://mail.python.org/mailman/listinfo/python-list From steve at holdenweb.com Wed Jun 4 08:57:08 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Jun 2008 08:57:08 -0400 Subject: Training Class in July Message-ID: <48469124.6050304@holdenweb.com> Holden Web is holding the second of its public "Introduction to Python" classes on July 8-10 in Springfield, VA (just outside Washington, DC). The class is described briefly at http://holdenweb.com/py/introclass/ and the current schedule is at http://holdenweb.com/py/training/ Bookings are now being accepted through our web site. Please contact info at holdenweb.com for multi-student discount details. Comments from the students on our March class: "Great class. Very informative" JSc "This tied Python together and now I can go learn on my own until I hit the next plateau" JSa "Excellent course, lots of good information" VB "It was a good course and the price was just right" AW -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From tjreedy at udel.edu Sun Jun 15 15:34:22 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 15 Jun 2008 15:34:22 -0400 Subject: Explaining Implementing a Binary Search Tree. References: Message-ID: "Bart Kastermans" wrote in message news:ae91857d-ea63-4204-9fc3-251049adee98 at k13g2000hse.googlegroups.com... |I wrote a binary search tree in python, explaining as I was doing it | how and why I did it. I am very interested in receiving comments on | the code, process, and anything else that will improve my coding or | writing. | | I wrote this all up in my blog at: | | http://kasterma.wordpress.com/2008/06/15/implementing-a-binary-search-tree/ | | The code of the class has been copied below, but the description of | the process (mostly an attempt at approaching test driving development | for as far as I understand the term) has not been copied. | | Any and all comments are appreciated. | | Best, | Bart | | *********** python code ************************ | | | import re | | class BSTree: | def __init__ (self, value = None): | self.value = value | self.left = None | self.right = None There are two possible approaches. 1. Define 1 tree class that is also used for subtrees -- what you did. Complication: self.value of root node can be none, so you constantly have to check self.value for None even though only possible for root node. 2. Define tree class and node class. This had other complications, but removes that above and makes str easier. tree.str = '(' str(rootnode) ')' and node.str= self.value '(' str(self.left) ')' '(' str(self.right) ')'. If use '' instead of None, no conditionals are needed. (This might apply partly to your version as well.) Or define class NullTree with a singleton instance with no attributes and a str method returning '' and an inOrder method yielding nothing. This would also eliminate the condifionals in the inOrder method. Not sure what is best. With a good test suite, it is easy to make sure alternative implementations 'work' before testing for speed. | def __str__ (self): string appending is an O(n**2) operations. The usual idiom, applied here, would be slist = ['('], slist.append(str(self.value)), .... return ''.join(slist). In other words, collect list of pieces and join at end. | string = "(" | if not self.value == None: | string += str (self.value) | | if not (self.left == None and self.right == None): | if self.left != None: | string += str (self.left) | else: | string += "()" | | if self.right != None: | string += str (self.right) | else: | string += "()" | | string += ")" | | return string | | def FromString (self, string): | """ parses the string and builds the corresponding tree. | | If the parsing fails we print an error message and make no | guarantees about the state of the tree. | | """ | | def readNumber (string, index): | """ reads the number starting at index. | | Returns the number (as a string) that starts at index and | the index that is just after the number. It expects the | index to point to the first numberal. | | """ | | isdigit = re.compile ("\d") | number = "" | while isdigit.match (string [index]): | number += string[index] | index += 1 | | return number, index | | def FromString_Help (string, index): | """ The function that actually does the parsing of the | string. | | Variable index indicates where in the string we start | working, | it should be pointing to an open paren, and in returning | point | to just after the corresponding closing paren. | | """ | | if not string [index] == "(": | print "FromString_Help: ERROR: no opening paren", | print string, index | | tree = BSTree () | | tree.value, index = readNumber (string, index + 1) | | if string [index] == "(": | tree.left, index = FromString_Help (string, index) | tree.right, index = FromString_Help (string, index) | | if not string[index] == ")": | print "FromString_Help: ERROR: no closing paren" | print string, index | | if tree.value == '' and tree.left == None and tree.right | == None: | return None, index + 1 | else: | tree.value = int (tree.value) | | return tree, index + 1 | | index = 0 | tree, index = FromString_Help (string, index) | | if tree == None: | print "FromString: ERROR: empty tree passed" | return | | self.value = tree.value | self.left = tree.left | self.right = tree.right | | def inOrder (self): | """ gives a generator that runs through the tree inOrder """ Nope. Returns an inorder list of values. For an actual generator, which I recommend, *yield* values. | | values = [] [delete this' | if self.left != None: | values += self.left.inOrder () for value in self.left.inOrder: yield value | if self.value != None: | values.append (self.value) yield self.value | if self.right != None: | values += self.right.inOrder () for value in self.right.inOrder: yield value | return values [delete this] The above with result in a stack of generators as deep as the tree. It would probably be faster to eliminate the recursion with an explicit stack of trees, but I cannot currently write that off the top of my head. (This is part of my current writing project.) But again, a test suite eases exploration of alternatives. | def Insert (self, value): | """ add value to the tree in BSTree fashion. | | We add the value so that the values of the tree will be in | order. We do not duplicate values in the tree. | | """ | if self.value == None: # first value added to this tree | self.value = value | | if self.value < value: | if self.right == None: | self.right = BSTree (value) | else: | self.right.Insert (value) | | if self.value > value: | if self.left == None: | self.left = BSTree (value) | else: | self.left.Insert (value) | | def Delete (self, value, parent = None, RL = None): | """ remove value from the tree in BSTree fashion. | | Note: we might end up with an empty tree. | | """ | if self.value == value: | if self.left == None and self.right == None: | if parent != None: | if RL == "right": | parent.right = None | else: | parent.left = None | else: | self.value = None # created an empty tree, note | only | # happens at the root. | return | if self.left == None: | self.value = self.right.value | self.left = self.right.left | self.right = self.right.right | elif self.left.right == None: | self.value = self.left.value | self.left = self.left.left | else: | moveup = self.left | while moveup.right != None: | # note that by the elif above at least one step is | taken | # we are here looking for the node to move up to | the root | moveup_parent = moveup | moveup = moveup.right | moveup_parent.right = moveup.left | self.value = moveup.value | return | | if self.value < value: | self.right.Delete (value, self, "right") | | if self.value > value: | self.left.Delete (value, self, "left") | | def Search (self, value): | if self.value == value: | return "yes" | if self.value < value: | if self.right == None: | return "no" | else: | return self.right.Search (value) | if self.value > value: | if self.left == None: | return "no" | else: | return self.left.Search (value) | -- | http://mail.python.org/mailman/listinfo/python-list | From joe.p.cool at googlemail.com Sat Jun 28 18:13:21 2008 From: joe.p.cool at googlemail.com (Joe P. Cool) Date: Sat, 28 Jun 2008 15:13:21 -0700 (PDT) Subject: surprising behaviour of os.environ.clear References: <463baf33-e2d5-41fd-839e-aae45ee5433e@b1g2000hsg.googlegroups.com> <52ecaa6c-b476-4720-9fd4-362471c2686e@k13g2000hse.googlegroups.com> Message-ID: <04719ede-59df-4845-bd63-4cbb2a34c649@z66g2000hsc.googlegroups.com> On 28 Jun., 23:06, "Joe P. Cool" wrote: > On 28 Jun., 04:05, Benjamin wrote: > > > On Jun 27, 4:05 pm, "Joe P. Cool" wrote: > > This is because of how os.environ is implement with a UserDict > > subclass. You should report this at bugs.python.org. > > issue 3227: os.environ.clear has no effect on child processes. According to Benjamin Peterson this has been fixed in the upcoming Python 2.6. From mnordhoff at mattnordhoff.com Fri Jun 27 12:50:34 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 27 Jun 2008 16:50:34 +0000 Subject: Windows OS , Bizarre File Pointer Fact In-Reply-To: <864ab9f2-7d99-49f0-9d41-93ec41e26203@y38g2000hsy.googlegroups.com> References: <864ab9f2-7d99-49f0-9d41-93ec41e26203@y38g2000hsy.googlegroups.com> Message-ID: <48651A5A.1020602@mattnordhoff.com> Taygun Kekec wrote: > Code : > #!/usr/bin/python > # -*- coding: utf-8 -*- > import os > > if os.name == 'nt': > OS_Selection = 0 > elif os.name == 'posix': > OS_Selection = 1 > else : > OS_Selection = 1 > > del_cmd_os = ( "del","rm") > filelist = ("ddd.txt","eee.txt","fff.txt") > > # Creating Files > for elem in filelist: > open( elem, 'w').write("Selam") > > # > # Removing Files > for elem in filelist: > fp = open( elem, 'r') > os.system( "%s %s" % (del_cmd_os[OS_Selection], fp.name)) > fp.close() > # > > Run this code on Windows XP , it says "the file is being used by > another process" and fails to delete the file. I tried replacing : > # > for elem in filelist: > open( elem, 'w').write("Selam") > # > with : > # > for elem in filelist: > fp = open( elem, 'w') > fp.write("Selam") > fp.close() > # > > in case of any interpreter file pointer destructor failure but it > didnt change anything. > Do you have any idea why my files cannot be deleted from my disk with > 2nd part of my code ? Why are you executing another program just to delete a file? >>> import os >>> os.remove('some/file.txt') -- From mmanns at gmx.net Sun Jun 1 14:17:36 2008 From: mmanns at gmx.net (Martin Manns) Date: Sun, 1 Jun 2008 20:17:36 +0200 Subject: pyspread 0.0.7 Message-ID: pyspread 0.0.7 has been released. -- New features: + CSV import dialog with preview grid Bug fixes: + setup.py now installs correctly into a sub-folder (tested for Linux and WinXP). -- About: pyspread is a spreadsheet that accepts a pure python expression in each cell. -- Highlights: + No non-python syntax add-ons + Access to python modules from cells + 3D grid + Numpy object array for representation of string entry into grid cell + Numpy object array for representation of eval function array + Cell access via slicing of numpy function array + X, Y, and Z yield current cell location for relative reference Requires: Python >=2.4, Numpy 1.0.4, and wxPython 2.8.7.1. License: GPL Project page: http://pyspread.sourceforge.net Best Regards Martin From saluk64007 at gmail.com Wed Jun 11 17:11:49 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Wed, 11 Jun 2008 14:11:49 -0700 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> <484e3526$0$30894$426a74cc@news.free.fr> <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> <783c55ec-a294-4600-91d9-4a0d78632c49@t12g2000prg.googlegroups.com> <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> <484f880c$0$6412$426a74cc@news.free.fr> Message-ID: On Wed, Jun 11, 2008 at 12:28 PM, Russ P. wrote: > > If Desthuilliers doesn't like my suggestion, then fine. If no other > Python programmer in the world likes it, then so be it. But do we > really need to get personal about it? Python will not be ruined if it > gets such a keyword, and Desthuilliers would be perfectly free to > continue using the leading-underscore convention if he wishes. Where > is the threat to his way of life? > Well, you have to understand that a lot of python programmers are refugees from the microsoft or sun worlds, where we were forced to do things a certain way, and often it was not in our opinion the best way, but there wasn't anything we could do about it. Some of these refugees are very experienced in that other world, and don't want to go back there. So proposing that python borrow these methods of control from the place we have fled from can feel threatening. Some people obviously take it more personally than others, but this is a general feeling a lot of python programmers share. Also I'm fairly certain you're not the first to mention this topic. Here's what the cookbook has to say: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/573442 Something like that is really your best bet. -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Thu Jun 19 12:37:16 2008 From: aahz at pythoncraft.com (Aahz) Date: 19 Jun 2008 09:37:16 -0700 Subject: dict order References: <4804032a-adef-4973-ae21-acc4ad2dce37@z72g2000hsb.googlegroups.com> <411fc353-dd54-4bbc-a72e-ddee66408313@c58g2000hsc.googlegroups.com> Message-ID: In article <411fc353-dd54-4bbc-a72e-ddee66408313 at c58g2000hsc.googlegroups.com>, wrote: > >Whoops > >for keys, values in dict_one.items(): > if keys in dict_two: > if values == dict_two[keys]: Except that "keys" implies a plural (meaning more than one thing); in a for loop, each iteration will have only one key. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From stefan_ml at behnel.de Thu Jun 26 13:58:04 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 26 Jun 2008 19:58:04 +0200 Subject: ask for a RE pattern to match TABLE in html In-Reply-To: References: Message-ID: <4863d8ac$0$27448$9b4e6d93@newsspool4.arcor-online.net> oyster wrote: > that is, there is no TABLE tag between a TABLE, for example >
1.the curd of milk separated from the whey and >>>> prepared >>>> >> in >>>> >> >> many ways as a food.
something with out table tag
> what is the RE pattern? thanks > > the following is not right > [^table]*? Why not use an HTML parser instead? Try lxml.html. http://codespeak.net/lxml/ Stefan From ian.g.kelly at gmail.com Fri Jun 13 16:13:32 2008 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 13 Jun 2008 14:13:32 -0600 Subject: Mapping None. Why? In-Reply-To: References: Message-ID: <3fc761710806131313y56889965ic41197b1ce266d0f@mail.gmail.com> On Fri, Jun 13, 2008 at 2:00 PM, Terry Reedy wrote: > filter(None, iterable) works the same way: None-> identity function, > The immediate reason is the Python has no builtin id(). > But apparently there is also historical precedent in the functional > community for this convention. Another way of viewing it is that filter(None, iterable) applies no function at all before testing the truth values, which does make some sense. With map, however, this is not strictly true. From s0suk3 at gmail.com Mon Jun 16 19:20:01 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Mon, 16 Jun 2008 16:20:01 -0700 (PDT) Subject: Please explain Python "__whatever__" construct. References: <02c8f509-2889-433b-a548-62ead677bd19@p39g2000prm.googlegroups.com> Message-ID: On Jun 16, 4:56 pm, bsag... at gmail.com wrote: > After a couple of weeks studying Python, I already have a few useful > scripts, including one that downloads 1500 Yahoo stock quotes in 6 > seconds. However, many things are puzzling to me. I keep on seeing > things like "__main__" in scripts. A more obscure example would be > "__add__" used in string concatenation. For example, I can use "Hello > "+"world (or just "Hello" "world") to join those two words. But I can > also use "Hello ".__add__("world"). When and why would I ever use > "__main__" or the many other "__whatever__" constructs? Generally, names with two leading and trailing underscores signal something "internal". Though the string "__main__" is rather something else: the variable __name__ is set to the string "__main__" when a script is run as a script (i.e., is not imported). The convention is also common in built-in object methods, such as the one you mentioned: the built-in type str's __add__() method. Personally, I usually try to avoid using such methods directly, because, as I said, they're rather for internal use or for special functionality. For example, when the expression '"hello" + "world"' is evaluated, it's likely that Python is calling one of the string's __add__() method internally to perform the "addition." So I'd recommend that you don't use those methods unless you absolutely need direct access to their functionality. From aafshar at gmail.com Wed Jun 4 08:34:28 2008 From: aafshar at gmail.com (Ali) Date: Wed, 4 Jun 2008 05:34:28 -0700 (PDT) Subject: Help need with subprocess communicate References: <0312b7e9-bffe-4360-bf3a-f5b3b26d243d@l64g2000hse.googlegroups.com> Message-ID: On Jun 3, 10:04?pm, rdab... at gmail.com wrote: > I'm trying to perform following type of operation from inside a python > script. > 1. Open an application shell (basically a tcl ) > 2. Run some commands on that shell and get outputs from each command > 3. Close the shell > > I could do it using communicate if I concatenate all my commands > ( separated by newline ) and read all the output in the end. So > basically I could do following sequence: > 1. command1 \n command2 \n command 3 \n > 2. Read all the output > > But I want to perform it interactively. > 1. command1 > 2. read output > 3. command2 > 4. read output ...... > > Following is my code: > > from subprocess import * > p2 = Popen('qdl_tcl',stdin=PIPE,stdout=PIPE) > o,e = p2.communicate(input='qdl_help \n qdl_read ?\n > qdl_reg_group_list ') > > Please suggest a way to perform it interactively with killing the > process each time I want to communicate with it. > > Thanks in advance, > -Rahul. It sounds like this may help: http://www.noah.org/wiki/Pexpect (pure python expect-like functionality) Ali From johnjsal at gmailNOSPAM.com Sat Jun 28 23:18:30 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sat, 28 Jun 2008 23:18:30 -0400 Subject: How do web templates separate content and logic? In-Reply-To: References: <486510f7$0$3007$c3e8da3@news.astraweb.com> Message-ID: <4866ff46$0$7333$607ed4bc@cv.net> bruno.desthuilliers at gmail.com wrote: > For which definitions of "content" and "logic" ??? > > The point of mvc is to keep domain logic separated from presentation > logic, not to remove logic from presentation (which just couldn't > work). Templating systems are for presentation logic. Whether they > work by embedding an existing complete programmation language or by > providing they're own specialised mini-language (or a mix of both) is > not the point here IMHO. No, I don't mean presentation logic at all. I mean something along the lines of combining HTML (which is what I refer to as "content") and Python (which is what I meant by "logic"). So for example, if you have code like this (and this isn't necessarily proper code, I'm just making this up, but you'll see what I mean):

Big Important Topic

This is where I say something important about

    % for topic in topics:
  1. ${topic}
Humph, I just made up that example to make the point that when you no longer have pure HTML, but instead have programmatic logic (Python) mixed in with the HTML, then you are mixing content and logic. However, as soon as I finished typing it out, it occurred to me that even the so-called logic in this example is really only producing more "content" to display. So maybe my question was a little premature. Or could it just be that this is a *good* way to mix HTML and Python, and there are other ways which may be bad? (For example, connecting to a database, like Sebastian's example. That definitely seems out of place in an HTML file.) From torriem at gmail.com Sun Jun 1 22:36:43 2008 From: torriem at gmail.com (Michael Torrie) Date: Sun, 01 Jun 2008 20:36:43 -0600 Subject: Good grid + calendar, etc.? In-Reply-To: References: <9c80b15f-791e-4933-984b-fd8bf0bafef1@m36g2000hse.googlegroups.com> Message-ID: <48435CBB.8040701@gmail.com> Gilles Ganault wrote: >> The grid can be quite advanced. Did you look at the wxPython demo? Or >> Dabo? > > Yes, but although the basic wigets are just fine, wxGrid looks a bit > like the basic TStringGrid in Delphi, ie. it's pretty basic so that > several vendors came up with enhanced alternatives. But maybe I > haven't played with it long enough. You don't say anything about looking at Dabo. If you are serious about writing real business apps, then you really do need to look at Dabo. While it's GUI objects may not be quite up to what you need, the framework itself is very critical to developing business apps. From your posts in this thread, it sounds to me like Dabo would greatly help you build the back-end database and business logic at least. Despite what you say about web interfaces in business applications, from what I've seen it's all going that way. PeopleSoft, etc. Everything is about web-delivered apps, with web services and custom integration these days. HTML/CSS/Ajax and a bit of Silverlight or Flash for the super custom widgets is actually competing *very* well with the traditional Delphi business widgets. True this requires you to maintain "code" in multiple languages, but frankly that's the cost of doing business. Business apps are *complicated* to build. When it does come down to it, you'll probably have to build some of your own widgets. PyQT makes this quite easy. Canvases, HTML widgets, etc. If you're going to all the work of developing a complete business app, then the work that goes into developing custom GUI components isn't that bad, compared. Since your target audience appears to be windows users, though, I'd second the notion of using IronPython and leveraging SWF .NET widgets. In theory this would run fine under Mono on Unix if you wanted to branch out. From mishok13 at gmail.com Sun Jun 15 06:48:54 2008 From: mishok13 at gmail.com (Andrii V. Mishkovskyi) Date: Sun, 15 Jun 2008 13:48:54 +0300 Subject: bpython - fancy Python shell In-Reply-To: References: Message-ID: <192840a00806150348r7189a8afq9648c93b18264374@mail.gmail.com> 2008/6/15, Bob Farrell : > > I released this a while ago but did some work recently to fix some bugs > so I thought I may as well post it here. To quickly summarise: > In-line syntax highlighting > Auto complete with suggestions as you type > Pastebin stuff, save to file > "Rewind" feature to jump back a line if you mess up (don't ask how it > works, please ;) > > You can get it here: > http://www.noiseforfree.com/bpython/ > > There's info about git repos and what have you there, and apparently > it's also in some real distro repos, but I don't know the details. > > Oh, and you'll need pygments and pyparsing, and it doesn't work on > Windows (heard good reports about it working fine on a Mac though). Great work, bobf. :) I've been using bpython from time to time for a month now, so I can only appreciate the fact that bpython is developing. I think that with that speed of development bpython will substitute ipython as my everyday python console in the near future (3-4 months). P.S. I think you should of cc'd this announcement to python-announce-list. ;) > -- > Bob Farrell > -- > http://mail.python.org/mailman/listinfo/python-list > -- Wbr, Andrii Mishkovskyi. He's got a heart of a little child, and he keeps it in a jar on his desk. From ptmcg at austin.rr.com Tue Jun 3 16:36:49 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 3 Jun 2008 13:36:49 -0700 (PDT) Subject: parser recommendation References: <686de663-94d2-4e8b-b079-197793d0a8cc@2g2000hsn.googlegroups.com> Message-ID: <8d2bb123-9e2b-4947-a93a-5359dbb5b29d@t54g2000hsg.googlegroups.com> On Jun 3, 12:34?pm, "Filipe Fernandes" wrote: > On Tue, Jun 3, 2008 at 10:41 AM, Paul McGuire wrote: > But I do have more questions... when reading the ply.py header (in > 2.5) I found the following paragraph... > > # The current implementation is only somewhat object-oriented. The > # LR parser itself is defined in terms of an object (which allows multiple > # parsers to co-exist). ?However, most of the variables used during table > # construction are defined in terms of global variables. ?Users shouldn't > # notice unless they are trying to define multiple parsers at the same > # time using threads (in which case they should have their head examined). > > Now, I'm invariably going to have to use threads... ?I'm not exactly > sure what the author is alluding to, but my guess is that to overcome > this limitation I need to acquire a thread lock first before > "defining/creating" a parser object before I can use it? > > Has anyone ran into this issue....? ?This would definitely be a > showstopper (for PLY anyway), if I couldn't create multiple parsers > because of threads. ?I'm not saying I need more than one, I'm just not > comfortable with that limitation. > > I have a feeling I'm just misunderstanding since it doesn't seem to > hold you back from creating multiple parsers under a single process. > > filipe You can use pyparsing from any thread, and you can create multiple parsers each running in a separate thread, but you cannot concurrently use one parser from two different threads. Some users work around this by instantiating a separate parser per thread using pickle to quickly construct the parser at thread start time. -- Paul From kretik at yahoo.com Tue Jun 17 00:53:21 2008 From: kretik at yahoo.com (kretik) Date: Mon, 16 Jun 2008 21:53:21 -0700 Subject: string.Template.delimiter cannot be overriden? Message-ID: <4rH5k.2032$to3.1384@newsfe15.phx> I've been trying to coax this class to use something other than the default '$' but it seems setting it to something else has no discernible effect. Is it necessary to inherit from the class to do this? I've only been using Python for a couple of weeks so I'm not sure what the best approach is here. Thanks in advance. From sturlamolden at yahoo.no Wed Jun 4 14:06:33 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 4 Jun 2008 11:06:33 -0700 (PDT) Subject: multiprocessing module (PEP 371) Message-ID: <877a5774-d3cc-49d3-bb64-5cab8505a419@m3g2000hsc.googlegroups.com> I sometimes read python-dev, but never contribute. So I'll post my rant here instead. I completely support adding this module to the standard lib. Get it in as soon as possible, regardless of PEP deadlines or whatever. I don't see pyprocessing as a drop-in replacement for the threading module. Multi-threading and multi-processing code tend to be different, unless something like mutable objects in shared memory is used as well (cf. Python Shared Objects). If this limitation can educate Python programmers to use queues instead of locks and mutable objects, even multi-threaded Python programs may actually benefit. Some API differences between threading and multiprocessing do not matter. Programmers should not consider processes as a drop-in replacement for threads. One limitation not discussed on python-dev is the lack of fork on Win32. This makes the pyprocessing module particularly inefficient at creating processes on this platform, as it depends on serializing (pickling and de-pickling) a lot of Python objects. Even a non-COWfork would be preferred. I will strongly suggest something is done to add support for os.fork to Python on Windows. Either create a full cow fork using ZwCreateProcess (ntdll.dll does support COWforking, but Win32 API does not expose it), or do the same as Cygwin is doing to fork a process without COW. Although a non-cow fork a la Cygwin is not as efficient as a fork on Linux/FreeBSD/Unix, it is still better than what pyprocessing is doing. From alexnbryan at gmail.com Wed Jun 25 19:07:11 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Wed, 25 Jun 2008 18:07:11 -0500 Subject: urllib tutorial and help Message-ID: <9212BFFF-759E-4421-AE87-353E0E9285AC@gmail.com> So I need to start learning about the urllib class, and am wondering where is a good place to start. I really don't want to go buy a book about it, but I was wondering if there is any good online tutorials or anything like that, that will help me out on connecting apps to the web, that specialize in the urllib class. Ideas? From bsagert at gmail.com Wed Jun 18 13:10:17 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Wed, 18 Jun 2008 10:10:17 -0700 (PDT) Subject: Importing module PIL vs beautifulSoup. Message-ID: I downloaded BeautifulSoup.py from http://www.crummy.com/software/BeautifulSoup/ and being a n00bie, I just placed it in my Windows c:\python25\lib\ file. When I type "import beautifulsoup" from the interactive prompt it works like a charm. This seemed too easy in retrospect. Then I downloaded the PIL (Python Imaging Library) module from http://www.pythonware.com/products/pil/. Instead of a simple file that BeautifulSoup sent me, PIL is an .exe that installed itself in c: \python25\lib\site-packages\PIL\. However it won't load by typing "import pil". I know I am supposed to RTFM, but a Google search has not led to the holy grail that Monty Python found. I realize that PIL is a package as opposed to a simple script (and it does not include a readme file). Thanks in advance for any help. From rurpy at yahoo.com Tue Jun 3 20:03:45 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Tue, 3 Jun 2008 17:03:45 -0700 (PDT) Subject: parser recommendation References: <686de663-94d2-4e8b-b079-197793d0a8cc@2g2000hsn.googlegroups.com> <8d2bb123-9e2b-4947-a93a-5359dbb5b29d@t54g2000hsg.googlegroups.com> Message-ID: On Jun 3, 2:55 pm, "Filipe Fernandes" wrote: > I haven't given up on pyparsing, although I'm now heavily leaning > towards PLY as an end solution since lex and yacc parsing is available > on other platforms as well. Keep in mind that PLY's "compatibility" with YACC is functional, not syntactical. That is, you can not take a YACC file, replace the actions with Python actions and feed it to PLY. It's a shame that the Python world has no truly YACC compatible parser like YAPP in the Perl world. From python at rcn.com Tue Jun 17 01:20:23 2008 From: python at rcn.com (Raymond Hettinger) Date: Mon, 16 Jun 2008 22:20:23 -0700 (PDT) Subject: string.Template.delimiter cannot be overriden? References: <4rH5k.2032$to3.1384@newsfe15.phx> Message-ID: <35e212be-e85b-41fd-90c2-f90959053232@l28g2000prd.googlegroups.com> On Jun 16, 9:53?pm, kretik wrote: > I've been trying to coax this class to use something other than the > default '$' but it seems setting it to something else has no discernible > effect. Is it necessary to inherit from the class to do this? Yes, subclassing is the intended way to produce variants of Template with a different delimiter. >>> import string >>> class PercentTemplate(string.Template): delimiter = "%" >>> s = PercentTemplate('Move %piece to %position') >>> s.substitute(piece='pawn', position='K4') 'Move pawn to K4' Raymond From esugreg at gmail.com Sat Jun 7 00:51:12 2008 From: esugreg at gmail.com (gms) Date: Fri, 6 Jun 2008 21:51:12 -0700 (PDT) Subject: Needing python experts to help with a problem Message-ID: Hello, I have the following list: [{'count': u'2', 'manu': }, {'count': u'4', 'manu': }, {'count': u'2', 'manu': }, {'count': u'2', 'manu': }] My current list currently contains four dictionaries. They are: {'count': u'2', 'manu': } {'count': u'4', 'manu': } {'count': u'2', 'manu': } {'count': u'2', 'manu': } I need to create a list for each specific Manufacturer. Since I have two dictionaries that have 'Manu2' as it's manufacturer. I will need some code that will create the following from the list above: [{'count': u'2', 'manu': }] [{'count': u'4', 'manu': },{'count': u'2', 'manu': }] [{'count': u'2', 'manu': }] The reason for this is because I want to send one email to each manufacturer. In this case I would send two emails to Manu2 because I have two dictionaries that have Manu2 as the manufacturer. That is why I need to create a separate list for each manufacturer. Any help on on how best to do this would be greatly appreciated! Thanks From ramb at sonic.net Sat Jun 14 03:50:55 2008 From: ramb at sonic.net (ramb at sonic.net) Date: Sat, 14 Jun 2008 00:50:55 -0700 Subject: ANN: pytoken 1.0 - native 86 machine code scanner generator Message-ID: I am pleased to announce the 1.0 version of pytoken. It is available here: http://code.google.com/p/pytoken/downloads/list What is pytoken Pytoken is a scanner generator. Given an input specification - a bunch of regular expressions - pytoken will generate x86 machine code that recognizes those regular expressions. Pytoken will be most useful for programmers that want to parse complex text files. Pytoken has separate objects for scanners and buffers. Here is a simple example: import pytoken lexer_obj = pytoken.lexer() lexer_obj.add_pattern("a", 1) lexer_obj.add_pattern("b", 2) lexer_obj.compile_to_machine_code() buf = pytoken.lexer_state() buf.set_input("ab") tok = lexer_obj.get_token(buf) assert tok == 1 tok = lexer_obj.get_token(buf) assert tok == 2 Pytoken has been written in a portable fashion - it is designed to support multiple CPU types, even though only the x86 (32 bit) is supported now. -Ram From aahz at pythoncraft.com Wed Jun 25 14:16:40 2008 From: aahz at pythoncraft.com (Aahz) Date: 25 Jun 2008 11:16:40 -0700 Subject: Threads, GIL and re.match() performance References: Message-ID: In article , Mirko Dziadzka wrote: > >I understand that the C implementation of Python use a global interpreter >lock to avoid problems, so doing CPU bound tasks in multiple threads >will not result in better performance on multi-CPU systems. > >However, I assumed that calls to (thread safe) C Library functions >release the global interpreter lock. Generally speaking that only applies to I/O calls. >Today I checked the performance of some slow re.match() calls and found, >that the do not run in parallel on a multi-CPU system. > >1) Is there a reason for this? >2) Is the regex library not thread-safe? >3) Is it possible, to release the GIL in re.match() to > get more performance? Theoretically possible, but the usual rule applies: patches welcome -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From duncan.booth at invalid.invalid Mon Jun 23 11:00:07 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Jun 2008 15:00:07 GMT Subject: -1/2 References: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> <2231475d-c1d6-45de-9ccb-ab82e923e902@x1g2000prh.googlegroups.com> Message-ID: Lie wrote: > On Jun 23, 1:32?am, "Serve Lau" wrote: >> What is the expected result of -1/2 in python? > > > Operator precedence: > Both python 2 and 3 follows the same rule for operator precedence, > see: > http://www.ibiblio.org/g2swap/byteofpython/read/operator-precedence.htm > l . In -1/2, unary negative takes precedence, then division, i.e. it's > interpreted as ((-1) / 2). > > Py3k and Python 2 differences: > Before Python 3, integer division is always rounds to minus infinity. > In Python 3, integer division yields floats. To use integer division > in Python 3, you use // operator. > > Simple answer: > Python 2: (-1)/2 = round(-0.5) = -1 > Py3k: (-1)/2 = float(-1) / float(2) = -0.5 > Python 2.x gives -1 or -0.5 depending on the division mode in operation and for -1 may also generate a deprecation warning: C:\>python25\python -Qnew -c "print -1/2" -0.5 C:\>python25\python -Qwarn -c "print -1/2" -c:1: DeprecationWarning: classic int division -1 -- Duncan Booth http://kupuguy.blogspot.com From gabriel.rossetti at arimaz.com Fri Jun 13 02:33:52 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Fri, 13 Jun 2008 08:33:52 +0200 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: References: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> Message-ID: <485214D0.5010907@arimaz.com> Duncan Booth wrote: > Mike Orr wrote: > > >> That's a misunderstanding of classes vs instances. If you have an >> instance of MyClass(Superclass), there is one instance but several >> classes. The instance is of MyClass; there is no instance of >> Superclass. 'self' has a .__class__ attribute because it's an >> instance, but MyClass and Superclass do not because they're already >> classes. >> > > Classes are also instances, usually they are instances of the type 'type' > (and even 'type' is an instance of itself): > > Ok, I didn't know that >>>> class SuperClass(object): pass >>>> > > >>>> SuperClass.__class__ >>>> > > >>>> type(SuperClass) >>>> > > >>>> type.__class__ >>>> > > > Old style classes don't have a class attribute, but you shouldn't be using > old style classes anyway and so long as you use > type(x) > to access its class rather than accessing the __class__ attribute directly > that doesn't particularly matter. > > Yes, I don't use old style classes From dstromberglists at gmail.com Fri Jun 13 14:20:10 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Fri, 13 Jun 2008 18:20:10 GMT Subject: Python Socket programming References: Message-ID: On Fri, 13 Jun 2008 21:59:06 +0530, srinivasan srinivas wrote: > Hi, > I am going to do some socket related programming in Python. Before that, > I wish to know the Gotchas of Python Scoket Programming. Can anyone send > me any link that satisfies my needs?? Thanks, > Srini > > > Explore your hobbies and interests. Go to > http://in.promos.yahoo.com/groups/ IMO, there aren't many. Some methods require a tuple where you might think they shouldn't need one. And you have to be careful not to make assumptions about, say, writing n bytes in your server and reading n bytes in the client - you may not get all n right away. TCP is free to split or aggregate your chunks as it sees fit. So you need some sort of record terminator or something, rather than assuming transfer sizes will be preserved by TCP. Often they will be preserved, but they aren't guaranteed to be. But this is true of just about any language with a socket interface. For the latter issue (the chunk size thing), I put together http:// stromberg.dnsalias.org/~strombrg/bufsock.html From bruno.42.desthuilliers at websiteburo.invalid Wed Jun 18 03:34:40 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 18 Jun 2008 09:34:40 +0200 Subject: Name lookup inside class definition In-Reply-To: <1c1a1181-905c-4401-ae00-36b3fabebab9@v1g2000pra.googlegroups.com> References: <1c1a1181-905c-4401-ae00-36b3fabebab9@v1g2000pra.googlegroups.com> Message-ID: <4858ba90$0$16043$426a74cc@news.free.fr> WaterWalk a ?crit : > Hello. Consider the following two examples: > class Test1(object): > att1 = 1 > def func(self): > print Test1.att1 // ok or print type(self).att1 > class Test2(object): > att1 = 1 > att2 = Test2.att1 // NameError: Name Test2 is not defined > > It seems a little strange. Why a class name can be used in a method > while cannot be used in the class block itself? class is an executable statement. The whole "class" block is first eval'd, then the class object is created and bound to it's name. So when the function is called, the class statement has already been executed, the class object created and bound to the name Test1. But when the att2=Test2.att1 is executed, the class object doesn't yet exists, nor the name Test2. Anyway, you don't need to refer to the class name here: class Toto(object): titi = 1 toto = titi + 1 From gert.cuykens at gmail.com Sat Jun 28 22:08:59 2008 From: gert.cuykens at gmail.com (gert) Date: Sat, 28 Jun 2008 19:08:59 -0700 (PDT) Subject: pxssh submit su commands = very very slow References: <39f89067-8ee6-470a-92ce-77b46a344f37@34g2000hsf.googlegroups.com> Message-ID: <48196ce2-42bd-437f-b914-c0e68e0097d3@y21g2000hsf.googlegroups.com> this does the same except 100 times faster ? I don't understand the logic about the prompt, its not the same as the output from the bash shell ? root at r12276:~# cat ssh2.py import pexpect import sys child = pexpect.spawn("ssh gert at 127.0.0.1") #child.logfile = sys.stdout i = child.expect(['assword:', r'yes/no'],timeout=120) if i==0: child.sendline('123') elif i==1: child.sendline('yes') child.expect('assword:', timeout=120) child.sendline('123') child.expect('gert at rxxxx.ovh.net: ~') print child.before child.sendline('ls -l') child.expect('gert at rxxxx.ovh.net:') print child.before child.sendline('su') child.expect('assword:') child.sendline('123') child.expect('gert at rxxxx.ovh.net: /srv/www/gert') print child.before child.sendline('ls -l') child.expect('root at rxxxx.ovh.net:') print child.before From Lie.1296 at gmail.com Wed Jun 18 15:57:44 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 18 Jun 2008 12:57:44 -0700 (PDT) Subject: python string comparison oddity References: Message-ID: <3ebd170e-8686-4bb4-9e47-0fba2179feb3@p39g2000prm.googlegroups.com> On Jun 19, 2:26?am, Faheem Mitha wrote: > Hi everybody, > > I was wondering if anyone can explain this. My understanding is that 'is' > checks if the object is the same. However, in that case, why this > inconsistency for short strings? I would expect a 'False' for all three > comparisons. This is reproducible across two different machines, so it is > not just a local quirk. I'm running Debian etch with Python 2.4.4 (the > default). > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Thanks, Faheem. > > In [1]: a = '--' > > In [2]: a is '--' > Out[2]: False > > In [4]: a = '-' > > In [5]: a is '-' > Out[5]: True > > In [6]: a = 'foo' > > In [7]: a is 'foo' > Out[7]: True Yes, this happens because of small objects caching. When small integers or short strings are created, there are possibility that they might refer to the same objects behind-the-scene. Don't rely on this behavior. From geonomica at gmail.com Sat Jun 14 11:39:47 2008 From: geonomica at gmail.com (gianluca) Date: Sat, 14 Jun 2008 08:39:47 -0700 (PDT) Subject: #define in swig Message-ID: <61886d78-f769-48d8-94f5-5a7d010a879b@56g2000hsm.googlegroups.com> I've a problem with python wrapper of C library. In a library's file there are #define istruction but I can't access it from python. Other functio works correctly. The define istruction is like this: #define START_OF_D _table_element=_mainsys- >matD,_table_end=_table_element+Dsize(_mainsys) #define START_OF_X _table_element=_mainsys- >matX,_table_end=_table_element+_mainsys->matXsize #define START_OF_MAT(set,num) _table_element=(set),_table_end=_table_element+(num)*_mainsys- >setAsize #define END_OF_MAT (_table_element<_table_end) #define NEXT_OF_MAT _table_element+=_mainsys->setAsize #define ELEM_OF_MAT _table_element #define ElemOfRule(rules,num,attr) (rules)[(num)*(_mainsys- >attributes_num)+(attr)] thanks Gianluca From ironfroggy at socialserve.com Sun Jun 15 13:20:38 2008 From: ironfroggy at socialserve.com (Calvin Spealman) Date: Sun, 15 Jun 2008 13:20:38 -0400 Subject: Iterate creating variables? In-Reply-To: <6b671d56-1060-4fd4-86ca-b36a1e4c936f@m44g2000hsc.googlegroups.com> References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> <6b671d56-1060-4fd4-86ca-b36a1e4c936f@m44g2000hsc.googlegroups.com> Message-ID: That smells bad the same was the eval() usage in the thread "Hard to understand 'eval'". This is only one pythoners opinion, of course. On Jun 13, 2008, at 3:29 PM, Jason Scheirer wrote: > for x in xrange(1, 26): > setattr(self, 'checkbox_%i' % x, ...) > -- > http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Thu Jun 26 19:27:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 26 Jun 2008 16:27:35 -0700 (PDT) Subject: Need help capturing output of re.search References: <771ef68a-d976-4f61-a3cc-7ed56fddc756@k37g2000hsf.googlegroups.com> Message-ID: <9757288e-0b48-46ee-8fd0-0adf36bbd710@p39g2000prm.googlegroups.com> On Jun 27, 8:31 am, joemacbusin... at yahoo.com wrote: > Hi - > > I need help capturing the output of a RegEx search. > I dont understand why this conditional fails. > > Here is the code: > > #================================= start snip > ====================================== > #!/usr/local/bin/python > > import os > import re > > dirName = '/home/user/bin/logs' > os.chdir(dirName) > files = os.listdir(dirName) > for myFile in files: > # print 'checking ...', myFile > reCheck = '' > reCheck = re.search(r'\bCC_', myFile) > # print 'reCheck = ', '=', reCheck, '=' > > if reCheck == "None": > print myFile, ' ..... does not qualify' > else: > print ' ', myFile, 'qualifies...', reCheck > > #================================= end snip > ====================================== > > The problem is that reCheck never == None. > So all of the files "qualify". My understanding of the > re.search (re.search(r'\bCC_', myFile)) is ... > 1) give me only files that start with a word boundary (\b) > 2) followed by a (CC_) > 3) in myFile > > Why doesn't the output of the re.search load reCheck with valid data? > (like "None") Because "None" is not "valid data" in this case. re.search returns None or a MatchObject instance. >>> type(None) >>> type("None") >>> None == "None" False >>> You may like to read this: http://www.amk.ca/python/howto/regex/ If you want to check for strings that start with some condition, you need re.match, not re.search. You don't need the '\b'; re.match(r'CC_', filename) would do the job. But then so would filename.startswith('CC_') HTH, John From larry.bates at websafe.com` Thu Jun 5 08:06:52 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 05 Jun 2008 07:06:52 -0500 Subject: line continuation for lines ending in "and" or "or" In-Reply-To: References: <90ee8b5d-1509-4463-aaab-f712f7e72d4b@j33g2000pri.googlegroups.com> <0d723e6d-f81b-4545-b406-fc60b20c5433@u6g2000prc.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: > On Wed, 4 Jun 2008 21:50:19 -0700 (PDT), "Russ P." > declaimed the following in comp.lang.python: > >> Darnit! You're right. I've been reading up on Scala lately, and I >> guess I got confused. Well, it wouldn't be a bad idea for Python to do >> what I thought it did, *plus* what I said it ought to do. >> > Is it that much of a difficulty to start multiline expresssions with > a (... > > That already covers all the conditions you want... Or just using a > line ending of \ > (which I find less appealing than the (... ) I suppose this is a matter of "taste". I find using parenthesis to trigger line continuations undesirable. Lines ending in backslash are explicit and easy to mentally parse. -Larry From andrei.avk at gmail.com Mon Jun 9 20:53:58 2008 From: andrei.avk at gmail.com (Rainy) Date: Mon, 9 Jun 2008 17:53:58 -0700 (PDT) Subject: Separators inside a var name References: Message-ID: On Jun 9, 5:34?pm, Alexander Schmolck wrote: > Rainy writes: > > I have a stylistic question. In most languages words in var. name are > > separated by underscores or cap letters, resulting in var names like > > var_name, VarName and varName. I don't like that very much because all > > 3 ways of naming look bad and/or hard to type. From what I understand, > > scheme can have variables like var-name. I'm curious about reasons > > that python chose to disallow this. > > Legacy -- mathematical notation is broken and conflates negation and > subtraction (causing all sorts of annoyances including this one). Thus if you > want to be able to name a variable ``a-b`` you either have to write ``a - b`` > to disambiguate subtracton from the variable name ``a-b`` or you need to chose > a different symbol for subtraction (writing "a ~ b" would likely be the best > choice). ~ is terrible, imho, I'd much rather disallow a - b for subtraction (and all math ops). > > > Another question I have is what other languages allow this naming scheme? > > All lisps. Dylan. Rebol. Postscript. Forth. I'm sure there are a few others. > > > Were there any languages that allowed space as a separator? > > Sure. > > > What would be a practical way to separate variables from keywords in that > > case? > > Lisp allows you to use pretty much anything in a variable name, you just have > to quote it, either > > ?like\ this > > or > > ?|like this| This is actually pretty nice. I think I like this much better than C/Java/etc convention. I wouldn't use pipes but I'd pick something that's easy to type and is nicely readable. Not sure what.. > > > "some long variable name", 'just a string', or maybe using 2 spaces: one var > > + other var + third var ? I think being able to easy have very long names > > for vars that are easy to type would be a fairly significant advantage. > > I assume you haven't programmed too much? The problem with long names is that > they obscure structure, so they are only worthwhile for rarely used and fairly > obscure concepts where the added descriptiveness yields a net advantage. Only about 8 years, but it may be that I'm just not very good ;-). I'm not sure that's the case. My problem with long names is that they look ugly, and the longer they are, the uglier they look when you use underscores or caps. Other than that, I'd like to have an option to use longer names. Maybe it won't be used all the time, but still.. > > > I know I'm probably being too obsessive about this, but that didn't stop me > > from posting. Comments? > > I think you're right -- the common naming convention's suck and "python's" is > particularly bad (HtmlFrob HTMLFrob htmlFrob html_frob htmlfrob HTML_FROB > HTMLFROB -- which one will it be? No way to know without looking at the rest > of the code, the only consistency is that the last two are mostly used for > constants; everything else is completely up for grabs). You'd better get used > to it though, it's become "standardized". > > 'as Well, I agree, this is terrible. If I were Guido I'd make a very explicit rule that a certain naming scheme is preferred and other schemes are very bad. And I'd get it in the beginning of official tutorial, libref, in books, etc. Mostly it's ClassName and func_name and var_name and so on, but very often it's something else. BUT even if that was the rule and everyone followed it, though it would be much better than what we have now, it would still offend my taste. Just saying! From noreply at yahoo.com Mon Jun 30 10:45:18 2008 From: noreply at yahoo.com (Kirk) Date: 30 Jun 2008 14:45:18 GMT Subject: Freeze problem with Regular Expression References: <6cf614F3f8ocoU1@mid.individual.net> <0e1a9726-cc1d-4bd2-b0ba-b2bcc1c27ee8@f24g2000prh.googlegroups.com> Message-ID: <6cs9rtF3g9fsvU1@mid.individual.net> On Wed, 25 Jun 2008 15:29:38 -0700, John Machin wrote: > Several problems: Ciao John (and All partecipating in this thread), first of all I'm sorry for the delay but I was out for business. > (1) lose the vertical bars (as advised by others) (2) ALWAYS use a raw > string for regexes; your \s* will match on lower- case 's', not on > spaces right! thanks! > (3) why are you using findall on a pattern that ends in "$"? Yes, you are right, I started with a different need and then it changed over time... > (6) as remarked by others, you haven't said what you are trying to do; I reply here to all of you about such point: that's not important, although I appreciate very much your suggestions! My point was 'something that works in Perl, has problems in Python'. In respect to this, I thank Peter for his analysis. Probably Perl has a different pattern matching algorithm. Thanks again to all of you! Bye! -- Kirk From larry.bates at websafe.com` Mon Jun 30 19:21:10 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 30 Jun 2008 18:21:10 -0500 Subject: The Yield statement In-Reply-To: References: Message-ID: Alex Bryan wrote: > Okay, so i don't really understand the Yield thing and i know it is > useful. I've read a few things about it but it is all programming jargon > and so basically it is hard for me to understand. So can anyone give me > a description or link me to a site that has a good definition and/or > examples of it? If you could I would really appreciate it. Use yield when you want the function to act as a generator. That is each time it is called it generates a response and returns it, but leaves its state intact so that the next time you call it, it can pick up where it left off and continue on. Best example I ever saw is the code that implements os.walk() function: def walk(top, topdown=True, onerror=None): """ Example: from os.path import join, getsize for root, dirs, files in walk('python/Lib/email'): print root, "consumes", print sum([getsize(join(root, name)) for name in files]), print "bytes in", len(files), "non-directory files" if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories """ from os.path import join, isdir, islink try: names = listdir(top) except error, err: if onerror is not None: onerror(err) return dirs, nondirs = [], [] for name in names: if isdir(join(top, name)): dirs.append(name) else: nondirs.append(name) if topdown: yield top, dirs, nondirs for name in dirs: path = join(top, name) if not islink(path): for x in walk(path, topdown, onerror): yield x if not topdown: yield top, dirs, nondirs Actually this code uses yield and is recursive. Pretty neat. -Larry From gherron at islandtraining.com Wed Jun 18 02:35:32 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 17 Jun 2008 23:35:32 -0700 Subject: Ternary operator alternative in Ptyhon In-Reply-To: References: Message-ID: <4858ACB4.70109@islandtraining.com> kretik wrote: > I'm sure this is a popular one, but after Googling for a while I > couldn't figure out how to pull this off. > > Let's say I have this initializer on a class: > > def __init__(self, **params): > > I'd like to short-circuit the assignment of class field values passed > in this dictionary to something like this: > > self.SomeField = \ > params.has_key("mykey") ? params["mykey"] : None) For years, Python did not have such a thing, but recent versions support the syntax a if c else b In spite of the odd ordering of that parts, they are executed (or not) just as you like. self.SomeField = params["mykey"] if params.has_key("mykey") else None Gary Herron > > Obviously I know this is not actual Python syntax, but what would be > the equivalent? I'm trying to avoid this, basically: > > if params.has_key("mykey"): > self.SomeField = params["mykey"] > else: > self.SomeField = None > > This is not a big deal of course, but I guess my main goal is to try > and figure out of I'm not missing something more esoteric in the > language that lets me do this. > > Thanks in advance. > -- > http://mail.python.org/mailman/listinfo/python-list From martin at v.loewis.de Thu Jun 19 15:40:03 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 19 Jun 2008 21:40:03 +0200 Subject: Python-3.0b1 build fails on Linux : _gestalt In-Reply-To: <6bupftF3d2d0kU1@mid.dfncis.de> References: <6bupftF3d2d0kU1@mid.dfncis.de> Message-ID: <485ab613$0$31976$9b622d9e@news.freenet.de> > Failed to find the necessary bits to build these modules: > _gestalt > > Looking at setup.py it seems that module '_gestalt' > is only needed on Darwin but my build on Linux fails > nevertheless. Why do you think the build fails (i.e. what specific error message makes you believe it failed)? Regards, Martin From carsten.haese at gmail.com Wed Jun 11 08:40:28 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Wed, 11 Jun 2008 08:40:28 -0400 Subject: problems with opening files due to file's path In-Reply-To: References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> Message-ID: <1JP3k.6889$jI5.5927@flpi148.ffdc.sbc.com> Alexnb wrote: > I don't think you understand it doesn't matter how the variable gets there But it *does* matter. Compare this: py> filename = "C:\Somewhere\01 - Some Song.mp3" py> print filename C:\Somewhere - Some Song.mp3 To this: py> filename = raw_input("Enter the filename: ") Enter the filename: C:\Somewhere\01 - Some Song.mp3 py> print filename C:\Somewhere\01 - Some Song.mp3 Note that the "\01" in the first case seems to have disappeared, whereas in the second case it's preserved. Now, if you want us to help you, please post your ACTUAL code with a description of the ACTUAL problem. -- Carsten Haese http://informixdb.sourceforge.net From duncan.booth at invalid.invalid Thu Jun 19 09:09:47 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Jun 2008 13:09:47 GMT Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <1ea1731d-9de9-4e73-9c08-e9f5572b9fd6@t54g2000hsg.googlegroups.com> <1a8797c6-a165-49b1-82de-94a6054cf856@z16g2000prn.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > My memory value comes from experiments, I have created a little > program like this: > > from memory import memory > > def main(N): > m1 = memory() > print m1 > > d = {} > for i in xrange(N): > d[i] = None > > m2 = memory() > print m2 > print float((m2 - m1) * 1024) / N > main(20000000) > > Where memory is a small module of mine that calls a little known > program that tells how much memory is used by the current Python > process. The results for that run n=20000000 are (first two numbers > are kilobytes, the third number is byte/pair): > > 1876 > 633932 > 32.3612672 > > It means to store 20_000_000 pairs it requires about 647_000_000 > bytes, Python 2.5.2, on Win. > What do you get if you change the output to exclude the integers from the memory calculation so you are only looking at the dictionary elements themselves? e.g. def main(N): keys = range(N) m1 = memory() print m1 d = {} for i in keys: d[i] = None m2 = memory() print m2 print float((m2 - m1) * 1024) / N main(20000000) -- Duncan Booth http://kupuguy.blogspot.com From cokofreedom at gmail.com Mon Jun 30 05:48:47 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 30 Jun 2008 02:48:47 -0700 (PDT) Subject: Why is recursion so slow? References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> <5504f9ac0806290703h1bf44639jbfe5331c4a2d1369@mail.gmail.com> Message-ID: <5dbba5c9-1855-47cc-979e-a55750bb88f7@a70g2000hsh.googlegroups.com> In case anyone is interested... # Retrieved from: http://en.literateprograms.org/Fibonacci_numbers_(Python)?oldid=10746 # Recursion with memoization memo = {0:0, 1:1} def fib(n): if not n in memo: memo[n] = fib(n-1) + fib(n-2) return memo[n] # Quick exact computation of large individual Fibonacci numbers def powLF(n): if n == 1: return (1, 1) L, F = powLF(n/2) L, F = (L**2 + 5*F**2) >> 1, L*F if n & 1: return ((L + 5*F)>>1, (L + F) >>1) else: return (L, F) def fib(n): return powLF(n)[1] From fanweixiao at gmail.com Sat Jun 28 15:46:25 2008 From: fanweixiao at gmail.com (weixiao.fan) Date: Sat, 28 Jun 2008 12:46:25 -0700 (PDT) Subject: how to upgrade python on centOS 5.2 Message-ID: <7456ecc5-0620-4b6a-929e-5db7dcd60555@u36g2000prf.googlegroups.com> CentOS5.2 installed python2.4 by default, but google app engine need 2.5+ version. I download the tar package from python.org then run ./ configure,make,make install and some other work. but I can't use it in gae with exceptions like can't use import time ... Is there a detailed guide on how to upgrade python to 2.5+ version on centos 5.2? thank you. From fake.mail at noone.be Sun Jun 22 05:44:13 2008 From: fake.mail at noone.be (Josip) Date: Sun, 22 Jun 2008 11:44:13 +0200 Subject: Storing value with limits in object Message-ID: I'm trying to limit a value stored by object (either int or float): class Limited(object): def __init__(self, value, min, max): self.min, self.max = min, max self.n = value def set_n(self,value): if value < self.min: # boundary check self.n = self.min if value > self.max: self.n = self.max else: self.n = value n = property(lambda self : self._value, set_n) This works, except I would like the class to behave like built-in types, so I can use it like this: a = Limited(7, 0, 10) b = math.sin(a) So that object itself returns it's value (which is stored in a.n). Is this possible? From bearophileHUGS at lycos.com Thu Jun 12 07:35:48 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 12 Jun 2008 04:35:48 -0700 (PDT) Subject: get keys with the same values References: Message-ID: Nader: > d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} > I will something as : > d.keys(where their values are the same) That's magic. > With this statement I can get two lists for this example: > l1= ['a','e'] > l2=['b','d'] > Would somebody tell me how I can do it? You can create a new dict where the keys are the values of the input dict and the values are a list of the keys of the original dict. So scanning the keys, values of the input dict, you can fill the second dict. Then you can scan the second dict, and create a list that contains only value lists longer than one. Bye, bearophile From thermostat at gmail.com Fri Jun 27 15:30:17 2008 From: thermostat at gmail.com (Dan) Date: Fri, 27 Jun 2008 12:30:17 -0700 (PDT) Subject: ask for a RE pattern to match TABLE in html References: <6a4f17690806260653i136681bdsabe0f6bb1dfab67b@mail.gmail.com> <62f752f3-d840-42de-a414-0d56d15d7c5a@w4g2000prd.googlegroups.com> Message-ID: <50285840-7601-41be-aa3d-865f46fe85c6@56g2000hsm.googlegroups.com> On Jun 27, 1:32 pm, "David C. Ullrich" wrote: > In article > <62f752f3-d840-42de-a414-0d56d15d7... at w4g2000prd.googlegroups.com>, > Jonathan Gardner wrote: > > > On Jun 26, 3:22 pm, MRAB wrote: > > > Try something like: > > > > re.compile(r'.*?', re.DOTALL) > > > So you would pick up strings like "
foo > td>
"? I doubt that is what oyster wants. > > I asked a question recently - nobody answered, I think > because they assumed it was just a rhetorical question: > > (i) It's true, isn't it, that it's impossible for the > formal CS notion of "regular expression" to correctly > parse nested open/close delimiters? Yes. For the proof, you want to look at the pumping lemma found in your favorite Theory of Computation textbook. > > (ii) The regexes in languages like Python and Perl include > features that are not part of the formal CS notion of > "regular expression". Do they include something that > does allow parsing nested delimiters properly? So, I think most of the extensions fall into syntactic sugar (certainly all the character classes \b \s \w, etc). The ability to look at input without consuming it is more than syntactic sugar, but my intuition is that it could be pretty easily modeled by a nondeterministic finite state machine, which is of equivalent power to REs. The only thing I can really think of that is completely non- regular is the \1 \2, etc syntax to match previously match strings exactly. But since you can't to an arbitrary number of them, I don't think its actually context free. (I'm not prepared to give a proof either way). Needless to say that even if you could, it would be highly impractical to match parentheses using those. So, yeah, to match arbitrary nested delimiters, you need a real context free parser. > > -- > David C. Ullrich -Dan From paul at boddie.org.uk Thu Jun 5 17:13:07 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 5 Jun 2008 14:13:07 -0700 (PDT) Subject: line continuation for lines ending in "and" or "or" References: <90ee8b5d-1509-4463-aaab-f712f7e72d4b@j33g2000pri.googlegroups.com> <0d723e6d-f81b-4545-b406-fc60b20c5433@u6g2000prc.googlegroups.com> Message-ID: <198c0b6a-65b3-437c-bcb0-ff58985f8ee7@l42g2000hsc.googlegroups.com> On 5 Jun, 22:40, "Terry Reedy" wrote: > > A line ending in an operator is ambiguous in that it *could* indicate that > the programmer intends to continue on the next line while it also could > indicate that the programmer forgot to finish before hitting return, or > that something got erased but not replaced. Yes, this is an excellent point. For the logical operators, consider code like the following... x = obj1.something() and obj2.conditional() and # time for lunch! obj4.obligatory_something() Although a trailing "and" or "or" operator might suggest a continuation of the expression on the next line, one has to consider whether the next line (or almost any line defining an expression) should suggest possible membership of an expression on the preceding line by default for its contents. One could, of course, insist on indentation to prevent such ambiguity since the second line above shouldn't be indented further if part of a separate statement. More work is definitely needed on such a proposal, certainly. Paul From michalis.avraam at gmail.com Fri Jun 20 12:45:25 2008 From: michalis.avraam at gmail.com (michalis.avraam at gmail.com) Date: Fri, 20 Jun 2008 09:45:25 -0700 (PDT) Subject: Python "is" behavior References: <02d58c63-f8d8-44a8-ac09-d483a0fa8c0f@v1g2000pra.googlegroups.com> <725bcf7a-3d6a-4a38-a906-bb397bdd447f@26g2000hsk.googlegroups.com> Message-ID: <03a030b7-1d47-4386-9826-435ce936c130@p39g2000prm.googlegroups.com> On Jun 20, 9:42?am, George Sakkis wrote: > On Jun 20, 12:31 pm, michalis.avr... at gmail.com wrote: > > > > > I am not certain why this is the case, but... > > > >>> a = 256 > > >>> b = 256 > > >>> a is b > > > True > > > >>> a = 257 > > >>> b = 257 > > >>> a is b > > > False > > > Can anyone explain this further? Why does it happen? 8-bit integer > > differences? > > No, implementation-dependent optimization (caching). For all we know, > the next python version may cache up to 1024 or it may turn off > caching completely; do not rely on it. More generally, do not use 'is' > when you really mean '=='. > > George Thank you George. I am very curious about some of these internal Python things that I keep stumbling upon through friends. And thank you for all the help! From dp_pearce at hotmail.com Thu Jun 19 06:25:02 2008 From: dp_pearce at hotmail.com (dp_pearce) Date: Thu, 19 Jun 2008 03:25:02 -0700 (PDT) Subject: Simple wxPython SetLabel question References: <005654a8-3406-4063-8e06-d7cf567b96d6@z66g2000hsc.googlegroups.com> Message-ID: Thank you very much C?dric. I thought it would be something very straight forward. From n.emami at gmail.com Mon Jun 9 09:47:40 2008 From: n.emami at gmail.com (Nader) Date: Mon, 9 Jun 2008 06:47:40 -0700 (PDT) Subject: lists to save in a tuple References: <130e261e-1e1a-4657-b8db-8a7704fb083d@z66g2000hsc.googlegroups.com> <6b4psbF35e8fgU1@mid.uni-berlin.de> Message-ID: <2d6b3e13-70c5-491d-ba07-3f8f36f28adc@e39g2000hsf.googlegroups.com> On Jun 9, 3:34 pm, "Diez B. Roggisch" wrote: > Nader wrote: > > Hello, > > > I have two lists and would save them in a tuple. > > > a = [1,2,3] > > b = ['a','b','c'] > > > with the next statement I can do that: > > > t = [(x,y), for x in a for y in b] > > > This gives the next list: > > > [(1,'a'),(1,'b'),(1,'c'), (2,'a'),(2,'b'),(2,'c'), (3,'a'),(3,'b'), > > (3,'c')] > > > But I want the next list: > > > [(1,'a'),(2,'b'),(3,'c')] > > > Would somebody tell me how I can solve this problem? > > zip(a, b) > > Diez Thank you! From gabriel.rossetti at arimaz.com Thu Jun 12 02:54:30 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Thu, 12 Jun 2008 08:54:30 +0200 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: <48494d73$0$31857$426a74cc@news.free.fr> References: <48494d73$0$31857$426a74cc@news.free.fr> Message-ID: <4850C826.7030108@arimaz.com> Bruno Desthuilliers wrote: > Gabriel Rossetti a ?crit : >> Larry Bates wrote: >>> Gabriel Rossetti wrote: >>>> Hello everyone, >>>> >>>> I had read somewhere that it is preferred to use >>>> self.__class__.attribute over ClassName.attribute to access class >>>> (aka static) attributes. I had done this and it seamed to work, >>>> until I subclassed a class using this technique and from there on >>>> things started screwing up. I finally tracked it down to >>>> self.__class__.attribute! What was happening is that the child >>>> classes each over-rode the class attribute at their level, and the >>>> parent's was never set, so while I was thinking that I had indeed a >>>> class attribute set in the parent, it was the child's that was set, >>>> and every child had it's own instance! Since it was a locking >>>> mechanism, lots of fun to debug... So, I suggest never using >>>> self.__class__.attribute, unless you don't mind it's children >>>> overriding it, but if you want a truly top-level class attribute, >>>> use ClassName.attribute everywhere! >>>> >>>> I wish books and tutorials mentioned this explicitly.... >>>> >>>> Gabriel >>> >>> If you define a class instance variable with the same name as the >>> class attribute, how would Python be able to distinguish the two? >>> That is a feature not a problem. Getter looks for instance >>> attribute, if one is not found it looks for a class attribute, and >>> upwards. This behavior is used by Zope to do all sorts of neat stuff. >>> >>> -Larry Bates >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >> A class instance variable, you must mean an instance attribute no? > > I think that's what he meant, yes. Ok. > >> If that is so, then with just self.attribute? Maybe there is a >> concept that I don't know about, > > The concept of name resolution (aka lookup) rules in Python, perhaps ? > When you do obj.attribute, attribute is first looked for in the > object, then in it's class, then in the parent classes. So yes, you > can get a class (or parent class) attribute directly on the instance. > Note that assignment on the instance (obj.attribute = value) will > alway (computed attributes or other hooks excepted) create the > attribute on the target, so if you have Class.attribute set, and then > do obj = Class(); obj.attribute = 42, then obj.attribute will shadow > Class.attribute. > Not really, see my answer to Mike Orr's msg. >> I've studied class/static attributes and instance attributes in my >> OOP classes. > > Forget about your OOP classes, mostly if it was in fact a Java or C++ > class. Python's object model is very far away from what most courses > present as "OOP". > Ok, in some ways yes. >> Gabriel > -- > http://mail.python.org/mailman/listinfo/python-list > > From mensanator at aol.com Mon Jun 23 13:47:57 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 23 Jun 2008 10:47:57 -0700 (PDT) Subject: Question: How do I format printing in python References: Message-ID: <2e43cbba-bcd1-492e-97aa-bf8d2708d665@26g2000hsk.googlegroups.com> On Jun 23, 12:12?pm, joemacbusin... at yahoo.com wrote: > Hi All, > > How do I format printed data in python? > I could not find this in the Python Reference Manual:http://docs.python.org/ref/print.html > Nor could I find it in Matloff's great tutorial:http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf > > For example, how do I turn this: > > 512 Jun 5 2004 X11r6 > 22 Jan 17 2005 a2p > 22 Jan 17 2005 acctcom > 5374 Sep 15 2002 acledit > 5664 May 13 2004 aclget > 12020 May 13 2004 aclput > 115734 Jun 2 2004 adb > 46518 Jun 4 2004 admin > 66750 Sep 16 2002 ali > 1453 Sep 15 2002 alias > 28150 Jun 4 2004 alog > 15 May 12 2005 alstat > > into this: > > 512 ? ? ? ?Jun ? 5 ? 2004 ? ?X11r6 > 22 ? ? ? ? Jan ? 17 ?2005 ? ?a2p > 22 ? ? ? ? Jan ? 17 ?2005 ? ?acctcom > 5374 ? ? ? Sep ? 15 ?2002 ? ?acledit > 5664 ? ? ? May ? 13 ?2004 ? ?aclget > 12020 ? ? ?May ? 13 ?2004 ? ?aclput > 115734 ? ? Jun ? 2 ? 2004 ? ?adb > 46518 ? ? ?Jun ? 4 ? 2004 ? ?admin > 66750 ? ? ?Sep ? 16 ?2002 ? ?ali > 1453 ? ? ? Sep ? 15 ?2002 ? ?alias > 28150 ? ? ?Jun ? 4 ? 2004 ? ?alog > 15 ? ? ? ? May ? 12 ?2005 ? ?alstat > > Thank you You could do this: data = ['512 Jun 5 2004 X11r6 ', \ '22 Jan 17 2005 a2p', \ '22 Jan 17 2005 acctcom ', \ '5374 Sep 15 2002 acledit ', \ '5664 May 13 2004 aclget ', \ '12020 May 13 2004 aclput ', \ '115734 Jun 2 2004 adb ', \ '46518 Jun 4 2004 admin ', \ '66750 Sep 16 2002 ali ', \ '1453 Sep 15 2002 alias ', \ '28150 Jun 4 2004 alog ', \ '15 May 12 2005 alstat '] for i in data: d = i.split() print d[0].ljust(9), print d[1].ljust(6), print d[2].ljust(4), print d[3].ljust(7), print d[4].ljust(9) which gives you 512 Jun 5 2004 X11r6 22 Jan 17 2005 a2p 22 Jan 17 2005 acctcom 5374 Sep 15 2002 acledit 5664 May 13 2004 aclget 12020 May 13 2004 aclput 115734 Jun 2 2004 adb 46518 Jun 4 2004 admin 66750 Sep 16 2002 ali 1453 Sep 15 2002 alias 28150 Jun 4 2004 alog 15 May 12 2005 alstat or perhaps this: for i in data: d = i.split() print d[0].rjust(9), print d[1].ljust(6), print d[2].zfill(2).ljust(4), print d[3].ljust(7), print d[4].ljust(9) which gives this (if you want the digits in the numbers to line up): 512 Jun 05 2004 X11r6 22 Jan 17 2005 a2p 22 Jan 17 2005 acctcom 5374 Sep 15 2002 acledit 5664 May 13 2004 aclget 12020 May 13 2004 aclput 115734 Jun 02 2004 adb 46518 Jun 04 2004 admin 66750 Sep 16 2002 ali 1453 Sep 15 2002 alias 28150 Jun 04 2004 alog 15 May 12 2005 alstat From bsagert at gmail.com Wed Jun 11 00:33:50 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Tue, 10 Jun 2008 21:33:50 -0700 (PDT) Subject: Thanks for help re: %userprofile% Message-ID: <5e9eff4c-8a0e-48e1-9a53-cb0a8d4624e5@p39g2000prm.googlegroups.com> The python community is very helpful to newbies like me. I did however manage to solve my problem in the meantime. I needed the modification time of certain files on various computers, but I didn't know the usernames ahead of time, so I used windows %userprofile% method. Python likes forward slashes in file names, whereas windows likes back slashes. Here is my script. import os, re u = os.getenv("USERPROFILE") # python returns "c:\\documents and Settings\\user" # note the escaped backslashes which windows hates. # let's repair that with re.sub u = re.sub( r"\\", "/", u) f = u+"/dir1/file1" mod = os.path.getmtime(f) # success, now do something c = "copy '%userprofile%\dir1\file1' c:\dir2\file2" # note back slashes here which windows tolerates. # In the os.system context, python delivers unescaped slashes. os.system(c) # success I'm a retired old fart trying to learn python so I welcome criticism and advice. My original post was at http://groups.google.ca/group/comp.lang.python/browse_thread/thread/59cc71e92bef1ee2?hl=en# From johnjsal at NOSPAMgmail.com Mon Jun 23 14:37:36 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 23 Jun 2008 14:37:36 -0400 Subject: Using Python to run SSH commands on a remote server References: <03a078c8$0$3229$c3e8da3@news.astraweb.com> <86adnQ8H4MFYdcLVnZ2dnUVZ_sHinZ2d@cablespeedwa.com> Message-ID: <03a08853$0$3220$c3e8da3@news.astraweb.com> "Jeffrey Froman" wrote in message news:86adnQ8H4MFYdcLVnZ2dnUVZ_sHinZ2d at cablespeedwa.com... > Be careful, this procedure sounds potential risky, security-wise ;-) I guess a blanket process might be a tad risky, but don't you want all CGI files to be executable by all? From omer at no-log.org Fri Jun 13 12:46:46 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Fri, 13 Jun 2008 18:46:46 +0200 Subject: Python Socket programming In-Reply-To: <655455.29695.qm@web7907.mail.in.yahoo.com> References: <655455.29695.qm@web7907.mail.in.yahoo.com> Message-ID: <200806131846.46807.omer@no-log.org> Hi, Le Friday 13 June 2008 18:29:06 srinivasan srinivas, vous avez ?crit?: > Hi, > I am going to do some socket related programming in Python. Before that, I > wish to know the Gotchas of Python Scoket Programming. Can anyone send me > any link that satisfies my needs?? Yes, the friendly manual :) http://docs.python.org/lib/module-socket.html and if you want to know more about socket themselves, the gnu libc info page is a good starting point as the python module is basically an interface to it: http://www.gnu.org/software/libc/manual/html_node/Sockets.html#Sockets -- C?dric Lucantis From gh at ghaering.de Fri Jun 13 09:31:50 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 13 Jun 2008 15:31:50 +0200 Subject: Summing a 2D list In-Reply-To: <740c3aec0806130558i2b02594dq5a6f3daf39c214a5@mail.gmail.com> References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <740c3aec0806130558i2b02594dq5a6f3daf39c214a5@mail.gmail.com> Message-ID: BJ?rn Lindqvist wrote: > [...] > Here is another solution: > > from itertools import groupby > from operator import itemgetter > > users = [1, 1, 1, 2, 2, 3, 4, 4, 4] > scores = [0, 1, 5, 3, 1, 2, 3, 3, 2] > > for u, s in groupby(zip(users, scores), itemgetter(0)): > print u, sum(y for x, y in s) Except that this won't work unless users and scores are sorted by user first. groupby() only coalesces identical values, and doesn't do what a "GROUP BY" clause in SQL is doing. Adding a sorted() call around zip() should be enough to make groupby() actually useful. But then, this code definitely starts to look like somebody desperately wanted to find a use for Python's new gimmicks. Here's more of the same sort ;-) >>> import sqlite3 >>> sqlite3.connect(":memory:").execute("create table tmp(user, score)").executemany("insert into tmp(user, score) values (?, ?)", zip(users, scores)).execute("select user, sum(score) from tmp group by user").fetchall() [(1, 6), (2, 4), (3, 2), (4, 8)] -- Gerhard From daveparker at flamingthunder.com Wed Jun 11 10:36:59 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Wed, 11 Jun 2008 07:36:59 -0700 (PDT) Subject: Dynamic HTML from Python Script References: <484f151c$0$5009$607ed4bc@cv.net> <484f21aa$1@dnews.tpgi.com.au> <484f24e9$0$5020$607ed4bc@cv.net> <484f2870$1@dnews.tpgi.com.au> <484f3574$0$4998$607ed4bc@cv.net> <5493ff9f-7ed0-41db-9837-94b11f757d3f@j1g2000prb.googlegroups.com> Message-ID: On Jun 11, 7:59 am, Lie wrote: > You can't make the browser refresh automatically in the server side, Yes you can. I don't know how to do it in Python, but here's an example in Flaming Thunder of a small, fast, light compiled server side CGI that delivers dynamic content every 10 seconds. # Write out the HTTP headers, followed by a blank line. # Make sure to write CRLF and not just LF, as per HTTP # specs. Also, turn off caching using the no-cache and # expires options, so that caching doesn't conflict with # refreshes. Set CRLF to CarriageReturn+LineFeed. Write "Refresh: 10; url=http://www.flamingthunder.com/cgi/ refresh.cgi",CRLF. Write "Content-type: text/html",CRLF. Write "Pragma: no-cache",CRLF. Write "Expires: 0",CRLF. Write "Cache-Control: no-cache",CRLF. Write CRLF. # Write out the dynamic information. In this # case, we'll just write out Greenwich mean time. Write GetGreenwichMeanTime. For this example, the dynamic content is just Greenwich mean time. You can see it in action at: http://www.flamingthunder.com/cgi/refresh.cgi To create the CGI script, I used Flaming Thunder's cross compiling ability to compile the script under Windows, targeting Linux: ft file refresh.ft output refresh.cgi target linux32 I then ftp'd refresh.cgi up to the cgi directory on my server, set the permissions to 700 to make it executable, and it works (without needing to install any bulky, plodding interpreter). On Jun 11, 7:59?am, Lie wrote: > On Jun 11, 9:16?am, asdf wrote: > > > > > > > On Wed, 11 Jun 2008 11:20:48 +1000, Aidan wrote: > > > asdf wrote: > > >>> Well, there's a few ways you could approach it. > > > >>> You could create a cgi program from your script - this is probably the > > >>> solution you're looking for. > > > >> Output from the script does come up very often. There is a new output > > >> every 10 secs and it's possible that the script might be run > > >> indefinitely. Basically I want all that output displayed in a web > > >> browser > > > > Well, in that case you could simply append the new output to a static > > > file every 10 seconds, or whenever there is new output. ?That way, you > > > just need to refresh the static file in your browser to see updates... > > > Given what I understand of your situation, that's how I'd do it. > > > The problem with this is that browser would have to be refreshed manually > > every 10 seconds. Unless there is a way to set this in the script itself. > > Surely you don't think you can do that without Javascript don't you? > You can't make the browser refresh automatically in the server side, > it has to be done in the client side scripting or like Opera browser > that have an option to make it refresh a page every few seconds. > > > > > > A constantly running CGI app is probably not the best idea, given > > > timeouts and other such constraints you might run into. > > > >>> You could have the script run periodically and create a static html > > >>> file in the webroot... this would be acceptable, maybe preferable, if > > >>> the output from your script doesn't change frequently.- Hide quoted text - > > - Show quoted text -- Hide quoted text - > > - Show quoted text - From tdahsu at gmail.com Sat Jun 14 18:29:26 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Sat, 14 Jun 2008 15:29:26 -0700 (PDT) Subject: Avoiding redirects with urllib References: Message-ID: <5c25f007-03dd-487f-9548-4e8481fc6142@m36g2000hse.googlegroups.com> On Jun 14, 6:18?pm, tda... at gmail.com wrote: > On Jun 14, 5:22?pm, Fernando Rodriguez > > wrote: > > Hi, > > > I'musing urllib to download pages from a site. How can I detect if a given > > url is being redirected somewhere else? I want to avoid this, is it possible? > > > Thanks in advance! > > Try this: > > import urllib > url_opener = urllib.URLopener() # create URLopener > #You could also work with urllib.FancyURLopener > > try: > ? ? data = url_opener.open("http://www.somedomain.com/index.html") ? # > open index.html > except IOError, error_code: > ? ? if error_code[0] == "http error": > ? ? ? ? if error_code[1] == 301: > ? ? ? ? ? ? #do something here > ? ? ? ? if error_code[2] == 302: > ? ? ? ? ? ? #do something here > > I hope that's of some help! ?I think you may want to delve deeper into > FancyURLopener... That last part might better be: if error_code[1] == 301: #do something here elif error_code[1] == 302: #do something here From spectrumdt at gmail.com Thu Jun 19 07:47:39 2008 From: spectrumdt at gmail.com (Spectrum) Date: Thu, 19 Jun 2008 04:47:39 -0700 (PDT) Subject: Extending Python with C: Cannot find MPI library Message-ID: I am writing some Python code using the Message Passing Interface (MPI), an API used in parallel computing. There exist a number of Python implementations of MPI, but apparently they all rely on the Numeric Python (numpy) package. I need to run my code on a particular machine made available by my university, which does not have numpy and will not be getting it. So I am trying to write my own mini-wrapper for MPI in C to extend my Python program. There exists a special C compiler to use when compiling C programs that use MPI, called mpicc. Here is what I have tried: I have written a minimal C program that uses MPI. It works correctly when compiled with mpicc. Then I've written Python boilerplate code and a Python script to compile my C program into a Python-includable module. This does not work a priori because the Python compilation script uses gcc rather than mpicc. So I have taken the exact gcc command that the script uses and replaced "gcc" with "mpicc". This produces an *.so file that compiles without errors. Unfortunately, it fails when I try to import it in Python. It can't find the MPI library. My MPI code looks like this (plus some boilerplate code): /* Return the MPI rank of the current process. */ int rank(){ int argc; char **argv; int rank, size; MPI_Init( &argc, &argv ); MPI_Comm_rank( MPI_COMM_WORLD, &rank ); MPI_Finalize(); return rank; } /* Main. A 'Hello World' function. */ int hello() { int rankNumber = rank(); printf ("Hello, World. I am process %d.\n", rankNumber); return rankNumber; } My Python program that includes it looks like this: import ctest ctest.hello() My error message is this: [ore at localhost Opgave03]$ mpiexec -n 1 python ctest.py Traceback (most recent call last): File "ctest.py", line 1, in import ctest ImportError: /big/School/Cluster/Opgave03/ctest.so: undefined symbol: ompi_mpi_comm_world [ore at localhost Opgave03]$ Can anyone suggest anything? Can I get MPI to work in Python? Last time I asked a similar question, someone recommended that I check out Cython instead of C. Do MPI bindings for Cython exist? Thanks in advance. - Claus Appel From eliben at gmail.com Fri Jun 27 09:10:17 2008 From: eliben at gmail.com (eliben) Date: Fri, 27 Jun 2008 06:10:17 -0700 (PDT) Subject: problem compiling extensions with mingw Message-ID: <4973972a-e510-49b1-86bf-4ee4294842cd@m44g2000hsc.googlegroups.com> Hello, I'm trying to compile the minimal example from http://en.wikibooks.org/wiki/Python_Programming/Extending_with_C with MinGW (latest version) and Python 2.5 (latest ActiveState binary install). When running the setup file, the following happens: running build running build_ext building 'hello' extension writing build\temp.win32-2.5\Release\hello.def d:\mingw\bin\gcc.exe -mno-cygwin -shared -s build \temp.win32-2.5\Release\hellomo dule.o build\temp.win32-2.5\Release\hello.def -LC:\Python25\libs -LC: \Python25\P Cbuild -lpython25 -lmsvcr71 -o build\lib.win32-2.5\hello.pyd build\temp.win32-2.5\Release\hellomodule.o:hellomodule.c:(.text+0x3e): undefined reference to `_imp___Py_NoneStruct' build\temp.win32-2.5\Release\hellomodule.o:hellomodule.c:(.text+0x46): undefined reference to `_imp___Py_NoneStruct' collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 What's more, compiling the same extension with Visual Studio 2005 (without using distutils) works fine, the extension is loaded and ran successfully from Python. Any ideas about this error ? Eli From andrei.avk at gmail.com Mon Jun 9 14:01:29 2008 From: andrei.avk at gmail.com (Rainy) Date: Mon, 9 Jun 2008 11:01:29 -0700 (PDT) Subject: Separators inside a var name References: Message-ID: <8f93a005-3149-41ef-90c8-934f9543fe75@79g2000hsk.googlegroups.com> On Jun 9, 1:42?pm, Gary Herron wrote: > Rainy wrote: > > I have a stylistic question. In most languages words in var. name are > > separated by underscores or cap letters, resulting in var names like > > var_name, VarName and varName. I don't like that very much because all > > 3 ways of naming look bad and/or hard to type. From what I understand, > > scheme can have variables like var-name. I'm curious about reasons > > that python chose to disallow this. > > Because we'd prefer var-name to mean subtraction of values: var minus > name. ?If you want to use a that character in names, what syntax would > you prefer for subtraction? ?Do you consider lisp/scheme (- a b) to be > reasonable in Python? I would make it that var - var2 would be subtraction and var-name would be a var name. I don't like (- a b) but I might have preferred it if it allowed dashes inside var names, if I got used to it. Hard to say. > > > Another question I have is what > > other languages allow this naming scheme? Were there any languages > > that allowed space as a separator? > > Fortran used to. ?(Haven't checked in on it in years though so I don't > know now). ?And it not so much as allowed spaces as it *ignored* all > spaces. ?This was now-a-days considered a *really* bad idea, and is > rumored to be responsible for a bug that crashed a satellite. ?(At least > that's the way a nice urban legend tells it.) Well, if I understand right, fortran used caps for many things? I'm not sure how it separated things if it ignored all spaces. I'll trust you that it's not a good idea :-). However that's not what I meant, I'd just like to use (or rather try using) spaces inside var names. From wolfgang.grafen at ericsson.com Mon Jun 16 08:57:07 2008 From: wolfgang.grafen at ericsson.com (Wolfgang Grafen) Date: Mon, 16 Jun 2008 14:57:07 +0200 Subject: bpython - fancy Python shell In-Reply-To: References: Message-ID: I couldn't get it work on Solaris (modified some lines for Python2.3). One reason was that I had to download pyreadline separately - I did than but now pyreadline requires either ironpython or a windows installation. Something is going wrong... Best regards Wolfgang Bob Farrell schrieb: > I released this a while ago but did some work recently to fix some bugs > so I thought I may as well post it here. To quickly summarise: > In-line syntax highlighting > Auto complete with suggestions as you type > Pastebin stuff, save to file > "Rewind" feature to jump back a line if you mess up (don't ask how it > works, please ;) > > You can get it here: > http://www.noiseforfree.com/bpython/ > > There's info about git repos and what have you there, and apparently > it's also in some real distro repos, but I don't know the details. > > Oh, and you'll need pygments and pyparsing, and it doesn't work on > Windows (heard good reports about it working fine on a Mac though). From pavlovevidence at gmail.com Mon Jun 2 20:11:31 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 2 Jun 2008 17:11:31 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> Message-ID: On Jun 2, 7:41 pm, "Russ P." wrote: > I thought you were saying that encapsulation or so-called "data > hiding" is worthless. If I misunderstood you, then I apologize. I > don't have time to go back and sort it all out. No, not at all. I was suggesting that Antoon's example of data hiding wasn't useful because it didn't really hide data: it was merely a spelling change. (I'm not, mind you, saying that it's ordinarily a good trade-off to encapsulate data, but I do get the point of it.) > Here's what I think Python should have. I think it should have a > keyword, something like "priv," to identify data or functions as > "private." As I said earlier, "private" for class data or functions > ("methods") could be implemented like "protected" in C++. That means > that derived classes would have access to it, but clients of the class > would not. If the client really needs or wants access, he could be > given a sort of "back door" access similar to the current Python rule > regarding double leading underscores. Thus, the client would have > access, but he would know very well that he is using something that > the original designer did not intend for him to use. Reasonable enough. I've always thought C++ should have a private_cast. Carl Banks From rdh at new.rr.com Thu Jun 5 08:48:18 2008 From: rdh at new.rr.com (DataSmash) Date: Thu, 5 Jun 2008 05:48:18 -0700 (PDT) Subject: readline() & seek() ??? References: <12655f64-33b1-4ab0-b6fb-294bfd2fa8c6@d45g2000hsc.googlegroups.com> Message-ID: <9c09e3cf-9117-4d62-b7bc-6fc59fe13ed1@m36g2000hse.googlegroups.com> On Jun 5, 3:50 am, Carl Banks wrote: > On Jun 4, 5:30 pm, DataSmash wrote: > > > Hi group, > > I have a text file that contains thousands of lines and each line is > > 256 characters long. > > > This is my task: > > For each line in the file, move to the 25th character, if the > > character is a "T", > > move to the 35th character of the line and read 5 characters from > > there. > > Capture these 5 characters and write them to a new text file, each 5 > > characters separated by a comma. > > Your professor possibly reads comp.lang.python, and if so, is likely > to know how to track you down with your IP address. > > Carl Banks Marc, Thanks. Tim, Thanks for the code. It's a easy task IF you know what to look for. I didn't. Carl, I'm not a student. Was just looking for some ideas. From tracyde at gmail.com Fri Jun 6 08:50:31 2008 From: tracyde at gmail.com (Derek Tracy) Date: Fri, 6 Jun 2008 08:50:31 -0400 Subject: Python CGI Upload from Server Status Message-ID: <9999810b0806060550w5a7297dbm8ba5cc902cad6f8b@mail.gmail.com> I am trying to create a simple python cgi app that allows the user to kick off an ftp from the server the cgi is on to another server; I have that piece working using ftplib but since the files in question are usually very large (500mb to 2gb) in size I want to be able to display some sort of status to the user, preferrably a progress bar of some sort. I have been scouring the internet for 2 days and have not came across a solution. I am unable to add modules that are not standard python modules (security restrictions), and have tried doing a page refresh meta tag and just have the cgi keep adding information to the page, but that doesn't seem to work. Does anybody have any ideas as to how I can attack this issue? -- --------------------------------- Derek Tracy tracyde at gmail.com --------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From lawtonpaul at gmail.com Sun Jun 15 20:18:54 2008 From: lawtonpaul at gmail.com (takayuki) Date: Sun, 15 Jun 2008 17:18:54 -0700 (PDT) Subject: newbie: for loop within for loop question Message-ID: <4ce96e03-d336-4c44-9d10-4a9418ce359d@w34g2000prm.googlegroups.com> Hi everyone, I'm studying python via the excellent "how to think like a python programmer" book by Allen Downey. Noob question follows... I have a txt file (animals.txt) which contains the following text each on a separate line: aardvark, bat, cat, dog, elephant, fish, giraffe, horse, inchworm, jackelope I want to create a function that loops through the animals.txt file and does *not* print the word if any of the user specified letters are in that word. def hasnolet(x): From kyosohma at gmail.com Tue Jun 10 20:45:26 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 10 Jun 2008 17:45:26 -0700 (PDT) Subject: Instructions on how to build py2exe 0.6.8 (or an installer would be nice, too!) References: <5426baaf-2ba6-41b0-a0ec-1070429b5195@x35g2000hsb.googlegroups.com> <7f3360e4-8a12-45cf-99fa-6172cb5a1aaa@a1g2000hsb.googlegroups.com> <1pqdneEnFojla9PVnZ2dnUVZ_oSunZ2d@comcast.com> Message-ID: <52e147d4-43ca-4f74-b21e-fa31ea49d219@m3g2000hsc.googlegroups.com> On Jun 10, 4:47?pm, Larry Bates wrote: > chard... at gmail.com wrote: > > On Jun 10, 11:34 am, Mike Driscoll wrote: > >> Maybe I'm missing something, but I can rename the executables I create > >> using py2exe 0.6.6 to anything I want after they're created. > > >> Or are you talking about a Windows installer for the py2exe module > >> itself? Where are you finding this 0.6.8 version anyway? I can't find > >> it onwww.py2exe.org > > >> Anyway, what Thomas is talking about is that the only way to create a > >> usable installer of py2exe on Windows is to use the same compiler that > >> the Python you are using. As I understand it, Python 2.4 and 2.5 used > >> Visual Studio 2003. I think 2.3 used VS6. I have both, so I can try to > >> compile an installer for any of those versions if you can link me to > >> the source. > > >> Mike > > >> Python Extension Building Network: ? ? http:\\www.pythonlibrary.org > > > The issue with renaming executables only applies to single-file > > executables, i.e. ones created with zipfile = None as an argument to > > setup() and --bundle 1 as a command line argument. This is a known > > issue as of 0.6.6:http://py2exe.org/index.cgi/ProblemsToBeFixed > > > I found sources for 0.6.8 on CVS at:http://sourceforge.net/cvs/?group_id=15583 > > > A Windows installer for the 0.6.8 py2exe module would be ideal, but > > somehow I doubt that's going to happen anytime soon since there hasn't > > been a new installer since 2006. If you are willing to build that for > > me (since I don't have VS) I'd really appreciate it : ) I'm using 32- > > bit WinXP on this computer. > > About every two weeks this "issue" pops up. ?Question: Why is is so important to > package everything into a single file? ?There are no Windows applications (that > I'm aware of) that ship as single files. ?Many of them consist of hundreds and > in some cases 'thousands' of files. ?Now if you want to DISTRIBUTE a single > setup.exe file, that makes sense to me. ?Use py2exe without the single file > option and ship a setup.exe file created by Inno Installer. ?Problem solved. > You will thank me when you want to include: registry entries, shortcuts, > documentation, configuration files, etc. in the distribution. > > -Larry Excellent point. I do include other files with my one exe using Inno myself. Originally when I bundled it all in one, my reasoning was that I needed to push it out to my organization and I figured pushing one large files was better than pushing a bunch of small ones. Or something like that. In retrospect, that's a dumb reason as I have lots of automated Python installers for things like Adobe Reader and Java and they basically just do copy jobs. Anyway, thanks for pointing that out. Mike From tdahsu at gmail.com Fri Jun 13 11:43:28 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Fri, 13 Jun 2008 08:43:28 -0700 (PDT) Subject: Iterate creating variables? References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> <6bfhj5F3b47fmU1@mid.uni-berlin.de> Message-ID: On Jun 13, 11:21?am, "Diez B. Roggisch" wrote: > tda... at gmail.com schrieb: > > > > > I have twenty-five checkboxes I need to create (don't ask): > > > self.checkbox1 = ... > > self.checkbox2 = ... > > . > > . > > . > > self.checkbox25 = ... > > > Right now, my code has 25 lines in it, one for each checkbox, since > > these are all variables. > > > Is there a way to write a loop so that I can have fewer lines of code > > but still keep the variables? > > > I've tried: > > > for o in xrange(25): > > ? ? self.checkbox[o] = ... > > > which didn't work, and > > > for o in xrange(25): > > ? ? self.checkbox[''%d'%(o)] = ... > > > which also didn't work. > > > Both give the error message: "Attribute error: Main.App has no > > attribute "checkbox"", which clearly indicates that I'm not keeping > > the "variability" aspect I want. > > > Is there a way? > > Keep either a list or dictionary around. Like this: > > checkboxes = [] > > for o in xrange(25): > ? ? ?checkboxes.append(....create a checkbox...) > > self.checkboxes = checkboxes > > Diez I don't understand... how do I then complete the assignment statement? If I have: self.checkbox1 = xrc.XRCCTRL(self.panel01, 'Checkbox1') . . . self.checkbox25 = xrc.XRCCTRL(self.panel01, 'Checkbox25') using your method, wouldn't I still need to figure out my original question? If I have a list of checkboxes, then I'll have: checkboxes = [checkbox1, checkbox2 ... checkbox25] in which case I'd still need to figure out how to get the variable at the end of checkbox to do the rest of the "=" statement. Or am I missing something? (I'm guessing that's likely!) Thanks. From fivetwentysix at gmail.com Thu Jun 5 02:46:26 2008 From: fivetwentysix at gmail.com (fivetwentysix at gmail.com) Date: Wed, 4 Jun 2008 23:46:26 -0700 (PDT) Subject: Looking for some good python learning resources on the web Message-ID: <8c4fb782-2767-4163-a577-195a22623493@v1g2000pra.googlegroups.com> What are the best sites to read to learn python? From gh at ghaering.de Mon Jun 9 04:06:12 2008 From: gh at ghaering.de (=?UTF-8?B?R2VyaGFyZCBIw6RyaW5n?=) Date: Mon, 09 Jun 2008 10:06:12 +0200 Subject: SQlite none english char In-Reply-To: References: <6b1ld5F3a4hsvU1@mid.uni-berlin.de> Message-ID: Gandalf wrote: > [...] > I solved the problem by entering data manually but now the problem is > that i had to delete this function: > con.text_factory = str > and now I can't see the data that I entered thought my sqlite manager Then apparently there is still non-UTF-8 data in the database. Perhaps SQLite Manager allows you to insert invalid data as well? Try this: con.text_factory = lambda s: unicode(s, "utf-8", "replace") This will decode to UTF-8 as good as possible, and for non-decodable characters you will get a REPLACEMENT CHARACTER instead. To demonstrate: >>> result = con.execute("select ? || ? || ?", ('text ok ', chr(230), ' ok, too')).fetchone()[0] The chr(230) is just random garbage that isn't valid UTF-8: >>> print result text ok ?k, too As you can see, there is now a strange character, but the second 'ok, too' got messed up :-/ But at least you can then find out which rows in the database have messed up data. You can then iterate over all rows with something like: Then, assuming the text to check for validity is in result, you can do something like: >>> import unicodedata >>> unicodedata.lookup("REPLACEMENT CHARACTER") in result True Does this help? -- Gerhard PS: This thread reinforces my believe that I have to make it harder for users of pysqlite to make themselves shoot in the foot with non-UTF-8 data. From wescpy at gmail.com Mon Jun 16 20:46:30 2008 From: wescpy at gmail.com (wesley chun) Date: Mon, 16 Jun 2008 17:46:30 -0700 Subject: FYA: visualizing repository commits Message-ID: <78b3a9580806161746k6916ae45ldb1621706daf259e@mail.gmail.com> have you guys seen this on Slashdot yet? (i did a quick search in the archives and haven't seen any posts yet so hopefully this isn't a duplicate msg!) http://developers.slashdot.org/developers/08/06/16/1855209.shtml this video is a visualization of the commits to the source base (and made by whom) over Python's lifetime: http://www.vimeo.com/1093745 the visualization project's home page is at: http://vis.cs.ucdavis.edu/~ogawa/codeswarm/ -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From jwkenne at attglobal.net Tue Jun 24 18:42:15 2008 From: jwkenne at attglobal.net (John W Kennedy) Date: Tue, 24 Jun 2008 18:42:15 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: Message-ID: <48617847$0$5021$607ed4bc@cv.net> David Combs wrote: > passing > *unnamed* functions as args (could Algol 60 also do something like that, > via something it maybe termed a "thunk") No, the "thunks" were necessary at the machine-language level to /implement/ ALGOL 60, but they could not be expressed /in/ ALGOL. -- John W. Kennedy "The first effect of not believing in God is to believe in anything...." -- Emile Cammaerts, "The Laughing Prophet" From mail at timgolden.me.uk Thu Jun 26 13:44:38 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 26 Jun 2008 18:44:38 +0100 Subject: Windows process ownership trouble In-Reply-To: <33847c9a-a816-48a1-a8c9-4209db9bf0b5@e53g2000hsa.googlegroups.com> References: <3fcf363f-3685-4b7b-8ba5-1ffc32e58af7@m44g2000hsc.googlegroups.com> <990516b7-f7ef-464a-97d0-fd55a0354ab4@y21g2000hsf.googlegroups.com> <33847c9a-a816-48a1-a8c9-4209db9bf0b5@e53g2000hsa.googlegroups.com> Message-ID: <4863D586.8030004@timgolden.me.uk> geoffbache wrote: > Tim, > > Unfortunately my previous message was premature, it seems your > workaround doesn't work > either on my system (Windows XP, Python 2.5.1) I get the following > printed out > > Traceback (most recent call last): > File "C:\TextTest\processown.py", line 12, in > os.remove ("filename") > WindowsError: [Error 32] The process cannot access the file because it > is being used by another process: 'filename' > close failed: [Errno 9] Bad file descriptor (Assuming you have the pywin32 extensions installed...) If you tweak your copy of subprocess.py by switching on the use of the pywin32 extensions in preference to the _subprocess module, the problem goes away, I think because the PyHANDLE object auto-closes. I'm not saying it won't ever fail -- the interactions of objects, scope, frames, exceptions and garbage collection are things I've never looked at too closely. But if you change line 378 from if 0: to if 1:, then the following works fine: import os import subprocess f = open ("filename", "w") try: p = subprocess.Popen ("blah", stdout=f) except WindowsError: f.close () os.remove ("filename") Note that the os.remove is *outside* the except handler. This is, I think, because the underlying handle object is still active until the try/except block closes. At which point it is, probably, gc-ed and closes. And you can remove the file. TJG From timr at probo.com Sun Jun 29 23:27:00 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 30 Jun 2008 03:27:00 GMT Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> Message-ID: <0ckg64hkkcjb7et08rv2hn5vb6nchkmbcl@4ax.com> John Salerno wrote: > >No, I don't mean presentation logic at all. I mean something along the >lines of combining HTML (which is what I refer to as "content") and >Python (which is what I meant by "logic"). So for example, if you have >code like this (and this isn't necessarily proper code, I'm just making >this up, but you'll see what I mean): > > >

Big Important Topic

>

This is where I say something important about

>
    > % for topic in topics: >
  1. ${topic}
  2. >
> > >Humph, I just made up that example to make the point that when you no >longer have pure HTML, but instead have programmatic logic (Python) >mixed in with the HTML, then you are mixing content and logic. Technically, you are probably right, but a model like MVC is supposed to enable better programming. It's not intended to be straightjacket and handcuffs. If that snippet makes sense to you, then there's nothing wrong with it. What's the alternative? The alternative is to have your Python code do something like this: topicList = [] for topic in topics: topicList.append( topic ) topicList = '
  • '.join( topicList ) and have your HTML page be:
    1. ${topicList}
    but now I've put chocolate into my peanut butter by embedding
  • tags in my Python code. >So maybe my question was a little premature. Or could it just be that >this is a *good* way to mix HTML and Python, and there are other ways >which may be bad? (For example, connecting to a database, like >Sebastian's example. That definitely seems out of place in an HTML file.) If it seems out of place to you, then you shouldn't do it. In general, you need to find a model that makes sense to you, and that allows you to write readable, workable, maintainable code. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From larry.bates at websafe.com` Mon Jun 2 17:02:34 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 02 Jun 2008 16:02:34 -0500 Subject: Cast list of objects to list of strings In-Reply-To: <48546eb1-11f3-4a88-b1ac-97bd485a1823@k30g2000hse.googlegroups.com> References: <48546eb1-11f3-4a88-b1ac-97bd485a1823@k30g2000hse.googlegroups.com> Message-ID: bukzor wrote: > I have this function: > > def write_err(obj): > from sys import stderr > stderr.write(str(obj)+"\n") > > and I'd like to rewrite it to take a variable number of objects. > Something like this: > > def write_err(*objs): > from sys import stderr > stderr.write(" ".join(objs)+"\n") > > but I lose the property that the function works on any object. What's > the simplest way to fix this? In essence, I need to cast a list of > objects to a list of strings. I'd like to do just "str(objs)" but that > (obviously) doesn't quite do what I need. > I think what you want is: def write_err(*args): from sys import stderr stderr.write("\n".join([str(o) for o in args])) but then I don't really understand why you would want such a function so I could be way wrong. -Larry From sjmachin at lexicon.net Fri Jun 27 09:23:56 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 27 Jun 2008 06:23:56 -0700 (PDT) Subject: where is the error? References: <8f8e1bf7-78b0-4292-9d56-396527b9dfb1@z66g2000hsc.googlegroups.com> <15ea1cb1-76a3-4fd3-8e4c-521b9aefcca2@m3g2000hsc.googlegroups.com> Message-ID: On Jun 27, 10:12 pm, la... at caramail.com wrote: > There was an error with the name of the variable !!!! I would not ask > this if it was just a question of different variable names !!!!! > Calm down. Stop shouting. It is not evident whether the above means that diff_temp_Stumpf was an error (should have been merely diff_temp) or not. > diff_temp=(logical_and(values[:,5] > -2,values[:,5] < 2)).nonzero() > new_values=values[diff_temp,:] > > Okay, I'm going to try to explain that more specifically that I did. I > have an array called values (size mxn). In this database, I just want > the lines for which the values of the nth row are between two values > (it's the purpose of diff_temp). So diff_temp gets me the number of > the lines for which this latter criteria is right. I think that you mean that diff_temp will be an array of the numberS (plural) of the lines (rows?) in values array that met the -2 < x < 2 criterion. Now you want to be able to use diff_temp to get the corresponding subset of some other array. Am I getting close? > But I'm interested > on the values of the lines corresponding to the number given by > diff_temp. Now you want to be able to use diff_temp to get the corresponding subset of some other array. Am I getting close? Perhaps you need something like other_array.take(diff_temp) ? > > In matlab, I will do > > diff_temp=find(values(:,5) > -2 & values[:,5) <2) > > new_values=values(diff_temp,:) > > Is it clear? Not very, I don't grok matlab. By the way, shouldn't you be using numpy? I thought numarray was going away by mid-2008 i.e. now. HTH, John > Thanks > Cedric From timr at probo.com Wed Jun 11 02:58:49 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 11 Jun 2008 06:58:49 GMT Subject: Python doesn't understand %userprofile% References: Message-ID: bsagert at gmail.com wrote: > >In xp when I try os.path.getmtime("%userprofile/dir/file%") Python >bites back with "cannot find the path specified" Since my script has >to run on machines where the username is unspecified I need a fix. For the record, the %PERCENT% syntax for looking up an environment variable is just a feature of the XP command shell. It has no meaning to any other part of Windows. os.environ is the right answer. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From vaahi0404 at gmail.com Thu Jun 5 04:55:44 2008 From: vaahi0404 at gmail.com (dev) Date: Thu, 5 Jun 2008 01:55:44 -0700 (PDT) Subject: comp.lang.python Message-ID: <71fba7ee-8f48-40b5-9d96-6cf12a97db7b@i36g2000prf.googlegroups.com> www.freeservice6.blogspot.com From mail at timgolden.me.uk Mon Jun 23 14:58:31 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 23 Jun 2008 19:58:31 +0100 Subject: Using Python and MS-SQL Server In-Reply-To: <734a9927-a18b-4af6-a717-eaf2631b4836@c58g2000hsc.googlegroups.com> References: <734a9927-a18b-4af6-a717-eaf2631b4836@c58g2000hsc.googlegroups.com> Message-ID: <485FF257.9090702@timgolden.me.uk> hwcowan at hotmail.com wrote: > I have programmed before, but I am new to using Python. I am > currently using the ArcGIS software which uses Python as its scripting > language for automating tasks. > > The current script that I am working on requires pulling in some > information from a Microsoft SQL Server. > > I was wondering if anyone could suggest the best way of doing this? I > have looked at the different modules that are specific to SQL server, > but none of them seem to be active or up to date. > > If not, could anyone make any suggestions? Or would it be better to > go the ODBC route? I am not talking about large amounts of data, so I > am not concerned about performance so ODBC would be fine to use as > well. Have a look at this: http://ramblings.timgolden.me.uk/2007/09/26/using-mssql-from-within-python-25/ It's hardly comprehensive, but it more-or-less answers your question. > Also, being new to Python, I recently read about dictionaries and was > wondering if there was a quick way to dump a table into a dictionary? > > For example, I have a customer list with a customer ID. It would be > great to have the ID as the "key" and the name as the "data" (or even > better, have a list as the data element containing all the information > about the customer). > > I am sure that this could be done manually, by looping through each > record and adding it to the dictionary -- but I was just wondering if > something like this has already been done (I don't need to reinvent > the wheel here). The key phrase you're looking for here is ORM (Object-Relational Mapper). Again, not an exact match for what you're saying, but unless you app remains *remarkably* simple, you're going to end up reinventing an ORM anyway. Probably the front runner these days is sqlalchemy (which certainly supports MS-SQL): http://sqlalchemy.org but just Google for "python orm" for any number of discussions and comparisons. TJG From socyl at 987jk.com.invalid Fri Jun 20 08:15:31 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 20 Jun 2008 12:15:31 +0000 (UTC) Subject: Why no output from xml.dom.ext.PrettyPrint? References: <19999864-b381-41b5-90fa-7e3cc3996d65@w8g2000prd.googlegroups.com> Message-ID: In <19999864-b381-41b5-90fa-7e3cc3996d65 at w8g2000prd.googlegroups.com> John Machin writes: >On Jun 20, 7:17 am, kj wrote: >> OK, the following should work but doesn't, and I can't figure out >> why: >> >> >>> from xml.marshal.generic import dumps >> >>> dumps( ( 1, 2.0, 'foo', [3,4,5] ) ) >> >> '12.0foo345' >> >> >>> from xml.dom.ext import PrettyPrint >> >>> PrettyPrint( dumps( ( 1, 2.0, 'foo', [3,4,5] ) ) ) >> >>> import sys >> >>> PrettyPrint( dumps( ( 1, 2.0, 'foo', [3,4,5] ) ), sys.stdout ) >> >> Why am I seeing no output from PrettyPrint? >> >You need to ask whoever you got your xml package from. In standard- >issue Python 2.5.2, there is an xml package with xml.dom, but it >contains no xml.dom.ext nor an xml.marshal. Hmmm!? OK. Thanks! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From lajam at caramail.com Fri Jun 27 09:55:26 2008 From: lajam at caramail.com (lajam at caramail.com) Date: Fri, 27 Jun 2008 06:55:26 -0700 (PDT) Subject: where is the error? References: <8f8e1bf7-78b0-4292-9d56-396527b9dfb1@z66g2000hsc.googlegroups.com> <15ea1cb1-76a3-4fd3-8e4c-521b9aefcca2@m3g2000hsc.googlegroups.com> Message-ID: <6a8b6c1c-c74c-448d-89c7-01dd5c3b4a40@m45g2000hsb.googlegroups.com> > > I think that you mean that diff_temp will be an array of the numberS > (plural) of the lines (rows?) in values array that met the -2 < x < 2 > criterion. Now you want to be able to use diff_temp to get the > corresponding subset of some other array. Am I getting close? I think that you're getting close. I want to get the lines that met the criterion. Diff_temp is an array containing the values of the lines. So bascially, > Now you want to be able to use diff_temp to get the corresponding > subset of some other array. Am I getting close? yes > Perhaps you need something like other_array.take(diff_temp) ? And my problem was that the commands worked on windows but not on linux. > By the way, shouldn't you be using numpy? I thought numarray was going > away by mid-2008 i.e. now. I know, but i'm not sure that it's the problem. Thanks Cedric From drakonik at gmail.com Sat Jun 28 11:56:25 2008 From: drakonik at gmail.com (Nick Dumas) Date: Sat, 28 Jun 2008 11:56:25 -0400 Subject: Pygame and Tkinter Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I'm doing a project with Pygame, a Snake game, and I've just taken a look at Tkinter and I really like how easy it is to build a GUI with it. The thing is that I don't know how I would use Tkinter and Pygame in conjunction. They seem to have some overlapping functionality (event handling and window drawing) so I'm not sure which tool I should use for which. Should I code the GUI and game in Pygame? Could I possibly embed the game in a Tkinter window/frame/widget? I would like to hear ideas on this; it's a very important project and I'd like to do it well. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkhmXykACgkQLMI5fndAv9giRwCgn/Zu2MGk+tKxHx+x+dkxSjvN l5MAoITZ0K8ekV6mgbvOGpTAreznahcv =Br5C -----END PGP SIGNATURE----- From vdutto at gmail.com Tue Jun 3 03:22:40 2008 From: vdutto at gmail.com (V) Date: Tue, 3 Jun 2008 00:22:40 -0700 (PDT) Subject: Books for programmers Message-ID: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> Hi, I'm a C++, Java and C programmer, and I'm searching for a (preferably printed) book that teaches me the "Python idioms", i.e. the "Python way" of doing something. Ideally, I'm searching for a book like "Effective C++" or "Effective Java", that does not lose time teaching what is a class, or a function, or a loop, but that enters into details and describes not only the "how", but also the "why". I read the book "Dive into Python", but I found too schematic and not enough advanced for my interests. I generally do not like books from O'Reilly, while I prefere those from Addison Wesley. Best regards. From gagsl-py2 at yahoo.com.ar Tue Jun 10 23:47:54 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Jun 2008 00:47:54 -0300 Subject: Using ElementTree as backend for a chat web application issues References: <1e5bcefd0806091132p78f42109t1edb5e5acfaadb43@mail.gmail.com> Message-ID: En Mon, 09 Jun 2008 15:32:00 -0300, Marcelo de Moraes Serpa escribi?: > I've built a chat with a front-end Ajax client and backend usign > ElementTree > to persist the data. > > In some circunstances I could not yet discover (it seems random) when I > edit/save the structure, the structure gets corrupted, elementree seems > to > get lost in its internal "cursor", usually something like this happens: > > > > > > > id="3"/> > > Pretty strange, and it drives the whole application unusable. > > I don't know if the concurrent nature of the application (multiple users > using the client at almost the same time and sending data to the server > which in turn must save the data to the same global.xml file) has > something > to do with it - I don't know if ElementTree is suitable for this kind of > thing. How to hanlde this concurrent issue? I don't think it's a problem with ElementTree. Perhaps you are writing the same (global) configuration file from several threads at the same time? You may need some locking mechanism in that case. -- Gabriel Genellina From eric.talevich at gmail.com Tue Jun 3 13:35:42 2008 From: eric.talevich at gmail.com (etal) Date: Tue, 3 Jun 2008 10:35:42 -0700 (PDT) Subject: Merging ordered lists References: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> <5722bab6-471b-4512-9d5e-7b173722d55b@p25g2000pri.googlegroups.com> <7d6bbe74-d6c5-4bb1-98b6-455f1fa0e18d@59g2000hsb.googlegroups.com> Message-ID: <4d8b256a-e918-48f9-b7fc-d98188508137@f36g2000hsa.googlegroups.com> On Jun 2, 11:08?pm, Raymond Hettinger wrote: > > If the inputs were not sorted, then I don't think you have a precise > idea of what it means to merge them while preserving order. ? For > example if the inputs are XYZPDQ and bYlmPz, then what does a merged > sequence look like once the Y and P duplicates are removed? Is it > XZPDQblmz or some intermix of the two like XbZlPmDzQ? ?If it is the > first of those, then the answer is simple: > I was looking at Bram Cohen's description of his diff algorithm, implemented in Bazaar: http://bramcohen.livejournal.com/37690.html "Instead of doing a longest common subsequence on everything, it does a longest common subsequence on lines which occur exactly once on both sides, then recurses between lines which got matched on that pass." So, if sources looks like: [list("XYZPDQ"), list("bYlmPz")] Then the proper merge would use Y and P as the delimiters, putting X and b before Y; Z, l and m before P; and D, Q and z after P -- like your second example (but keeping an instance of Y). Right? Leaving us with the context-dependent issue of ordering between the delimiters, probably depending on which list is used as the reference initially. So, if the reference list's elements go first, the result would be XbYZlmPDQz. If the elements from later sources go after the last common element (my first approach), it's bXYlmZPzDQ. However, in the cold light of morning it looks like that was the wrong approach -- it makes sense to treat any data that doesn't occur in the reference list as semi-obsolete and append it instead -- so I think I'll use your much simpler algorithm. Thanks! From johnjsal at NOSPAMgmail.com Thu Jun 26 12:10:45 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 26 Jun 2008 12:10:45 -0400 Subject: Mako vs. Cheetah? References: <4862f57c$0$11621$607ed4bc@cv.net> Message-ID: <4863bf9c$0$14081$c3e8da3@news.astraweb.com> "John Salerno" wrote in message news:4862f57c$0$11621$607ed4bc at cv.net... >I always have the desire to learn one thing well instead of split my >attention between several options, so I'm trying to decide which of these >two to start learning. Are there any particular things I should look at >when deciding between them, in terms of features, for example? Do they do >all the same things? Is it correct to say that Mako allows you to embed Python code within HTML, whereas Cheetah requires a certain amount of "tweaking" of Python code so that it isn't really code you could just run independently in the interpreter? I'm getting that impression from what I see so far. From mdw at distorted.org.uk Sun Jun 8 08:40:37 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Sun, 8 Jun 2008 12:40:37 +0000 (UTC) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> Message-ID: Russ P. wrote: > The idea of being able to discern properties of an object by its name > alone is something that is not normally done in programming in > general. Really? You obviously haven't noticed Prolog, Smalltalk, Haskell, ML, or Erlang then. And that's just the ones I can think of off the top of my head. * Prolog and Erlang distinguish atoms from variables by the case of the first letter; also `_' is magical and is equivalent to a new variable name every time you use it. * Smalltalk distinguishes between global and local variables according to the case of the first letter. * Haskell distinguishes between normal functions and constructors (both data constructors and type constructors) by the case of the first letter, and has Prolog's `_' convention. * ML allows a single-quote in variable names, but reserves names beginning with a single-quote for type variables. It also has Prolog's `_' convention. As far as I can see, discerning properties of a thing from its name seems relatively common. -- [mdw] From geoff.bache at jeppesen.com Thu Jun 19 04:09:59 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Thu, 19 Jun 2008 01:09:59 -0700 (PDT) Subject: Annoying message when interrupting python scripts References: <578d1ef8-231b-46fa-a181-e320fe1cc368@s33g2000pri.googlegroups.com> <87y753wk9a.fsf@benfinney.id.au> <1729bb65-0d3c-4407-858b-3816e19a46a3@d19g2000prm.googlegroups.com> <565c5f0e-5aef-4bcf-ab26-793ff138348f@59g2000hsb.googlegroups.com> Message-ID: <4d0f56dc-fc8a-4b54-ab59-24d827b15a39@c58g2000hsc.googlegroups.com> As nobody decried the idea of this being a bug, it now is :) http://bugs.python.org/issue3137 /Geoff From dullrich at sprynet.com Fri Jun 13 13:04:31 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 13 Jun 2008 12:04:31 -0500 Subject: Mapping None. Why? References: Message-ID: In article , Paddy wrote: > On Jun 13, 12:49 pm, David C. Ullrich wrote: > > On Thu, 12 Jun 2008 12:05:02 -0700 (PDT), Paddy > > > > wrote: > > > > >Iam wondering why the peculiar behavior of map when the function in > > >given as None: > > > > If you start with a value x and then apply no function > > at all to it, what results is x. > > > > David C. Ullrich > > True, but None is not a function. It's a sentinel value to turn on the > functionality. Uh, thanks. I think I knew that - I was just suggesting why the way map works makes sense. > - Paddy. -- David C. Ullrich From pavlovevidence at gmail.com Mon Jun 2 08:14:59 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 2 Jun 2008 05:14:59 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> Message-ID: On Jun 2, 6:40 am, Antoon Pardon wrote: > On 2008-06-02, Carl Banks wrote: > > > > > On Jun 2, 5:38 am, Antoon Pardon wrote: > >> If you really need it, you can do data hiding in python. It just > >> requires a bit more work. > > >> ----------------------------- Hide.py --------------------------------- > >> class Rec(object): > >> def __init__(__, **kwargs): > >> for key,value in kwargs.items(): > >> setattr(__, key, value) > > >> def __getitem__(self, key): > >> return getattr(self, key) > > >> def __setitem__ (self, key, val): > >> setattr(self, key, val) > > >> class Foo(object): > > >> def __init__(self): > > >> hidden = Rec(x=0, y=0) > > >> def SetX(val): > >> hidden.x = val > > >> def SetY(val): > >> hidden.y = val > > >> def GetX(): > >> return hidden.x > > >> def GetY(): > >> return hidden.y > > >> self.SetX = SetX > >> self.SetY = SetY > >> self.GetX = GetX > >> self.GetY = GetY > > > Red Herring. > > > 1. This doesn't hide the variables; it just changes their spelling. > > 2. This also "hides" the variables from its own class. > > > In other words, it's a useless no-op. > > > In fact, I'd say this is even worse than useless. Creating accessor > > functions is a sort of blessing for external use. Knowing that there > > are accessor functions is likely to cause a user to show even less > > restraint. > > I think you completed missed the point. I'm not sure I missed the point so much as I failed to read your mind. > This is just a proof of concept thing. In a real example there would > of course no Set en Get methods but just methods that in the course > of their execution would access or update the hidden attributes Fair enough, but I don't see anything in your example that suggests a way to discriminate between access from within the class and access from outside the class, which is the crucial aspect of data hiding. Carl Banks From gherron at islandtraining.com Fri Jun 6 17:40:39 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 06 Jun 2008 14:40:39 -0700 Subject: Learning which modules were loaded In-Reply-To: References: Message-ID: <4849AED7.9010509@islandtraining.com> James Stroud wrote: > I am rolling up a distribution of a program I wrote. It uses > matplotlib with tkagg so the bundle is HUGE (47 MB, 14 MB after bz > compression). Is there any way to run the program, put it through all > of its paces, and then inspect which modules were loaded. I would like > to gather these in a list and delete any others that py2app and py2exe > attempt to include. Currently, these (or py2app, at least) use > dependency graphing and icnlude everything belonging to pylab, > matplotlib, and numpy by default. I don't want everything, I only want > what my program needs to run. For example, some modules are imported > by functions (in Pmw, for example) that never get called. I don't want > to include these. > > Thanks in advance for any help. > > James > -- > http://mail.python.org/mailman/listinfo/python-list Import sys, then look at sys.modules. It's a dictionary that contains all the imported modules, but I suspect you'll find that it's much easier to let py2app and py2exe determine what's imported than it is to go through sys.modules yourself. Gary Herron From martin at v.loewis.de Tue Jun 17 18:34:32 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 18 Jun 2008 00:34:32 +0200 Subject: PEP 372 -- Adding an ordered directory to collections In-Reply-To: <31defced-c60d-45dc-a32a-af01a2b84c89@2g2000hsn.googlegroups.com> References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <4856e80c$0$30401$9b622d9e@news.freenet.de> <2d1e9b84-3dc7-4822-9c61-73991a527c67@s50g2000hsb.googlegroups.com> <48574b41$0$30410$9b622d9e@news.freenet.de> <31defced-c60d-45dc-a32a-af01a2b84c89@2g2000hsn.googlegroups.com> Message-ID: <48583bf9$0$14752$9b622d9e@news.freenet.de> > I think I have lost the thread here, sorry. So I explain again what I > mean. I think for this data structure it's important to keep all the > normal dict operations at the same speed. If you use a C > implementation vaguely similar to my pure python recipe you can > perform the del in O(1) too, because pairs are joined in (double) > linked list. But such data structure is O(n) to find the n-th item > inserted into the sequence. Right. So byindex(n) would be O(n) then, right? If so, what's the purpose of having that method in the first place? The PEP doesn't give a rationale, but just proposes that the method be there. My guess is that it includes it for performance reasons. However, I think the PEP (author) is misguided in assuming that making byindex() a method of odict, you get better performance than directly doing .items()[n] - which, as you say, you won't. Regards, Martin From bob at mellowood.ca Mon Jun 16 16:47:30 2008 From: bob at mellowood.ca (bvdp) Date: Mon, 16 Jun 2008 13:47:30 -0700 Subject: Simple and safe evaluator Message-ID: Okay guys. I have the _ast based safe eval installed and working in my program. It appears to be working just fine. Thanks for the help. Now, a few more questions: 1. I see that _ast is a 2.5 module?? So, for folks using my code with <2.5 I could do something like this: # I've got some imports here to look after the error() and warning() funcs .... emsg_done = 0 etx = "" def unsafe_eval(s): """ safe eval for < python 2.5 (lacks _ast) """ global emsg_done if not emsg_done: warning("You are using an unsafe eval() function. Please upgrade to Python version 2.5 or greater.") emsg_done=1 # need error trap here as well ... return eval(s, {"__builtins__":None}, {} ) def safe_eval(text): "similar to eval, but only works on numerical values." global etx try: ast = compile(text, "", 'eval', _ast.PyCF_ONLY_AST) except: error("Expression error in '%s'" % text) etx = text # for error reporting, bvdp return _traverse(ast.body) try: import _ast num_eval = safe_eval except: num_eval = unsafe_eval # rest of matt's ast code follows. Which appears to do the following: if there isn't an _ast module we just define an alternate, not-so-safe, function and warn the user; otherwise we use the safe version. I'm a bit uncomfortable with the import _ast being after the function which uses the code, but it seems to work. 2. I thought I'd be happy with * / + -, etc. Of course now I want to add a few more funcs like int() and sin(). How would I do that? Thanks. This is looking very nice indeed. Bob. From mensanator at aol.com Sat Jun 7 21:56:12 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 7 Jun 2008 18:56:12 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> <484ad07b$0$25721$607ed4bc@cv.net> <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> <484b3464$0$25724$607ed4bc@cv.net> Message-ID: <09d98480-c834-42bd-b97f-481133be9cb4@s50g2000hsb.googlegroups.com> On Jun 7, 8:22?pm, John Salerno wrote: > Mensanator wrote: > > What I DID say was that how the builtins actually > > work should be understood and it APPEARED that the > > OP didn't understand that. Maybe he understood that > > all along but his example betrayed no evidence of > > that understanding. > > Well, the truth is that I know zip truncates to the shorter of the two > arguments, Ok, sorry I thought otherwise. > and also in my case the two arguments would always be the > same length. Yes, because you're controlling the source code. But since lists are mutable, source code literals don't always control the length of the list. > But it is still helpful for other people to point out to me > potential problems like this, My intentions were always to be helpful, not arrogant. Otherwise, I'd just tell you to go RTFM. I do seem to have a gift for rubbing people the wrong way. What's important at the end of the day is that you have a working program, right? > so I can be aware of it the next time I > might want to use zip with unequal length arguments. There are, of course, situations where that's desireable, that's why I said such behaviour is by design. It's much easier to debug a program that crahes than one that works but gives you the wrong answer. You'll find the "out of range" errors readily enough, it's when the list is longer than the range and the answer comes up short that are hard to spot. That previous example I gave you? I've run that with a list of over 800,000 numbers, far too many to manually verify. I must have absolute confidence that the algorithm works correctly. That's what you should strive for - confidence that things will work even when you can't manually verify them. From carsten.haese at gmail.com Wed Jun 11 14:05:03 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Wed, 11 Jun 2008 14:05:03 -0400 Subject: problems with opening files due to file's path In-Reply-To: References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> <77acc29a-fffa-44d6-b07b-6bcf8b5bdd74@h1g2000prh.googlegroups.com> Message-ID: Alexnb wrote: > Okay, so as a response to all of you, I will be using the Entry() widget in > Tkinter to get this path. and the repr() function just makes all my > backslashes 4 instead of just 1, and it still screwes it up with the numbers > and parenthesis is has been since the first post. Oh and I know all about > escape characters, (\n,\b,\a,etc.) I can program C, not a lot, but enough to > know that I like python better. Anyway, so far I tried all of your stuff, > and it didn't work. infact, it puts backslashes in front of the "'" in some > of the words, such as "I'm" goes to "I\'m." So I posted the code I will be > using if you want to see the Tkinter code I can post it, but I don't see how > it will help. Your reluctance to post your code puzzles me. Several people have asked you several times to post your code. We're not doing this to waste your time. In fact, your reluctance to post your code wastes your time and our time by making us guess. Seeing your code should enable us to see exactly what the problem is. Your vague descriptions of what's going on are not useful because they are filtered through your inaccurate understanding of what's going on. I mean no offense by this, but if your understanding were accurate, you wouldn't be here asking for help. So, if you want us to help you, please humor us and post the actual code that gets the filename from the user and attempts to open the file. Also tell us what input you're entering and the output the code produces. -- Carsten Haese http://informixdb.sourceforge.net From maric at aristote.info Fri Jun 27 03:34:22 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 27 Jun 2008 09:34:22 +0200 Subject: Email Bounce Detection In-Reply-To: References: Message-ID: <200806270934.23395.maric@aristote.info> Le Friday 27 June 2008 09:03:15 madhav, vous avez ?crit?: > Hello everybody, I need a mechanism to detect email bounces. I tried > browsing through smtplib implementation and found not helpful in this > case. Actually it is said in the documentation that if a mail is sent > to say: "somerandomname at randomorg.com", then "_send()" in the > SMTPConnection class returns 550(Unknown recceipient). I checked the > same but its not returning 550 and return 250(receipient ok). This is not the same scenario, the SMTP server that will respond 550 is the MX for the domain, if you send your mails using an outgoing SMTP server, it can't know in advance the list of remote adressesbut will bounce your message when receiving the 550 from the remote MX. > Later, I tried getting the smtp error code from the mail body of a > bounced msg. the "Message" class doesnot have any error code attribute > by default. We need to get it from the mailbody(by regex ing), which i > think is not a valid solution, as "550" can occur anywhere in the body > of any message otherthan the bounced msg also. > Please help me regarding this. > Thanks in advance. Bounces are multipart messages easily parsed with the email package of the stdlib (dont' use regexes here). Abounce message is of type : Content-Type: multipart/report; report-type=delivery-status; a delivery-status imply that one of the subpart of the message is a message/delivery-status with all needed infos set in the headers. This one is taken from a real example : Content-Description: Delivery report Content-Type: message/delivery-status Reporting-MTA: dns; aristote.info X-Postfix-Queue-ID: 1D07D1409FF X-Postfix-Sender: rfc822; maric at aristote.info Arrival-Date: Fri, 27 Jun 2008 09:10:14 +0200 (CEST) Final-Recipient: rfc822; unknownadress at nerim.net Original-Recipient: rfc822;unknownadress at nerim.net Action: failed Status: 5.0.0 Remote-MTA: dns; tyrande.nerim.net Diagnostic-Code: smtp; 550 : Recipient address rejected: User unknown in local recipient table So, for example : >>>[48]: import email >>>[49]: bounce = email.message_from_string(open('ex.eml').read()) >>>[50]: bounce.get_content_type() ...[50]: 'multipart/report' >>>[51]: >>>[52]: for i in bounce.get_payload() : ....: if i.get_content_type() == 'message/delivery-status' : ....: print i.get_payload()[1]['status'] ....: ....: 5.0.0 -- _____________ Maric Michaud From Lie.1296 at gmail.com Mon Jun 9 18:02:16 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 9 Jun 2008 15:02:16 -0700 (PDT) Subject: Question by someone coming from C... References: <9d40211d-e03f-4f0c-a512-3ac78b0ede21@i18g2000prn.googlegroups.com> <4789a069-1038-4ee2-a2d6-933a9eaf6e2e@s21g2000prm.googlegroups.com> Message-ID: <94256cb0-cdb3-45ba-b7b7-b6fc53366270@w4g2000prd.googlegroups.com> On Jun 10, 4:32?am, Skye wrote: > OK, sounds good. ?So if not bitfields, what would be a good Python-y > way to do it? The word is "pythonic". > Flip booleans in a "debug config" dictionary or something? I'm not really sure, I've been programming with Python (and some other languages) but never really felt the need to store data in such super- efficient manners. I reckon a dict should do the job and it would be easier to read too compared to bitfield, since dict's entry is named. Actually, in python I usually do not put debugging codes before entering debugging cycle, and I usually remove all those debugging codes when the debugging cycle has finished (I'm talking for myself, not the whole python community). > Skye From cs at zip.com.au Wed Jun 25 23:32:12 2008 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 26 Jun 2008 13:32:12 +1000 Subject: struct.pack behavior In-Reply-To: Message-ID: <20080626033212.GA5526@cskk.homeip.net> On 25Jun2008 22:38, Steven Clark wrote: | On Wed, Jun 25, 2008 at 7:03 PM, John Machin wrote: | > On Jun 26, 9:00 am, "Steven Clark" wrote: | >> Can anyone explain to me why | >> struct.pack('HB',1,2) gives 3 bytes, whereas struct.pack('BH',1,2) | >> gives 4 bytes? | >> | > Alignment -- read the manual. | | If "the manual" is the help files for the struct module, I've read it | several times over. I understand endianness; I don't understand | alignment. Could anyone give a less cryptic / terse answer? For efficiency reasons many CPUs require particular primitive data types (integers/pointers of various sizes) to be placed in memory at particular boundaries. For example, shorts ("H" above, usually two bytes and probably always so in the struct module) are often required to be on even addresses, and longer objects to be on 4 or 8 byte boundaries. This allows for much more efficient memory access on many platforms (of course the rules depend on the platform). Although RAM _appears_ to the random access to arbitrary bytes, the underlying hardware will often fetch chunks of bytes in parallel. If a number spanned the boundaries of such a chunk it would require two fetch cycles instead of one. So this is avoided for performance reasons. So, packing "HB" puts a short at offset 0 (even) and then a byte. Conversely, packing "BH" puts a byte at offset zero but puts the short at offset 2 (to be even), leaving a gap after the byte to achieve this, thus the 4 byte size of the result (byte, gap, short). This layout procedure is called "alignment". Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Kilimanjaro is a pretty tricky climb. Most of it's up, until you reach the very, very top, and then it tends to slope away rather sharply. From gongchangzhaojie at gmail.com Wed Jun 4 18:50:44 2008 From: gongchangzhaojie at gmail.com (Zhaojie Boulder) Date: Wed, 4 Jun 2008 16:50:44 -0600 Subject: gcc error in Mac OS X Message-ID: <12956470806041550k7e2815b4ga6823ee7967a8718@mail.gmail.com> Hello, I am new to Mac and used python in linux before. What I am trying to do is to install "Ipython" and "PyCogent" in Mac OS X. For PyCogent, after entering the package path, I typed "python setup.py install". The results are as follows: Didn't find Pyrex - will compile from .c files running install running build running build_py running build_ext building 'cogent.align._compare' extension gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DMACOSX -I/usr/include/ffi -DENABLE_DTRACE -arch i386 -arch ppc -pipe -I/Users/zhaojie/Downloads/PyCogent-1.0.1/include -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -c cogent/align/_compare.c -o build/temp.macosx-10.5-i386-2.5/cogent/align/_compare.o -w unable to execute gcc: No such file or directory error: command 'gcc' failed with exit status 1 After google, I installed Xcode,but it did not help. Also, the Xcode folder is not within "applications" folder, but a separate one parallel with "applications". Dragging Xcode folder into the applications folder did not make a difference, either. Hope someone familiar with Mac can help me out. Thank you, Jie -------------- next part -------------- An HTML attachment was scrubbed... URL: From yxs008 at gmail.com Mon Jun 30 02:27:38 2008 From: yxs008 at gmail.com (yxs008 at gmail.com) Date: Sun, 29 Jun 2008 23:27:38 -0700 (PDT) Subject: Chanel shoes - Best High Quality Chanel shoes www.luxury-gift.org Message-ID: Chanel shoes - Best High Quality Chanel shoes www.luxury-gift.org Luxury Gift : http://www.luxury-gift.org Chanel shoes : http://www.luxury-gift.org/Shoes/Chanel-shoes.html Chanel shoes series contain the following items, each item is the perfect marriage of function and design. Chanel shoes are finely copied, you don't need to worry about the quality. We believe that no matter what you're looking for in a watch, our Chanel shoes will exceed your expectations. Explore the World of Brand Watches & Handbags It is a well-known fact that a watch you wear not just serves as a faithful time keeping device,but is also associated with your social status.style and evenframe of mind.If you intend tomake a wise choice as for purchasing awatch just right for you,devote your attention to awide range of high quality brand watches . The Best Chanel shoes Series : Chanel shoes All Products : Chanel shoes RCS001, Chanel shoes RCS002, Chanel shoes RCS003, Chanel shoes RCS004, Chanel Boots CS001, Chanel Boots CS002, Chanel Boots CS003, Chanel Boots CS004, Chanel Shoes CS005, Chanel Shoes CS006, Chanel Shoes CS007, Chanel Shoes CS008, Chanel Shoes CS009, chanel shoes RCS0711001, chanel shoes RCS0711002, chanel shoes RCS0711003, chanel shoes RCS0711004, chanel shoes RCS0711005, chanel shoes RCS0711006, chanel shoes RCS0711007, chanel shoes RCS0711008, chanel shoes RCS0711009, chanel shoes RCS0711010, chanel shoes RCS0711011, chanel shoes RCS0711012, chanel shoes RCS0711013, chanel shoes RCS0711014, chanel shoes RCS0711015, chanel shoes RCS0711016, chanel shoes RCS0711017, chanel shoes RCS0711018, chanel shoes RCS0711019, Chanel Shoes CAS0802001, Chanel Shoes CAS0802002, Chanel Shoes CAS0802003, Chanel Shoes CAS0802004, Chanel Shoes CAS0802005, Chanel Shoes CAS0802006, Chanel Shoes CAS0802007, Chanel Shoes CAS0802008, Chanel Shoes CAS0802009, Chanel Shoes CAS0802010, Chanel Shoes CAS0802011, Chanel Shoes CAS0802012, Chanel Shoes CAS0802013, Chanel Shoes CAS0802014, chanel shoes CAS0803001, chanel shoes CAS0803002, chanel shoes CAS0803003, chanel shoes CAS0803004, chanel shoes CAS0803005, chanel shoes CAS0803006, chanel shoes CAS0803007, chanel shoes CAS0803008, chanel shoes CAS0803009, chanel shoes CAS0803010, chanel shoes CAS0803011, chanel shoes CAS0803012, chanel shoes CAS0803013, chanel shoes CAS0803014, chanel shoes CAS0803015, Chanel shoes : http://www.luxury-gift.org/Shoes/Chanel-shoes.html From stephan at transvection.de Mon Jun 9 03:34:41 2008 From: stephan at transvection.de (Stephan Diehl) Date: Mon, 09 Jun 2008 09:34:41 +0200 Subject: Access to CAN-Bus In-Reply-To: <484cd469$0$28520$3b214f66@aconews.univie.ac.at> References: <484cd469$0$28520$3b214f66@aconews.univie.ac.at> Message-ID: Thin Myrna schrieb: > I'd like to access some drive hardware via CAN bus from Python under Linux > (sending rec'ing PDOs). Googling around I couldn't find a Python package, > but people who said that they are doing this, though. I guess they are > using their home brewn software. > > Any pointer to > - such software (anyone willing to share his experience?) > - how to write such software? > > Under Windows, I guess, I could use some COM or ctypes functionality to > access the hardware vendor's hardware. What if I wanted to access such > hardware from Linux? Is there a package that allows that in a vendor (who > doesn't support Linux) independent way? > > Many thanks in advance > Thin We've done this once (sorry no open source). If I remember right, we've been using ctypes on windows to access the CAN card. If I had to do something like this again, I'd definatelly check out an USB CAN adapter which might be easier to handle (but one never knows). Stephan From Hughjar700 at gmail.com Tue Jun 24 20:24:17 2008 From: Hughjar700 at gmail.com (Hughjar700 at gmail.com) Date: Tue, 24 Jun 2008 17:24:17 -0700 (PDT) Subject: Porn Addiction Message-ID: <0bc1d618-f140-4390-9dd0-4ade923ab054@w1g2000prd.googlegroups.com> Help, I'm addicted to porn. I've been downloading porn online and masturbating to it for a few years... Lately it's gotten even worse, I spend hours and hours surfing and masturbating to it. It's taking over my life and ruining everything.. I even missed days from work because of this addiction. I'm going to the porn as a way to avoid unwanted feelings or procrastination and then it just takes over. What can I do to end this horrible addiction? -Hugh From alexnbryan at gmail.com Tue Jun 10 21:55:25 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 10 Jun 2008 18:55:25 -0700 (PDT) Subject: problems with opening files due to file's path In-Reply-To: References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> Message-ID: <17768511.post@talk.nabble.com> Okay, I don't understand how it is too vague, but here: >>> path = "C:\Documents and Settings\Alex\My Documents\My >>> Music\Rhapsody\Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm >>> Yours.wma" >>> os.startfile(path) Traceback (most recent call last): File "", line 1, in os.startfile(path) WindowsError: [Error 2] The system cannot find the file specified: "C:\\Documents and Settings\\Alex\\My Documents\\My Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\x01 - I'm Yours.wma" Here's another way: >>> os.startfile(r"%s"%path) Traceback (most recent call last): File "", line 1, in os.startfile(r"%s"%path) WindowsError: [Error 2] The system cannot find the file specified: "C:\\Documents and Settings\\Alex\\My Documents\\My Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\x01 - I'm Yours.wma" Same output, however if I personally input it like so: >>> os.startfile("C:\\Documents and Settings\\Alex\\My Documents\\My >>> Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\\01 - I'm >>> Yours.wma") It works out fine because I can make each backslash doubles so it doesn't mess stuff up. So if I could take the path varible and make ever "\" into a "\\" then it would also work. Did I clarify? Grant Edwards wrote: > > On 2008-06-11, Alexnb wrote: > >> I am using GUI, Tkinter to be exact. But regardless of how the >> path gets there, it needs to opened correctly. The problem I >> am running into is that the program receives a path of a file, >> either .wma or .mp3 and is supposed to open it. I run into >> problems when there is either a ")" or a number next to the >> backslash "\" in the file path. I am looking for a way to make >> it work with a variable, I can make it work when I physically >> type it in, but not with a variable that holds the path. > > You're going to have to show us code and example input and > output. Your description of the problem is far too vague for > anybody to help you. > > -- > Grant Edwards grante Yow! With YOU, I can > be > at MYSELF... We don't NEED > visi.com Dan Rather... > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17768511.html Sent from the Python - python-list mailing list archive at Nabble.com. From timr at probo.com Wed Jun 11 02:05:03 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 11 Jun 2008 06:05:03 GMT Subject: time.clock() or Windows bug? References: <0uep44hpn8rupgr15a135f37q346tif9v2@4ax.com> Message-ID: Nick Craig-Wood wrote: > >Hmmm, 10,000,000 cycles (40 ms @2.5GHz) is nowhere near the ~90,000 >second jump in time.clock() output reported by the OP. I wonder if >there could be a different cause? Just wild theorizing, but it's possible that they are actually getting a negative delta, and some kind of signed/unsigned manipulation produces the 90,000 number. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From johnjsal at gmailNOSPAM.com Mon Jun 16 23:40:14 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Mon, 16 Jun 2008 23:40:14 -0400 Subject: Does '!=' equivelent to 'is not' In-Reply-To: References: Message-ID: <4857321f$0$11606$607ed4bc@cv.net> pirata wrote: > I'm a bit confusing about whether "is not" equivelent to "!=" > > if a != b: > ... > > if a is not b: > ... > > > What's the difference between "is not" and "!=" or they are the same thing? No, they are not the same thing. == and != test to see if the *value* of two variables are the same. Like so: >>> a = 'hello world' >>> b = 'hello world' >>> a == b True a and b both have the value of 'hello world', so they are equal is and is not, however, do not test for value equivalence, they test for object identity. In other words, they test to see if the object the two variables reference are the same object in memory, like so: >>> a is b False a and b are assigned to two different objects that happen to have the same value, but nevertheless there are two separate 'hello world' objects in memory, and therefore you cannot say that a *is* b Now look at this: >>> c = d = 'hello world' >>> c == d True >>> c is d True In this case, they are again the same value, but now the is test also shows that they are the same *object* as well, because both c and d refer to the same 'hello world' object in memory. There is only one this time. != and is not work the same: >>> a != b False >>> a is not b True >>> c != d False >>> c is not d False >>> Hope that helps! From gagsl-py2 at yahoo.com.ar Tue Jun 17 03:46:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 17 Jun 2008 04:46:38 -0300 Subject: print problem References: <2MWdnYXqCY3yy8rVnZ2dnUVZ_sbinZ2d@posted.internode> <48576371.7000209@gmail.com> Message-ID: En Tue, 17 Jun 2008 04:10:41 -0300, Rich Healey escribi?: > Gabriel Genellina wrote: >> En Tue, 17 Jun 2008 03:15:11 -0300, pirata escribi?: >> >>> I was trying to print a dot on console every second to indicates >>> running process, so I wrote, for example: >>> >>> for i in xrange(10): >>> print ".", >>> time.sleep(1) >>> >>> Idealy, a dot will be printed out each second. But there is nothing >>> print out until after 10 seconds, all 10 dots come out together. >>> >>> I've tried lose the comma in the print statement, and it works. >>> >>> Is that because of the print statement buffer the characters until >>> there is a new line character? >> >> Very probably, altough I can't reproduce it on Windows. Try invoking the script with python -u (unbuffered input/output): >> >> python -u your_script.py >> > Or just write to sys.stdout without the print wrapper.. I think the output is still buffered, even if you write directly to sys.stdout, but I don't have a Linux box to test right now. -- Gabriel Genellina From shank.nasa at gmail.com Mon Jun 30 14:46:07 2008 From: shank.nasa at gmail.com (Shankar Narayana) Date: Mon, 30 Jun 2008 14:46:07 -0400 Subject: Query regarding PythonQt In-Reply-To: <3231b5170806271141o38e7c2fcqffe7ecab04d33590@mail.gmail.com> References: <3231b5170806271141o38e7c2fcqffe7ecab04d33590@mail.gmail.com> Message-ID: <3231b5170806301146y6e530920o14123c863eba86ae@mail.gmail.com> Hi, After a big fight, I could get through the problem. I am posting it so that others does not waste time solving the issue. I dont know why "evalfile" method is having problems with existing .pyc files. But, we can solve it this way. First create your .cpp and .py file in directory. Then, do the following 1. Create somename.qrc file Filename.py 2. Navigate to the directory . Type the command: qmake -project (It creates project (.pro) file) 3. Next command: qmake (It creates a make file). 4. Then update the makefile INCPATH to add for Python and Python-Qt -I/usr/include/python2.5 -I/home/workspace/PythonQt-1.0/src 5. Update the LIBS -L/usr/lib/python2.5/config/libpython2.5.a -L/home/workspace/PythonQt-1.0/lib -lpython2.5 -lPythonQt WARNING: Always use ":" in your cpp file eval command. Then only Qrc will be used to create the corresponding. pyc file. Otherwise, the terminal will crash. Now issue the command "make" and run your application. Things work fine now. I am not very clear with QRC but its a very good solution. Rgds, Shankar On Fri, Jun 27, 2008 at 2:41 PM, Shankar Narayana wrote: > Hi, > I am newbie to PythonQt. I wanted to access the Qt objects created in C++ > using Python and update things. I had a look at this URL " > http://doc.trolltech.com/qq/qq23-pythonqt.html#decoratorsandcwrappers" > which talks about using PythonQt for the same. > I followed the instructions given in the example. I created my cpp file > and .py file and could make them working. > But once after the first time after .pyc file is created, my program no > longer executes. It is giving me a segmentation fault. If I remove my .pyc > file and run the program, things work fine. > > My cpp file > #include > #include > #include "PythonQt.h" > int main(int argc, char* argv[]) > { > QApplication app(argc,argv); > QTextEdit *welcomemsg = new QTextEdit("Hi whatsup"); > PythonQt::init(); > PythonQtObjectPtr mainModule = PythonQt::self()->getMainModule(); > mainModule.addObject("welcomemsg",welcomemsg); // Check with different > names > mainModule.evalFile("Pyscript.py"); > mainModule.removeVariable("welcomemsg"); > PythonQt::cleanup(); > return app.exec(); > } > > My Python file (Pyscript.py) > > from PythonQt import * > #append the text to the existing text edit > welcomemsg.append("Hurray I did it") > welcomemsg.show() > > Can somebody help me what makes this not to run once Python interpreter > works on the Python file and creates a .pyc file ? > > > Regards, > Shankar > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at gmail.com Fri Jun 6 02:36:33 2008 From: cwitts at gmail.com (Chris) Date: Thu, 5 Jun 2008 23:36:33 -0700 (PDT) Subject: readline() & seek() ??? References: <12655f64-33b1-4ab0-b6fb-294bfd2fa8c6@d45g2000hsc.googlegroups.com> Message-ID: <078bfcbf-4f6c-459c-9f68-619af24c3678@27g2000hsf.googlegroups.com> On Jun 6, 5:13?am, Kam-Hung Soh wrote: > Tim Roberts wrote: > > DataSmash wrote: > >> I have a text file that contains thousands of lines and each line is > >> 256 characters long. > > >> This is my task: > >> For each line in the file, move to the 25th character, if the > >> character is a "T", > >> move to the 35th character of the line and read 5 characters from > >> there. > >> Capture these 5 characters and write them to a new text file, each 5 > >> characters separated by a comma. > > >> I appreciate your help! > > > Did you even TRY this? ?Your task reads like pseudocode that translates > > virtually line-for-line to Python code. > > > ? fout = open('outputfile.txt','w') > > ? for line in open('inputfile.txt'): > > ? ? ? if line[24] == 'T': > > ? ? ? ? ? fout.write( line[34:39] + ',' ) > > Should the last line be ... > > fout.write(','.join(line[34:39]) > > -- > Kam-Hung Soh Software Salariman each 5 characters need to be delimited by a comma, your statement would have a comma between each of the 5 characters. From auch-ich-m at g-kein-spam.com Thu Jun 19 15:46:50 2008 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Thu, 19 Jun 2008 21:46:50 +0200 Subject: regex \b behaviour in python References: Message-ID: <24284438.YDfgAvrJ06@news.perlig.de> * Walter Cruz wrote: > irb(main):001:0>"walter ' cruz".split(/\b/) > => ["walter", " ' ", "cruz"] > > and in php: > > Array > ( > [0] => > [1] => walter > [2] => ' > [3] => cruz > [4] => > ) > > > But in python the behaviour of \b is differente from ruby or php. My python here does the same, actually: $ cat foo.py import re x = "walter ' cruz" s = 0 r = [] for m in re.finditer(r'\b', x): p = m.start() if s != p: r.append(x[s:p]) s = p print r $ python2.4 foo.py ['walter', " ' ", 'cruz'] $ python2.5 foo.py ['walter', " ' ", 'cruz'] $ nd -- $_=q?tvc!uif)%*|#Bopuifs!A`#~tvc!Xibu)%*|qsjou#Kvtu!A`#~tvc!KBQI!)*|~ tvc!ifmm)%*|#Qfsm!A`#~tvc!jt)%*|(Ibdlfs(~ # What the hell is JAPH? ; @_=split/\s\s+#/;$_=(join''=>map{chr(ord( # Andr? Malo ; $_)-1)}split//=>$_[0]).$_[1];s s.*s$_see; # http://pub.perlig.de/ ; From CracKPod at googlemail.com Sat Jun 28 02:55:01 2008 From: CracKPod at googlemail.com (CracKPod) Date: Fri, 27 Jun 2008 23:55:01 -0700 (PDT) Subject: More on Urllib, and Urllib2 References: Message-ID: On 28 Jun., 01:42, Alex Bryan wrote: > Okay, so I am having issues figuring anything out about this and have ? > read the "missing manual" about it so please don't send me that link ? > again. To put it simply I want to be able to input a word and get the ? > definition from dictionary.com. Now I found a work-around for ? > searching for the word, I just make it in the actual address. For ? > example I want to search for cheese, I can just do a: > > urllib2.urlopen("http://dictionary.reference.com/browse/cheese") > > However, the actual definition is in javascript on the page. I used ? > firebug to see it, and the first def, looks like this: > > > > > > > > the problem being that if I use code like this to get the html of that ? > page in python: > > response = urllib2.urlopen("the webiste....") > html = response.read() > print html > > I get the html source of the page, but no table with my definitions. ? > So what can I do? Also, is there a book or a better tutorial or ? > explanation of this urllib2, and urllib? If so, PLEASE let me know ? > about it; I will be eternally grateful. It would probably be a good idea to take a look at mechanize: http://wwwsearch.sourceforge.net/mechanize/ and at BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/ Greetz, CracKPod From cricket.keith at gmail.com Wed Jun 11 12:46:31 2008 From: cricket.keith at gmail.com (Keith Nation) Date: Wed, 11 Jun 2008 11:46:31 -0500 Subject: Reading info from an active file In-Reply-To: <21935b370806110940y3c4f4a33l8fd06ad679fb6863@mail.gmail.com> References: <21935b370806110940y3c4f4a33l8fd06ad679fb6863@mail.gmail.com> Message-ID: <21935b370806110946g7c8c1115p5b1a8ff1d914ec4f@mail.gmail.com> I have a program that writes a log file as it is running to give status of the job. I would like to read that file, pull certain lines of text from it, and write to a new file. Because I am such a novice user, I was hoping someone had covered this before and could let me know of your methods. If I open and close the file repeatedly to get refreshed information, I assume it would slow the system down. Any thoughts? Keith Nation -------------- next part -------------- An HTML attachment was scrubbed... URL: From larry at portcommodore.com Sun Jun 29 23:47:01 2008 From: larry at portcommodore.com (larry at portcommodore.com) Date: Sun, 29 Jun 2008 20:47:01 -0700 (PDT) Subject: help debugging noob code - converting binary data to images... References: <56955a42-155c-4c37-9bf6-5a99cadb5c79@l42g2000hsc.googlegroups.com> <8a9b4e80-45cf-4145-85c0-94d2f2a04aa4@j22g2000hsf.googlegroups.com> Message-ID: success, had to fill in a few blanks with some more googling, here is the finished script (used all for loops this time, saved a few more lines): ========== #!/usr/local/bin/python import string import Image, ImageDraw size = 2 im = Image.new("1",[8*size,8*size],1) draw = ImageDraw.Draw(im) cset = open("chargen","r") for cchar in range(0, 512, 1): for charline in range(0, 8, 1): x = cset.read(1) ch = ord(x) for position in range(0, 8, 1): if ch & ( 2 ** position ): xp = (7-position)*size yp = charline*size draw.rectangle(((xp,yp),(xp+size-1,yp+size-1)), fill=0 ) outfile = "/home/mydir/work/char"+string.zfill(cchar,3)+".png" im.save(outfile,"png") draw.rectangle(((0,0),(size*8,size*8)),fill=1) im.show() ========== It does the variable sizes like I wanted and it now sure is fast. If I wanted to display an image without saving how do I do that, on the image module it does not pop up a canvas.. the im.show() on the bottom does not seem to work. Thanks again! From hat at se-162.se.wtb.tue.nl Wed Jun 25 06:37:43 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 25 Jun 2008 12:37:43 +0200 Subject: insertion sorts... References: <06adb999-c7e2-4475-a49f-dbfbe042f4fd@r66g2000hsg.googlegroups.com> <5f0111a3-c1b9-4864-bae3-32fa324c4e5e@j22g2000hsf.googlegroups.com> <841dd5b8-d99d-4a60-ad39-b7c9563fca1d@d1g2000hsg.googlegroups.com> Message-ID: On 2008-06-25, python_newbie wrote: > On 24 Haziran, 04:33, Terry Reedy wrote: > Thanks for all answers. At the end i ve only one point. If a decide to > copy list to iterate when will i have to do this ? Before the > iteration ? And then iterate through one list and change value of the > other ? Before starting the iteration would be a good point.... I usually do in such cases: for x in mylist[:]: ... making a copy just before the for loop starts. Lately, I have started avoiding in-place modification of lists. Instead, I construct a new list from scratch inside the for-loop, and replace the old list with the newly constructed list afterwards like: new_list = [] for x in mylist: .... new_list.append(x) mylist = new_list by appending a different value than the original or by not appending, you can influence the contents of the new list. I find this solution nicer than in-place modification of an existing list. Sincerely, Albert From dyamins at gmail.com Fri Jun 13 19:01:56 2008 From: dyamins at gmail.com (Dan Yamins) Date: Fri, 13 Jun 2008 19:01:56 -0400 Subject: A package import question Message-ID: <15e4667e0806131601r14759c54jac431a8fc531414d@mail.gmail.com> I'm having a problem importing a package in python, deleting some of what's been imported, and then reimporting. (I'm the sure the problem is trivial, but I just don't understand it.) I have a directory of python modules called Operations. It contains a python module called archive.py. Here's a import of the archive module via package import: Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import Operations.archive >>> Operations.archive So far, so good. But now, suppose I want to delete Operations.archive. then, I can't reimport it. instead, I >>> del Operations.archive >>> import Operations.archive >>> dir() ['Operations', '__builtins__', '__doc__', '__name__'] >>> Instead of getting 'Operations.archive', I just seem to get 'Operations'. I can't seem to be able to import Operations.archive without quitting the python interpreter and starting again. What's going on here, and how do I fix it? Thanks, Dan -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Mon Jun 30 20:24:18 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 30 Jun 2008 17:24:18 -0700 (PDT) Subject: Looping-related Memory Leak References: <94312edc-babb-4c1b-8db1-233404aa4a02@i76g2000hsf.googlegroups.com> <0abf2145-231c-4189-a8ca-b1f327a735dd@a1g2000hsb.googlegroups.com> <1e36866c-4a94-40b6-9780-81e104286862@d1g2000hsg.googlegroups.com> Message-ID: On Jun 30, 1:55 pm, Tom Davis wrote: > On Jun 26, 5:38 am, Carl Banks wrote: > > > > > On Jun 26, 5:19 am, Tom Davis wrote: > > > > I am having a problem where a long-running function will cause a > > > memory leak / balloon for reasons I cannot figure out. Essentially, I > > > loop through a directory of pickled files, load them, and run some > > > other functions on them. In every case, each function uses only local > > > variables and I even made sure to use `del` on each variable at the > > > end of the loop. However, as the loop progresses the amount of memory > > > used steadily increases. > > > Do you happen to be using a single Unpickler instance? If so, change > > it to use a different instance each time. (If you just use the module- > > level load function you are already using a different instance each > > time.) > > > Unpicklers hold a reference to everything they've seen, which prevents > > objects it unpickles from being garbage collected until it is > > collected itself. > > > Carl Banks > > Carl, > > Yes, I was using the module-level unpickler. I changed it with little > effect. I guess perhaps this is my misunderstanding of how GC works. > For instance, if I have `a = Obj()` and run `a.some_method()` which > generates a highly-nested local variable that cannot be easily garbage > collected, it was my assumption that either (1) completing the method > call or (2) deleting the object instance itself would automatically > destroy any variables used by said method. This does not appear to be > the case, however. Even when a variable/object's scope is destroyed, > it would seem t hat variables/objects created within that scope cannot > always be reclaimed, depending on their complexity. > > To me, this seems illogical. I can understand that the GC is > reluctant to reclaim objects that have many connections to other > objects and so forth, but once those objects' scopes are gone, why > doesn't it force a reclaim? Are your objects involved in circular references, and do you have any objects with a __del__ method? Normally objects are reclaimed when the reference count goes to zero, but if there are cycles then the reference count never reaches zero, and they remain alive until the generational garbage collector makes a pass to break the cycle. However, the generational collector doesn't break cycles that involve objects with a __del__method. Are you calling any C extensions that might be failing to decref an object? There could be a memory leak. Are you keeping a reference around somewhere. For example, appending results to a list, and the result keeps a reference to all of your unpickled data for some reason. You know, we can throw out all these scenarios, but these suggestions are just common pitfalls. If it doesn't look like one of these things, you're going to have to do your own legwork to help isolate what's causing the behavior. Then if needed you can come back to us with more detailed information. Start with your original function, and slowly remove functionality from it until the bad behavior goes away. That will give you a clue what's causing it. Carl Banks From bj_666 at gmx.net Wed Jun 4 00:51:34 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 4 Jun 2008 04:51:34 GMT Subject: Q about object identity References: Message-ID: <6amlamF38poe2U1@mid.uni-berlin.de> On Tue, 03 Jun 2008 23:08:46 +0200, Christian Heimes wrote: > vronskij at gmail.com schrieb: >> Hello, >> >> I am testing object identity. >> >> If I do it from the interpreter, I get strange results. >> >>>>> print [] is [] >> False >> >>>>> print id([]), id([]) >> 3083942700 3083942700 >> >> >> >> Why is that? Isn't this an error? > > No, it's not an error. You are getting this result because the list > implementation keeps a bunch of unused list objects in a free list. It's > an optimization trick. Python has to create two different list objects > for "[] is []" while it can reuse the same list object for id([]) == id([]). I don't think you need optimization tricks for the explanation. In ``[] is []`` there need to be two lists that exist at the same time to be compared by the ``is`` operator. With ``id([]) == id([])`` just the id numbers have to exist at the same time, so the execution may look like this: ? create empty list ? call `id()` with it ? remember first id number ? when `id()` returns, the list is not referenced anymore and can be garbage collected ? create empty list, and here the list object might get allocated at the same memory location as the first empty list ? same id. ? call `id()` with it ? remember second id number ? garbage collect second empty list ? compare both numbers Ciao, Marc 'BlackJack' Rintsch From arslanburney at gmail.com Fri Jun 13 02:15:36 2008 From: arslanburney at gmail.com (arslanburney at gmail.com) Date: Thu, 12 Jun 2008 23:15:36 -0700 (PDT) Subject: Creating a st line after a specific point in Gnuplot Message-ID: <226801d7-0987-4020-bb8e-c300a6fff5c0@i76g2000hsf.googlegroups.com> While using gnuplot.py if id want to make a straight line supposingly y = 3 after the point (2,3) (a point on another line) with the same color as that of the line how wud i do that? From pistacchio at gmail.com Wed Jun 25 06:34:23 2008 From: pistacchio at gmail.com (pistacchio) Date: Wed, 25 Jun 2008 03:34:23 -0700 (PDT) Subject: Apache2 + Python WITHOUT mod_pytho References: <4f90e1e5-056e-4f61-866b-015a15030ebf@e39g2000hsf.googlegroups.com> Message-ID: <4b94d5b3-3f8d-4d48-af96-f7bc14ce8f2f@25g2000hsx.googlegroups.com> Solved. Here my new /etc/apache2/sites-available/default __________________________ NameVirtualHost * ServerAdmin webmaster at localhost DocumentRoot /var/www/ Options FollowSymLinks AllowOverride None AddHandler cgi-script .py Options ExecCGI Indexes FollowSymLinks MultiViews #Options All AllowOverride None Order allow,deny allow from all #AddHandler mod_python .py #PythonHandler mod_python.publisher #PythonDebug On ErrorLog /var/log/apache2/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/apache2/access.log combined ServerSignature On Alias /doc/ "/usr/share/doc/" Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 __________________________ On 25 Giu, 11:13, pistacchio wrote: > Hi to all! > How can i configure apache2 so that it processes all .py files with > python _without_ using mod_python? > I'm on Ubuntu 8.4. > > currently my /etc/apache2/sites-available/default file reads: > > __________________________ > NameVirtualHost * > > ? ? ? ? ServerAdmin webmaster at localhost > > ? ? ? ? DocumentRoot /var/www/ > ? ? ? ? > ? ? ? ? ? ? ? ? Options FollowSymLinks > ? ? ? ? ? ? ? ? AllowOverride None > ? ? ? ? > ? ? ? ? > ? ? ? ? ? ? ? ? #Options +ExecCGI Indexes FollowSymLinks MultiViews > ? ? ? ? ? ? ? ? Options All > ? ? ? ? ? ? ? ? AllowOverride None > ? ? ? ? ? ? ? ? Order allow,deny > ? ? ? ? ? ? ? ? Allow from all > ? ? ? ? ? ? ? ? #AddHandler mod_python .py > ? ? ? ? ? ? ? ? #PythonHandler mod_python.publisher > ? ? ? ? ? ? ? ? #PythonDebug On > > ? ? ? ? > > ? ? ? ? ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ > ? ? ? ? > ? ? ? ? ? ? ? ? AllowOverride None > ? ? ? ? ? ? ? ? Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch > ? ? ? ? ? ? ? ? Order allow,deny > ? ? ? ? ? ? ? ? Allow from all > ? ? ? ? > > ? ? ? ? ErrorLog /var/log/apache2/error.log > > ? ? ? ? # Possible values include: debug, info, notice, warn, error, > crit, > ? ? ? ? # alert, emerg. > ? ? ? ? LogLevel warn > > ? ? ? ? CustomLog /var/log/apache2/access.log combined > ? ? ? ? ServerSignature On > > ? ? Alias /doc/ "/usr/share/doc/" > ? ? > ? ? ? ? Options Indexes MultiViews FollowSymLinks > ? ? ? ? AllowOverride None > ? ? ? ? Order deny,allow > ? ? ? ? Deny from all > ? ? ? ? Allow from 127.0.0.0/255.0.0.0 ::1/128 > ? ? > > > __________________________ > > Thanks in advance > Gustavo From pedrof.abranches at gmail.com Sun Jun 22 17:13:33 2008 From: pedrof.abranches at gmail.com (abranches) Date: Sun, 22 Jun 2008 14:13:33 -0700 (PDT) Subject: Regular expression problem Message-ID: <181fe17d-61f0-40f4-89b4-99fe4c483bf7@k30g2000hse.googlegroups.com> Hello everyone. I'm having a problem when extracting data from HTML with regular expressions. This is the source code: You are ready in the next
    12M 48S And I need to get the remaining time. Until here, isn't a problem getting it, but if the remaining time is less than 60 seconds then the source becomes something like this: You are ready in the next
    36S I'm using this regular expression, but the minutes are always None... You are ready in the next.*?(?:>(\d+)M
    )?.*?(?:>(\d+)S) If I remove the ? from the first group, then it will work, but if there are only seconds it won't work. I could resolve this problem in a couple of python lines, but I really would like to solve it with regular expressions. Thanks, Pedro Abranches From __peter__ at web.de Tue Jun 17 03:42:59 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 17 Jun 2008 09:42:59 +0200 Subject: 'string'.strip(chars)-like function that removes from the middle? References: <48569B9E.6030206@admailinc.com> <200806161839.13647.omer@no-log.org> Message-ID: Terry Reedy wrote: > C?dric Lucantis wrote: > >> I don't see any string method to do that > > >>> 'abcde'.translate(str.maketrans('','','bcd')) > 'ae' > > I do not claim this to be better than all the other methods, > but this pair can also translate while deleting, which others cannot. You should mention that you are using Python 3.0 ;) The 2.5 equivalent would be >>> u"abcde".translate(dict.fromkeys(map(ord, u"bcd"))) u'ae' Peter From gagsl-py2 at yahoo.com.ar Thu Jun 12 05:29:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Jun 2008 06:29:41 -0300 Subject: h2py.py bug? References: <484E771D.1050404@arimaz.com> <484F7CDE.9000300@arimaz.com> Message-ID: En Wed, 11 Jun 2008 04:21:03 -0300, Gabriel Rossetti escribi?: > Gabriel Genellina wrote: >> En Tue, 10 Jun 2008 09:44:13 -0300, Gabriel Rossetti >> escribi?: >> >>> I wanted to use the h2py.py script (Tools/scripts/h2py.py) and it >>> didn't like char litterals : >>> >>> Skipping: PC_ERROR = ord() >>> >>> where my *.h file contained : >>> >>> #define PC_ERROR '0' >>> >>> I searched the web and found a post with the same error : >>> >>> http://mail.python.org/pipermail/python-list/2005-September/340608.html >>> >>> but it got no replies, I tried the fix and it works. I have the >>> following questions: >>> >>> 1) Why did it not get any attention, is something wrong with it? >>> 2) If nothing is wrong, did the fix not get applied because a bug >>> report wasn't filed? >> >> Very probably - bug reports outside the tracker are likely to go >> unnoticed or forgotten. >> > Ok, I'll file one then. >>> 3) Isn't turning a char literal into the ordinal value not contrary to >>> what a C programmer had in mind when he/she defined it? I mean if you >>> define a char literal then in python you would have used a string >>> value : >>> >>> #define PC_ERROR '0' >>> >>> would become : >>> >>> PC_ERROR = '0' >>> >>> in python, and if you intended to use the char type for an 8 bit >>> numerical value you would have done : >>> >>> #define PC_ERROR 0x30 >>> >>> where 0x30 is the '0' ascii hex value, so shouldn'it the line in the >>> diff (see the post) be : >>> >>> body = p_char.sub("'\\1'", body) >>> >>> instead of : >>> >>> body = p_char.sub("ord('\\1')", body) >> >> It's not so clear what's the intended usage - chars are also integers >> in C. (I prefer the current behavior, but certainly it may be wrong in >> several places). >> > Yes, true, but if you intend to use it as an integer, wouldn't you use a > numeric value instead of a character literal? Not always. Using characters as ordinal numbers is very common in that language. A small example: #define FIRST 'A' #define LAST 'Z' #define index(letter) ((letter)-FIRST) int accum[LAST-FIRST+1]; ... char x = some_word[0]; accum[index(x)]++; accum is an array of 26 integers, element 0 corresponding to letter 'A'. If one has to reproduce the exact same structure, in Python it would be: FIRST = ord('A') LAST = ord('Z') def index(letter): return ord(letter)-FIRST accum = [0 for i in range(LAST-FIRST+1)] x = some_word[0] accum[index(x)] += 1 Of course, in other cases, character constants are intended to be used as character data, so ord(...) is not the appropiate thing to do when converting to Python. But I don't think my example above is very contrived or uncommon - chars *are* integers from the C point of view, and some people isn't worried too much about the distinction, specially those who use C as their main or only language. -- Gabriel Genellina From robert.kern at gmail.com Wed Jun 11 17:58:02 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 11 Jun 2008 16:58:02 -0500 Subject: Numpy array to gzip file In-Reply-To: References: Message-ID: Sean Davis wrote: > I have a set of numpy arrays which I would like to save to a gzip > file. Here is an example without gzip: > > b=numpy.ones(1000000,dtype=numpy.uint8) > a=numpy.zeros(1000000,dtype=numpy.uint8) > fd = file('test.dat','wb') > a.tofile(fd) > b.tofile(fd) > fd.close() > > This works fine. However, this does not: > > fd = gzip.open('test.dat','wb') > a.tofile(fd) > > Traceback (most recent call last): > File "", line 1, in > IOError: first argument must be a string or open file As drobinow says, the .tofile() method needs an actual file object with a real FILE* pointer underneath it. You will need to call fd.write() on strings (or buffers) made from the arrays instead. If your arrays are large (as they must be if compression helps), then you will probably want to split it up. Use numpy.array_split() to do this. For example: In [13]: import numpy In [14]: a=numpy.zeros(1000000,dtype=numpy.uint8) In [15]: chunk_size = 256*1024 In [17]: import gzip In [18]: fd = gzip.open('foo.gz', 'wb') In [19]: for chunk in numpy.array_split(a, len(a) // chunk_size): ....: fd.write(buffer(chunk)) ....: > In the bigger picture, I want to be able to write multiple numpy > arrays with some metadata to a binary file for very fast reading, and > these arrays are pretty compressible (strings of small integers), so I > can probably benefit in speed and file size by gzipping. File size perhaps, but I suspect the speed gains you get will be swamped by the Python-level manipulation you will have to do to reconstruct the array. You will have to read in (partial!) strings and then put the data into an array. If you think compression will really help, look into PyTables. It uses the HDF5 library which includes the ability to compress arrays with gzip and other compression schemes. All of the decompression happens in C, so you don't have to do all of the manipulations at the Python level. If you stand to gain anything from compression, this is the best way to find out and probably the best way to implement it, too. http://www.pytables.org If you have more numpy questions, you will probably want to ask on the numpy mailing list: http://www.scipy.org/Mailing_Lists -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From omer at no-log.org Sun Jun 15 12:20:48 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Sun, 15 Jun 2008 18:20:48 +0200 Subject: problem with Py_BuildValue In-Reply-To: References: Message-ID: <200806151820.48809.omer@no-log.org> > Thank you. At least I can exclude another few error sources, now. > > >> I see nothing wrong with your code so I'd say it is somewhere else (did >> you snip any code between the end of the loop and the return?). >No. (Apart from freeing allocated memory.) I'm pretty sure we'll find something interesting here :) > > and if it doesn't help trace the content of your list > > after each iteration to see when the bad things happen (you can check the > > reference count of an object with obj->ob_refcnt). > > Seems ok. What I did to check this was placing this after building the > list: > > for (i=0; i < limit; i++) { > dummy = PyList_GetItem(python_return_value, i); > printf("%f\n", PyFloat_AsDouble(dummy)); > Py_CLEAR(dummy); > } PyList_GetItem returns a borrowed reference so you shoud _not_ unref it (this explains the refcnt -1 I think) Here's the code producing your message (from Objects/object.c in the python sources) : /* Implementation of PyObject_Print with recursion checking */ static int internal_print(PyObject *op, FILE *fp, int flags, int nesting) { if (op->ob_refcnt <= 0) /* XXX(twouters) cast refcount to long until %zd is universally available */ fprintf(fp, "", (long)op->ob_refcnt, op); } } I don't really understand its purpose, but it confirms that it's a ref count problem. Maybe the full source of your function could help ? -- C?dric Lucantis From hongfeng02 at gmail.com Wed Jun 18 13:16:33 2008 From: hongfeng02 at gmail.com (hongfeng02 at gmail.com) Date: Wed, 18 Jun 2008 10:16:33 -0700 (PDT) Subject: www.nikeadishoes.com Message-ID: <0caec560-47ca-4cd4-9f30-dbc2abb11cc2@j1g2000prb.googlegroups.com> because our company open no long time,and we have some pro in deals with oredr please make you new order to us ,i think we will have a good beginning !! Our website: www.nikeadishoes.com Choose your favorite products please trust us ,have a good beginning Email:shoesec at yahoo.com.cn MSN:shoes-ec at hotmail.com From eric.talevich at gmail.com Sun Jun 1 01:00:19 2008 From: eric.talevich at gmail.com (etal) Date: Sat, 31 May 2008 22:00:19 -0700 (PDT) Subject: Merging ordered lists Message-ID: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> Here's an algorithm question: How should I efficiently merge a collection of mostly similar lists, with different lengths and arbitrary contents, while eliminating duplicates and preserving order as much as possible? My code: def merge_to_unique(sources): """Merge the unique elements from each list in sources into new list. Using the longest input list as a reference, merges in the elements from each of the smaller or equal-length lists, and removes duplicates. @return: Combined list of elements. """ sources.sort(None, len, True) # Descending length ref = sources[0] for src in sources[1:]: for i, s in enumerate(src): if s and (ref[i] != s) and s not in ref: ref.insert(ref.index(src[i-1])+1, s) # Remove duplicates return [r for i, r in enumerate(ref) if r and r not in ref[i+1:]] This comes up with using the CSV module's DictWriter class to merge a set (list, here) of not-quite-perfect CSV sources. The DictWriter constructor needs a list of field names so that it can convert dictionaries into rows of the CSV file it writes. Some of the input CSV files are missing columns, some might have extras -- all of this should be accepted, and the order of the columns in the merged file should match the order of the input files as much as possible (not alphabetical). All of the list elements are strings, in this case, but it would be nice if the function didn't require it. Speed actually isn't a problem yet; it might matter some day, but for now it's just an issue of conceptual aesthetics. Any suggestions? From evidentemente.yo at gmail.com Tue Jun 24 05:50:46 2008 From: evidentemente.yo at gmail.com (evidentemente.yo) Date: Tue, 24 Jun 2008 02:50:46 -0700 (PDT) Subject: calling a .exe from Python Message-ID: Hi, i am trying to call a .exe from my .py file, i have found the exec function, but i'm not sure of how to use it:S would it be f.e.: execl (mypath/myfile.exe,myfile,arg1,arg2,...) ???? Another question is, when i call my .exe with exec, i understand that my .py file will stop running, and instead the new process will be launched instead of it. Is it true? Is there a way to launch my .exe without finishing my .py file?? thank you very much:) From a.harrowell at gmail.com Tue Jun 17 13:44:08 2008 From: a.harrowell at gmail.com (TYR) Date: Tue, 17 Jun 2008 10:44:08 -0700 (PDT) Subject: Making wxPython a standard module? References: <6bidd7F3bg8usU1@mid.uni-berlin.de> <87fxrfx0h0.fsf@physik.rwth-aachen.de> <48e9a145-d0f4-4ec3-9874-97d2cff1a91b@27g2000hsf.googlegroups.com> Message-ID: >" b = wx.Button(label="Click Me", action=myCallable) > Instead you used to have to create a button and then call > some utility function in some other object to bind that > button to a callable (IIRC this was one place where Window > IDs could be used). Now, the button actually has a method > you can use. It's still an extra step... That looks quite a lot like the behaviour of PythonForS60's appuifw class. Frex, a menu: appuifw.app.menu = [(u'Octopus', getfish(octopus)), (u'Cuttlefish', getfish(cuttlefish)), (u'Squid', ((u'Humboldt', getfish(humboldt)), (u'Giant', getfish(giantsquid)), (u'Colossal', getfish(colossal)))] gives you a menu with three options, the last of which has three sub- options, all of which call your getfish() function with their value. From grante at visi.com Sat Jun 14 15:26:24 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 14 Jun 2008 14:26:24 -0500 Subject: Creating a TCP/IP connection on already-networked computers References: <4853f269$0$11615$607ed4bc@cv.net> <4854123f$0$5017$607ed4bc@cv.net> <485413d0$0$4997$607ed4bc@cv.net> Message-ID: On 2008-06-14, John Salerno wrote: > John Salerno wrote: > >> ----- >> #!/usr/bin/env python >> >> from socket import * >> from time import ctime >> >> HOST = '192.168.1.100' > > >> ----- >> #!/usr/bin/env python >> >> from socket import * >> >> HOST = '192.168.1.100' > > A question about this. Is the "HOST" referring to the IP > address of the server computer in both of these cases? Yes. > Because when I ran the program and got to the part where it > says "connected from:" on the server side, it shows this same > IP address. Then you must have been either running the client program on the same machine as the server program or you've got some sort of NAT/port-forwarding going on. > Shouldn't it be something different, since the requests are > coming from a different computer than the server computer? Works fine for me. When I run the client program on a machine different than the server program, the server program prints out "connected from:" and then the client machine's IP address. -- Grant Edwards grante Yow! Maybe I should have at asked for my Neutron Bomb visi.com in PAISLEY -- From ironfroggy at socialserve.com Tue Jun 17 15:05:08 2008 From: ironfroggy at socialserve.com (Calvin Spealman) Date: Tue, 17 Jun 2008 15:05:08 -0400 Subject: Static memory allocation in Python In-Reply-To: <5868cf920806171134n33af0512j8ad93fc300fe015a@mail.gmail.com> References: <5868cf920806171134n33af0512j8ad93fc300fe015a@mail.gmail.com> Message-ID: On Jun 17, 2008, at 2:34 PM, Eduardo Henrique Tessarioli wrote: > Hi, > > I am running a very simple python application and I noted that the > memory allocation is something like 4,5M. > This is a problem in my case, because I have to run 2 thousand > process at the same time. > The memory I need is 100k or less. Is there any way to set this for > the python process? The runtime itself isn't as light as, say, the C stdlib. Now, there are a lot of shared libraries here, so you should measure not just a single instance, but how much it actually grows in overall system memory usage as you run more simultaneous python interpreters. > Regards, > Eduardo > -- > http://mail.python.org/mailman/listinfo/python-list From johnjsal at NOSPAMgmail.com Tue Jun 10 09:15:34 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 10 Jun 2008 09:15:34 -0400 Subject: chm file for download? Message-ID: <038f1951$0$3232$c3e8da3@news.astraweb.com> Is the chm doc file available for download from the Python website? I can't seem to find it. It would be nice to read through while I'm at work (where I don't have Python installed). Also, is it possible to use a chm file on Linux? Thanks. From sluggoster at gmail.com Wed Jun 11 16:09:38 2008 From: sluggoster at gmail.com (Mike Orr) Date: Wed, 11 Jun 2008 13:09:38 -0700 (PDT) Subject: ClassName.attribute vs self.__class__.attribute References: Message-ID: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> On Jun 5, 8:40 am, Gabriel Rossetti wrote: > Hello everyone, > > I had read somewhere that it is preferred to use > self.__class__.attribute over ClassName.attribute to access class (aka > static) attributes. I had done this and it seamed to work, until I > subclassed a class using this technique and from there on things started > screwing up. I finally tracked it down to self.__class__.attribute! What > was happening is that the child classes each over-rode the class > attribute at their level, and the parent's was never set, That's a misunderstanding of classes vs instances. If you have an instance of MyClass(Superclass), there is one instance but several classes. The instance is of MyClass; there is no instance of Superclass. 'self' has a .__class__ attribute because it's an instance, but MyClass and Superclass do not because they're already classes. Going further, self.a retrieves the instance attribute if it exists, or or MyClass.a if it doesn't, or Superclass.a if that doesn't. But assigning to self.a always assigns to an instance attribute. To assign a class attribute you must use .__class__ or TheClass. Likewise, to retrieve a class attribute that has been overridden by a subclass or instance, you must use .__class__ or TheClass. There's a very good reason to use self.__class__: it makes it possible to subclass your class. In Jason Orendorff's path.py, some path methods return new path objects. He uses 'path()' rather than self.__class__ to construct these. So if you subclass 'path' to extend it, these methods return path objects rather than your subclass objects. In my Unipath package which was written later, I use self.__class__ in these cases to allow users to extend my class. It's a little annoying that if you want to print a class's name in some unknown object, you have to use obj.__class__.__name__ if it's an instance, and obj.__name__ if it's a class. I sometimes wish classes had a .__class__ attribute that's the class itself, but I can see how that would cause its own confusion (and recursion). -- Mike Orr From markc.westwood at gmail.com Fri Jun 13 04:29:48 2008 From: markc.westwood at gmail.com (Mark Westwood) Date: Fri, 13 Jun 2008 01:29:48 -0700 (PDT) Subject: Point Of intersection between two plotted functions References: <2fd19881-27f8-48f3-bfa9-2d8a26f31920@26g2000hsk.googlegroups.com> Message-ID: Hi Let your 2 functions be f(x) and g(x). Then you have to solve the equation f(x) = g(x). For some functions it will be easier to determine intervals of the real line where f(x)-g(x) > 0 and where f(x)-g(x) < 0 and to find an interval in which the 2 intersect, which would probably be good enough for plotting. How straightforward any of this is depends entirely on the nature of your functions. Regards Mark On Jun 13, 7:34 am, arslanbur... at gmail.com wrote: > Is there anyway one could find ot the point of intersection between > any two plotted functions and also display them using gnuplot.py?? From tjreedy at udel.edu Sun Jun 8 04:19:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 8 Jun 2008 04:19:49 -0400 Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net><484ad07b$0$25721$607ed4bc@cv.net> <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> Message-ID: "Mensanator" wrote in message news:8d7c0912-422f-4480-a034-078f9dbcae24 at 2g2000hsn.googlegroups.com... | On Jun 7, 6:43?pm, "Terry Reedy" wrote: | > zip(range(9,2000000000), iterable) | | Oh, dear. You didn't actually try this, did you? Works fine in Py3, which is what I use now. From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 23 11:53:40 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 23 Jun 2008 17:53:40 +0200 Subject: Passing arguments to subclasses In-Reply-To: <7pgv54l0pfaa2l05c4l8f3bld1rskd4dtf@4ax.com> References: <7pgv54l0pfaa2l05c4l8f3bld1rskd4dtf@4ax.com> Message-ID: <485fc702$0$22189$426a74cc@news.free.fr> John Dann a ?crit : > May I ask a simple newbie question, which I presume is true, but for > which I can't readily find confirmation: > > Let's say I have a parent class with an __init__ method explicitly > defined: > > class ParentClass(object): > def __init__(self, keyword1, keyword2): > etc > > and I subclass this: > > class ChildClass(ParentClass): > # No __init__ method explicitly defined > > Now I presume that I can instantiate a child object as: > > child = ChildClass(arg1, arg2) > > and arg1, arg2 will be passed through to the 'constructor' of the > antecedent ParentClass (there being no overrriding __init__ method > defined for ChildClass) and mapping to keyword1, keyword2 etc. > > Have I understood this correctly? Yes. But you could have checked by yourself: bruno at bruno:~$ python Python 2.5.1 (r251:54863, Mar 7 2008, 03:41:45) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Parent(object): ... def __init__(self, kw1, kw2): ... print self, kw1, kw2 ... self.kw1, self.kw2 = kw1, kw2 ... >>> class Child(Parent): pass ... >>> c = Child("arg1", "arg2") <__main__.Child object at 0xb7ddeccc> arg1 arg2 >>> c.kw1 'arg1' >>> c.kw2 'arg2' >>> HTH From spoier at gmail.com Thu Jun 5 20:05:04 2008 From: spoier at gmail.com (Skye) Date: Thu, 5 Jun 2008 17:05:04 -0700 (PDT) Subject: Newb question: underscore Message-ID: What is this doing? print >> fd, _(__doc__) I'm guessing line-splitting __doc__ into a list, but what's that leading underscore do? Thanks! From mishok13 at gmail.com Wed Jun 18 03:31:34 2008 From: mishok13 at gmail.com (Andrii V. Mishkovskyi) Date: Wed, 18 Jun 2008 10:31:34 +0300 Subject: How do I create user-defined warnings? In-Reply-To: <1213749985.25016.8.camel@generator> References: <1213749985.25016.8.camel@generator> Message-ID: <192840a00806180031p6dc001f6sc8831004ad38c7a8@mail.gmail.com> 2008/6/18 Clay Hobbs : > I already know how to make user-defined exceptions, like this one: > > class MyException(Exception): > pass > > But for a module I'm making, I would like to make a warning (so it just > prints the warning to stderr and doesn't crash the program). I have > tried this: > > class MyWarning(Warning): > pass > > And it behaves like a normal error. Please help me, I can't figure out > what I'm doing wrong. Use 'warnings' module. http://docs.python.org/lib/module-warnings.html > > -- > Ratfink > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Wbr, Andrii Mishkovskyi. He's got a heart of a little child, and he keeps it in a jar on his desk. From d3vvnull at gmail.com Tue Jun 10 11:34:19 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Tue, 10 Jun 2008 10:34:19 -0500 Subject: Building 64-bit Python on AIX Message-ID: <170543c70806100834x5a7d33b4n15e19237bd0f2ca9@mail.gmail.com> Hi all. I am trying to rebuild Python on our AIX system in 64 bit so I can use our installed 64-bit UnixODBC library. Has anyone successfully done this and can they share the configure options they used? Thanks. Mike -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From h.goebel at goebel-consult.de Tue Jun 10 08:28:50 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Tue, 10 Jun 2008 14:28:50 +0200 Subject: ANN: pdfposter 0.4.2 Message-ID: I'm pleased to announce pdfposter 0.4.2, a tool to scale and tile PDF images/pages to print on multiple pages. http://pdfposter.origo.ethz.ch/download/ This version fixes a view minor bugs - some media-/poster-sizes (eg. Letter) have not beeb recogniced - some PDF files crashed the tool. Download --------------- :Quick Installation: easy_install -U pdfposter :Tarballs: http://pdfposter.origo.ethz.ch/download/ What is pdfposter? -------------------- Scale and tile PDF images/pages to print on multiple pages. ``Pdfposter`` can be used to create a large poster by building it from multple pages and/or printing it on large media. It expects as input a PDF file, normally printing on a single page. The output is again a PDF file, maybe containing multiple pages together building the poster. The input page will be scaled to obtain the desired size. This is much like ``poster`` does for Postscript files, but working with PDF. Since sometimes poster does not like your files converted from PDF. :-) Indeed ``pdfposter`` was inspired by ``poster``. For more information please refere to the manpage or visit the `project homepage `_. :Author: Hartmut Goebel :Copyright: GNU Public Licence v3 (GPLv3) :Homepage: http://pdfposter.origo.ethz.ch/ From frank at chagford.com Wed Jun 11 05:48:33 2008 From: frank at chagford.com (Frank Millman) Date: Wed, 11 Jun 2008 02:48:33 -0700 (PDT) Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: Thanks to all for the various replies. They have all helped me to refine my ideas on the subject. These are my latest thoughts. Firstly, the Decimal type exists, it clearly works well, it is written by people much cleverer than me, so I would need a good reason not to use it. Speed could be a good reason, provided I am sure that any alternative is 100% accurate for my purposes. My approach is based on expressing a decimal number as a combination of an integer and a scale, where scale means the number of digits to the right of the decimal point. Therefore 0.04 is integer 4 with scale 2, 1.1 is integer 11 with scale 1, -123.456 is integer -123456 with scale 3. I am pretty sure that any decimal number can be accurately represented in this form. All arithmetic is carried out using integer arithmetic, so although there may be rounding differences, there will not be the spurious differences thrown up by trying to use floats for decimal arithmetic. I use a class called Number, with two attributes - an integer and a scale. My first attempt required these two to be provided every time an instance was created. Then I realised that this would cause loss of precision if I chain a series of instances together in a calculation. The constructor can now accept any of the following forms - 1. A digit (either integer or float) and a scale. It uses the scale factor to round up the digit to the appropriate integer. 2. Another Number instance. It takes the integer and scale from the other instance. 3. An integer, with no scale. It uses the integer, and assume a scale of zero. 4. A float in string format (e.g. '1.1') with no scale. It uses the number of digits to the right as the scale, and scales the number up to the appropriate integer. For addition, subtraction, multiplication and division, the 'other' number can be any of 2, 3, or 4 above. The result is a new Number instance. The scale of the new instance is based on the following rule - For addition and subtraction, the new scale is the greater of the two scales on the left and right hand sides. For multiplication, the new scale is the sum of the two scales on the left and right hand sides. For division, I could not think of an appropriate rule, so I just hard- coded a scale of 9. I am sure this will give sufficient precision for any calculation I am likely to encounter. My Number class is now a bit more complicated than before, so the performance is not as great, but I am still getting a four-fold improvement over the Decimal type, so I will continue running with my version for now. My main concern is that my approach may be naive, and that I will run into situations that I have not catered for, resulting in errors. If this is the case, I will drop this like a hot potato and stick to the Decimal type. Can anyone point out any pitfalls I might be unaware of? I will be happy to show the code for the new Number class if anyone is interested. Thanks Frank From desothier at yahoo.com Wed Jun 25 05:55:16 2008 From: desothier at yahoo.com (antar2) Date: Wed, 25 Jun 2008 02:55:16 -0700 (PDT) Subject: python -regular expression - list element Message-ID: <62e21ec1-18f3-4572-b223-1b8a5c40688c@f63g2000hsf.googlegroups.com> Hello, I am a beginner in Python and am not able to use a list element for regular expression, substitutions. list1 = [ 'a', 'o' ] list2 = ['star', 'day', 'work', 'hello'] Suppose that I want to substitute the vowels from list2 that are in list1, into for example 'u'. In my substitution, I should use the elements in list1 as a variable. I thought about: for x in list1: re.compile(x) for y in list2: re.compile(y) if x in y: z = re.sub(x, 'u', y) but this does not work From bruno.42.desthuilliers at websiteburo.invalid Thu Jun 12 05:17:49 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 12 Jun 2008 11:17:49 +0200 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> References: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> Message-ID: <4850e95d$0$10444$426a74cc@news.free.fr> Mike Orr a ?crit : (snip) > 'self' has a .__class__ attribute because it's an > instance, but MyClass and Superclass do not because they're already > classes. Not true for new-style classes: >>> class Toto(object): pass ... >>> Toto.__class__ (snip) > I sometimes wish classes > had a .__class__ attribute that's the class itself, newstyle classes do have a class attribute, that refers to the metaclass. > but I can see how > that would cause its own confusion (and recursion). FWIW, metaclasses do have a class attribute that refers to itself !-) From larry.bates at websafe.com` Wed Jun 4 12:37:30 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 04 Jun 2008 11:37:30 -0500 Subject: [XP] Batch-print bunch of RTF files? In-Reply-To: References: Message-ID: nospam at nospam.com wrote: > Hello, > > I have about two hundred individual RTF files to print from an > XP host. Word 2000 doesn't seem to have this feature, so I'm looking > for a way to print those RTF files from an ActivePython script. Would > someone have some working code handy? > > Thank you. Sure it does, just not the way you think. - Click on Start-Settings-Printer and Faxes - Double-click the printer you want to print to - Open folder where your 200 RTF files are stored. - Drag and drop the file on to the printer window and your machine will launch and print each of thes in Word. -Larry From gherron at islandtraining.com Sun Jun 22 14:59:17 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 22 Jun 2008 11:59:17 -0700 Subject: -1/2 In-Reply-To: References: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> Message-ID: <485EA105.9090706@islandtraining.com> Christian Heimes wrote: > Serve Lau wrote: > >> What is the expected result of -1/2 in python? >> > > 0 > > No. That's not right. (It would be in C/C++ and many other languages.) See my other response for the correct answer. Gary Herron > Christian > > -- > http://mail.python.org/mailman/listinfo/python-list > From atrophier at uno.net Sun Jun 22 00:15:10 2008 From: atrophier at uno.net (Atrophier Bigarrés) Date: 22 Jun 2008 04:15:10 GMT Subject: Ryhmän sfnet.tietoliikenne.yhteydentarjoajat virallinen kuvaus References: Message-ID: <1213555441_2169@250.130.139.19> MTV 3. 07.06.2008. "Norjassa tuulivoima my?t?tuulessa. Norjan energiatarpeista PUOLET voidaan kattaa tuulivoimalla, kun nykysuunnitelmat toteutetaan! Kaiken kaikkiaan 130 tuulivoimalapuistohanketta on haettu rakennuslupaa Norjan energiavirastolta. Jos kaikille halukkaille my?nnet??n lupa energiantuotanto kasvaisi 56 terawatttitunnilla, mik? on noin puolet maan nykytuotannosta. N?iden lis?ksi 19 tuulihanketta on saanut rakennusluvan, mutta rakentamista ei ole viel? alettu." *Niin.. ..MYKIST?V??! .. On jo p?iv?n selv??, ett? Tanskan ja Saksan uskaliaat uudisenergiairtiotot ovat saamassa arvoisensa triumfin. Maailman energiaj?tit alkavat k??nty? ennenn?kem?tt?m?n massiivisesti pois ydinmenneisyydest? ja suuntaavat tuhdisti turpoaville uudisenergiasektoreille. Erityisherkkuna on nimenomaan toimivimman offshoremerituuliosuuden aukeaminen. Kun jopa Englannin kaltaiseen pataydintaantumusvaltioon rakennetaan parhaillaan maailman masiivisinta Loviisaluokan ofshoretuuloipuistoa, ydinalan korttipeli p??ttyi t?yskaatoon. Ja kohta s?hk?verkot my?s kautta Pohjolan suorastaan notkuvat tuskin en?? kymmenesosaa ydins?hk?kustannuksesta maksavaa 100% saasteetonta bulkkiekoenergiaa. 100% s??dett?v?t ja puolisen vuotta sitten Norjan Trondheimissa mitatut k?sitt?m?tt?m?n hyv?t tuulivoiman ***99% vuosipysyvyyshy?tysuhteet NELJ? kertaa paremmat kuin ydinreaktorirumiluksilla ajetut enemm?n kuin vakuuttivat.*** T?ss? on tulossa sellaiset energiantuotannon poistumat ydinvoiman kaltaisista uudiskyvytt?mist? vektoreista, ett? ydinvoiman mustapekka sopeutumiskyvytt?m?lle Suomelle on varmentumassa. T?h?n settiin kun Viro julkaisee tuuliaikeensa ja saadaan ilman muuta Ruotsi mukaan, niin ydinsuomi sotketaan mukavasti ydinsuohonsa, jopa omilla s?hk?markkinoillaan. KUKAAN EI TARVITSE sikakallista s??t?kyvyt?nt? ja EU:ssa maineensa mokanutta ydinvoimaa. Tulemme n?kem??n sellaisen ydinvastarinnan n?emm? MY?S talousmiesten jaloin ??nestyksin, ettei mit??n jakoa. HIENOA!)) From ladasky at my-deja.com Tue Jun 3 20:57:07 2008 From: ladasky at my-deja.com (John Ladasky) Date: Tue, 3 Jun 2008 17:57:07 -0700 (PDT) Subject: Import, site packages, my modules, Windows vs. Linux Message-ID: <4993bd3d-22aa-4e0d-a593-38c0f5e2d69a@m44g2000hsc.googlegroups.com> Hi folks, Running Python 2.5 on both a Windows XP laptop, and an Ubuntu Linux 7.04 desktop. I've gotten tired of maintaining multiple copies of my personal modules that I use over and over. I have copies of these files in the same directory as the main program I happen to be working on at the time. I've also downloaded FANN, and want to use its Python bindings. FANN does not seem to build automatically, like wxWidgets did. These two issues have led me to examine exactly how the import statement works, how the PYTHONPATH environment variable is constructed, and how to change it. On Windows I found a solution that works, but which may be a kludge. In the Python "site-packages" folder, I added a sub-folder called "my- packages". Then I created a text file, "my-packages.pth", containing the single line, "my-packages." Finally, I moved my common personal modules into the my-packages folder and deleted all of my clumsy duplicates. Import statements now work for all of my files on the Windows box, great! I then tried to use this same strategy in Linux, and saw that I don't automatically have the privileges needed to alter the site-packages folder. On my Windows box, my default account has Administrator privileges. On Linux I can, of course, use sudo to modify the site- packages folder. But the fact that I would have to use sudo has me asking -- is there something inappropriate, or unsafe in my approach? I want to know what is the *recommended* way to integrate my own personal modules with Python. Thanks! From a.harrowell at gmail.com Fri Jun 20 07:01:39 2008 From: a.harrowell at gmail.com (TYR) Date: Fri, 20 Jun 2008 04:01:39 -0700 (PDT) Subject: Strange re problem Message-ID: <2a0a6f87-f72e-4190-85f8-6e43821e313a@r66g2000hsg.googlegroups.com> OK, this ought to be simple. I'm parsing a large text file (originally a database dump) in order to process the contents back into a SQLite3 database. The data looks like this: 'AAA','PF',-17.416666666667,-145.5,'Anaa, French Polynesia','Pacific/ Tahiti','Anaa';'AAB','AU',-26.75,141,'Arrabury, Queensland, Australia','?','?';'AAC','EG',31.133333333333,33.8,'Al Arish, Egypt','Africa/Cairo','El Arish International';'AAE','DZ', 36.833333333333,8,'Annaba','Africa/Algiers','Rabah Bitat'; which goes on for another 308 lines. As keen and agile minds will no doubt spot, the rows are separated by a ; so it should be simple to parse it using a regex. So, I establish a db connection and cursor, create the table, and open the source file. Then we do this: f = file.readlines() biglist = re.split(';', f) and then iterate over the output from re.split(), inserting each set of values into the db, and finally close the file and commit transactions. But instead, I get this error: Traceback (most recent call last): File "converter.py", line 12, in biglist = re.split(';', f) File "/usr/lib/python2.5/re.py", line 157, in split return _compile(pattern, 0).split(string, maxsplit) TypeError: expected string or buffer Is this because the lat and long values are integers rather than strings? (If so, any ideas?) From bruno.42.desthuilliers at websiteburo.invalid Thu Jun 19 03:57:32 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 19 Jun 2008 09:57:32 +0200 Subject: Function argument conformity check In-Reply-To: <0efa09ce-dbf9-4699-b87c-34c2c3b271f0@34g2000hsh.googlegroups.com> References: <0efa09ce-dbf9-4699-b87c-34c2c3b271f0@34g2000hsh.googlegroups.com> Message-ID: <485a1167$0$17213$426a74cc@news.free.fr> dlists.cad at gmail.com a ?crit : > Hi. I am looking for a way to check if some given set of (*args, > **kwds) conforms to the argument specification of a given function, > without calling that function. import inspect help(inspect.getargspec) From aweraw at gmail.com Fri Jun 13 05:01:01 2008 From: aweraw at gmail.com (Aidan) Date: Fri, 13 Jun 2008 19:01:01 +1000 Subject: Comments on my first script? In-Reply-To: References: <7e3a7c92-6204-46dd-8df8-90218f2fb314@26g2000hsk.googlegroups.com> <4016716e-0ff7-41aa-951a-ed9562ff2ac8@m44g2000hsc.googlegroups.com> <7bb26acf-8b58-4d29-8e64-05a75eb5e584@d45g2000hsc.googlegroups.com> Message-ID: Chris wrote: > On Jun 13, 9:38 am, Phillip B Oldham wrote: >> Thanks guys. Those comments are really helpful. The odd semi-colon is >> my PHP background. Will probably be a hard habbit to break, that >> one! ;) If I do accidentally drop a semi-colon at the end of the line, >> will that cause any weird errors? >> >> Also, Chris, can you explain this: >> a, b = line.split(': ')[:2] >> >> I understand the first section, but I've not seen [:2] before. > > That's slicing at work. What it is doing is only taking the first two > elements of the list that is built by the line.split. slicing is a very handy feature... I'll expand on it a little OK so, first I'll create a sequence of integers >>> seq = range(10) >>> seq [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] "take element with index 4 and everything after it" >>> seq[4:] [4, 5, 6, 7, 8, 9] "take everything up to, but not including, the element with index 4" >>> seq[:4] [0, 1, 2, 3] "take the element with index 3 and everything up to, but not including, the element with index 6" >>> seq[3:6] [3, 4, 5] then there's the step argument "take every second element from the whole sequence" >>> seq[::2] [0, 2, 4, 6, 8] "take every second element from the element with index 2 up to, but not including, the element with index 8" >>> seq[2:8:2] [2, 4, 6] Hope that helps. From grflanagan at gmail.com Sun Jun 29 16:01:01 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Sun, 29 Jun 2008 13:01:01 -0700 (PDT) Subject: Docutils rst2html.py gives Unknown Directive type "toctree" References: Message-ID: On Jun 19, 11:19?pm, "Calvin Cheng" wrote: > Hi, > > I am attempting to convert a bunch of .txt files into html using the > docutils package. > > It works for most of the txt files except for the index.txt file which > gives 2 errors: > (1) Unknown Directive type "toctree" > (2) (ERROR/3) Unknown interpreted text role "ref". > > Any idea how I can fix this? > > Would be glad if someone who is familiar with docutils could point me > in the right direction. "toctree" is a directive specific to the sphinx documentation system: http://sphinx.pocoo.org/concepts.html#the-toc-tree You must have something like: .. toctree:: in your file. docutils won't recognise this. G. From cwitts at gmail.com Fri Jun 13 10:29:15 2008 From: cwitts at gmail.com (Chris) Date: Fri, 13 Jun 2008 07:29:15 -0700 (PDT) Subject: Create list from string References: Message-ID: <7e8cd275-67a6-4fb4-b618-180a38528cad@z72g2000hsb.googlegroups.com> On Jun 13, 4:15?pm, ericdaniel wrote: > Hi, > > I'm new to Python and I need to do the following: > > from this: ? s = "978654321" > to this : ? ? ?["978", "654", "321"] > > Any help is appreciated > > Thanks, > > Eric What you could do is iterate over the string appending the characters 1 at a time to a new string and when you hit the point you want to place it in your output list you can append it there and clear the temp string eg. length = 3 tmp_string = '' results = [] for i,character in enumerate(s): if not (i+1) % length: results.append(tmp_string) else: tmp_string += character I don't like this approach as you create to many temp items and fairly ugly. What you could do is to rather use slicing to build it. results = [] length = 3 for i in xrange(0,len(s),length): results.append(s[i:i+length]) And then the neatest approach would be to put that into a list comprehension instead s = "978654321" step = 3 output = [s[start:start+step] for start in xrange(0,len(s),step)] Those are just some ways to do it. Hope that helps From auch-ich-m at g-kein-spam.com Wed Jun 4 06:01:44 2008 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Wed, 04 Jun 2008 12:01:44 +0200 Subject: Best way to modify code without breaking stuff. References: Message-ID: <2531546.63WkQjL8G4@news.perlig.de> Jesse Aldridge wrote: > I've got a module that I use regularly. I want to make some extensive > changes to this module but I want all of the programs that depend on > the module to keep working while I'm making my changes. What's the > best way to accomplish this? Don't ;-) If the changes are that extensive it might be considerable to write a new module and switch the depending code to use that new module when you're done and they're ready. As mentioned in another posting revision control is a good thing as well. Not just for that task. nd From grante at visi.com Sun Jun 29 09:39:05 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 29 Jun 2008 08:39:05 -0500 Subject: complex numbers should respect the "I" representation References: <6c674bf8-f16b-40f1-81ef-72c009c08465@w1g2000prd.googlegroups.com> Message-ID: <38idndLnYqrkDfrVnZ2dnUVZ_gydnZ2d@posted.visi> On 2008-06-29, Roy Smith wrote: >> I think complex numbers should respect the "i" or "I" >> representation, instead of "j". No reason being cute and using >> a different character instead of the traditional >> representation? > > Ask any electrical engineer what j means. And ask them what "I" means. -- Grant Edwards grante Yow! HUGH BEAUMONT died at in 1982!! visi.com From Robert.Bossy at jouy.inra.fr Wed Jun 18 11:39:01 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 18 Jun 2008 17:39:01 +0200 Subject: Looking for lots of words in lots of files In-Reply-To: References: Message-ID: <48592C15.1020402@jouy.inra.fr> brad wrote: > Just wondering if anyone has ever solved this efficiently... not > looking for specific solutions tho... just ideas. > > I have one thousand words and one thousand files. I need to read the > files to see if some of the words are in the files. I can stop reading > a file once I find 10 of the words in it. It's easy for me to do this > with a few dozen words, but a thousand words is too large for an RE > and too inefficient to loop, etc. Any suggestions? The quick answer would be: grep -F -f WORDLIST FILE1 FILE2 ... FILE1000 where WORDLIST is a file containing the thousand words, one per line. The more interesting answers would be to use either a suffix tree or an Aho-Corasick graph. - The suffix tree is a representation of the target string (your files) that allows to search quickly for a word. Your problem would then be solved by 1) building a suffix tree for your files, and 2) search for each word sequentially in the suffix tree. - The Aho-Corasick graph is a representation of the query word list that allows fast scanning of the words on a target string. Your problem would then be solved by 1) building an Aho-Corasick graph for the list of words, and 2) scan sequentially each file. The preference for using either one or the other depends on some details of your problems: the expected size of target files, the rate of overlaps between words in your list (are there common prefixes), will you repeat the operation with another word list or another set of files, etc. Personally, I'd lean towards Aho-Corasick, it is a matter of taste; the kind of applications that comes to my mind makes it more practical. Btw, the `grep -F -f` combo builds an Aho-Corasick graph. Also you can find modules for building both data structures in the python package index. Cheers, RB From kyosohma at gmail.com Tue Jun 17 14:43:07 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 17 Jun 2008 11:43:07 -0700 (PDT) Subject: text alignment References: <39d1c620-9923-46e7-999d-ed86c8b465ff@34g2000hsh.googlegroups.com> <114f3f4c-4004-488b-86c5-4bf6416e15bd@l42g2000hsc.googlegroups.com> <8d563101-53f0-41d3-a544-ee0ba1d58db5@m36g2000hse.googlegroups.com> <657c1cb2-cfeb-4806-960c-15b3f25f6575@w7g2000hsa.googlegroups.com> Message-ID: <39ae3cec-c231-4196-8f9a-b567b9a47b5c@c65g2000hsa.googlegroups.com> On Jun 17, 1:20?pm, Gandalf wrote: > since you brought up this issue, please tell me where can I fine > menual for this library? You want the manual for wxPython? Go to the download page on the Official wxPython page and get the Docs & Demos package: http://wxpython.org/download.php That include the wxWidgets Reference. Also see: http://wxpython.org/onlinedocs.php > can i generate dynamic GUI from it? Not sure what you mean by this. If you know how to create a "dynamic GUI" with html/ajax or some such based on the user's interactions with your website, than it should work in the embedded browser just as well as it would in a non-embedded one. > If not, Is there any way to generate dynamic GUI (one that can change > according to the user input) with HTML-CSS- javascript similar > environment? Mike From david at abbottdavid.com Sun Jun 29 22:54:25 2008 From: david at abbottdavid.com (David) Date: Sun, 29 Jun 2008 22:54:25 -0400 Subject: How to invoke the Python idle In-Reply-To: <12ca7dc20806291949w34199ac2g9b4d4e88465cb328@mail.gmail.com> References: <08484763-05df-49ee-b308-2dd64b7e2379@e39g2000hsf.googlegroups.com> <48683F65.80906@abbottdavid.com> <12ca7dc20806291949w34199ac2g9b4d4e88465cb328@mail.gmail.com> Message-ID: <48684AE1.8010701@abbottdavid.com> Alon Ben-Ari wrote: > Thank you > > yes I have > This is what I got: > alon at linux:~> idle > bash: idle: command not found > alon at linux:~> > > Any idea > ? > > Alon > > > On Sun, Jun 29, 2008 at 10:05 PM, David > wrote: > > Only-Trouble wrote: > > Hi all > I am running openSUSE 10.3 > I am learning python on my own, it seems like the system has > already > installed a python IDLE > The question is how to invoke it? > > > Thanks > > Only-Trouble > -- > http://mail.python.org/mailman/listinfo/python-list > > > > > Did you try to enter idle in a terminal? > > -- > Powered by Gentoo GNU/LINUX > http://www.linuxcrazy.com > > Could be you need something like this; http://rpmfind.net//linux/RPM/opensuse/updates/10.3/i586/python-idle-2.5.1-39.2.i586.html -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From maric at aristote.info Tue Jun 10 02:52:48 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 10 Jun 2008 08:52:48 +0200 Subject: Can I find out (dynamically) where a method is defined? In-Reply-To: References: Message-ID: <200806100852.48792.maric@aristote.info> Le Monday 09 June 2008 19:03:18 allendowney at gmail.com, vous avez ?crit?: > Thanks Maric! That's very close to what I want, although using dir() > can be misleading because if you invoke it on class B you get all of > class A's methods as well. I took your idea and wrote it up like > this: > > def find_defining_class(obj, meth_name): > """find and return the class object that will provide > the definition of meth_name (as a string) if it is > invoked on obj. > """ > for ty in type(obj).mro(): > if meth_name in ty.__dict__: > return ty > return None > > Cheers, > Allen > Oh ! you're just right, my first writing of this was : for m in 'a', 'b', 'c' : print [ t for t in type(i).mro() if m in t.__dict__ ] which I carelessly ad wrongly rewrote using dir while posting. Sorry. -- _____________ Maric Michaud From larudwer at freenet.de Thu Jun 5 15:25:28 2008 From: larudwer at freenet.de (Rüdiger Werner) Date: Thu, 5 Jun 2008 21:25:28 +0200 Subject: Interesting Math Problem References: Message-ID: "BEES INC" schrieb im Newsbeitrag news:mailman.105.1212653740.1044.python-list at python.org... ... Problem: Star Ratings People can rate cheeseburgers on my website with a star rating of 0-5 stars (whole stars only), 5 being mighty tasty and 0 being disgusting. I would like to show the average of everyone's ratings of a particular cheeseburger to the nearest half star. I have already calculated the average rating as a float (star_sum) and the total number of people that rated the particular cheeseburger (num_raters). The result should be stored as a float in a variable named "stars." My Solution (in Python): Well seems this is a typical half even rounding problem. See http://mail.python.org/pipermail/python-list/2008-April/485889.html for a long discussion However since your problem looks like a typical homework problem i made my example buggy by intention. However the result should be correct. have fun! def myround(x): d, m = divmod(x, 2) return 2*d + round(m - 1) + 1 num = 1.5 for _i in xrange(30): print num, ' -> ', myround(num * 2)/2 num -= 0.1 >pythonw -u "test18.py" 1.5 -> 1.5 1.4 -> 1.5 1.3 -> 1.5 1.2 -> 1.0 1.1 -> 1.0 1.0 -> 1.0 0.9 -> 1.0 0.8 -> 1.0 0.7 -> 0.5 0.6 -> 0.5 0.5 -> 0.5 0.4 -> 0.5 0.3 -> 0.5 0.2 -> 0.0 0.1 -> 0.0 -1.94289029309e-016 -> 0.0 < --- hint for bug -0.1 -> 0.0 -0.2 -> 0.0 -0.3 -> -0.5 -0.4 -> -0.5 -0.5 -> -0.5 -0.6 -> -0.5 -0.7 -> -0.5 -0.8 -> -1.0 -0.9 -> -1.0 -1.0 -> -1.0 -1.1 -> -1.0 -1.2 -> -1.0 -1.3 -> -1.5 -1.4 -> -1.5 >Exit code: 0 to avoid the bug have a look at: http://mail.python.org/pipermail/python-list/2008-April/485934.html and try this example: num = 3 for _i in xrange(num * 10,-num *10, -1): if myround(float(_i)/10) != myround(num): print num, " -> ", myround(num ), " --- ", myround(float(_i)/10) print "-----" num -= 0.1 From salmoni at gmail.com Thu Jun 12 23:00:17 2008 From: salmoni at gmail.com (Alan J. Salmoni) Date: Thu, 12 Jun 2008 20:00:17 -0700 (PDT) Subject: Notify of change to list Message-ID: <8b34cc2b-aa3a-4788-b849-1f926284c7ca@m36g2000hse.googlegroups.com> Hello everyone, I searched through groups to find an appropriate answer to this one but could only find these which didn't meet my program's needs: http://groups.google.com/group/comp.lang.python/browse_thread/thread/53a0bfddeedf35b2/5e4b7119afa5f8df?lnk=gst&q=monitor+change+in+mutable#5e4b7119afa5f8df, http://groups.google.com/group/comp.lang.python/browse_thread/thread/b7e0bb2cf9e2f5cd/bccfd49a5c8a56e2?lnk=gst&q=monitor+change+in+object#bccfd49a5c8a56e2. My question is how can my program be notified of a change to a class attribute that is a list? I have a class defined that has a list as an attribute and the program needs to know when the user changes this attribute either completely or elementwise via an interpreter built-in to the program. Using __setattr__ I can be informed whenever it is rebound (x.attr = [2,3,4]) but not when changes are made elementwise (x.attr[1] = 99). I tried using properties to get changes but again the same result occurs. class c(object): def __init__(self): self._x = 0 def getx(self): return self._x def setx(self, x): print "setting x: ", x self._x = x x = property(getx, setx) # all of the following need to be caught a.x = [1,2,3] # is rebound from 0 so is caught a.x[1] = 99 # element-wise change only which isn't caught a.x = [4,5,6] # is rebound so is caught a.x[0:3] = [11,12,13] # though a "complete" change in terms of elements, this is element-wise and is not rebound and is thus not caught >>> setting x: [1, 2, 3] setting x: [4, 5, 6] >From what I understand, changes will only be caught if the attribute is completely rebound (ie, completely re-assigned), but I cannot force my users to do this. Short of hacking around with the interpreter to catch element-wise reassignments (possible, but I'd rather avoid), can anyone suggest a way to do this? Alan From news at prodata.co.uk Tue Jun 17 07:28:08 2008 From: news at prodata.co.uk (John Dann) Date: Tue, 17 Jun 2008 12:28:08 +0100 Subject: Numeric type conversions Message-ID: I'm new to Python and can't readily find the appropriate function for the following situation: I'm reading in a byte stream from a serial port (which I've got working OK with pyserial) and which contains numeric data in a packed binary format. Much of the data content occurs as integers encoded as 2 consecutive bytes, ie a 2-byte integer. I'm guess that there should be a function available whereby I can say something like: My2ByteInt = ConvertToInt(ByteStream[12:13]) to take a random example of the 2 bytes occurring at positions 12 and 13 in the byte stream. Can anyone point me in the right direction towards a suitable function please? NB I don't know without further checking exactly how the bytes are encoded, but I'm just transcribing some code across from a Windows VB.Net program and these same bytes could be read straight into a standard 2-byte signed short int, so I can be confident that it's a fairly standard Windows-compatible encoding. From sjmachin at lexicon.net Sat Jun 21 10:06:06 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 21 Jun 2008 07:06:06 -0700 (PDT) Subject: Getting column names from a cursor using ODBC module? References: Message-ID: <386e874a-ed66-4f1e-8eed-bf88e1b561c9@i18g2000prn.googlegroups.com> On Jun 21, 11:58 pm, dana... at yahoo.com wrote: > Is there any way to retrieve column names from a cursor using the ODBC > module? Or must I, in advance, create a dictionary of column position > and column names for a particular table before I can access column > values by column names? I'd prefer sticking with the ODBC module for > now because it comes standard in Python. > > I'm using Python 2.4 at the moment. > > Thanks. From mr.edel at gmx.at Tue Jun 3 12:28:04 2008 From: mr.edel at gmx.at (Matt) Date: Tue, 03 Jun 2008 16:28:04 +0000 Subject: ctypes, function pointers and a lot of trouble References: <832f57f4-7d26-44a5-8abe-567165cc532f@f36g2000hsa.googlegroups.com> Message-ID: > The docs say CFUNCTYPE(restype, *argtypes), so: > > cstreamopen = CFUNCTYPE(c_uint, c_ushort, c_uint) > > is saying that the result type is c_uint, not void. I think you need: > > cstreamopen = CFUNCTYPE(None, c_uint, c_ushort, c_uint) > > instead. Hm, thanks, now I can access my data in the functions and also write them but the program keeps terminating right at the point when the "open" function finishes. Unfortunately everything closes and I get no error messages. I did some additional work in the meantime and changed my code so it has the correct datatypes now: --------------------------CODE-------------------------------------------- def pystreamopen (contextH, mode, pErr): print "opening..." print contextH.contents.dwBufferSize #just to check the structure print mode #tells about what the DLL wants to do with this stream contextH.contents.mode = c_byte(5) #5=Permission to read and write contextH.contents.lPos = c_uint(0) #start position print pErr.contents pErr.contents = c_uint(0) cstreamopen = CFUNCTYPE(None, POINTER(MemStreamData), c_ushort, POINTER(c_uint)) def pystreamclose (contextH, pErr): print "closing..." pass cstreamclose = CFUNCTYPE(None, POINTER(MemStreamData), POINTER(c_uint)) def pystreamread (contextH, pBuf, pBufsize, pErr): print "reading..." pass cstreamread = CFUNCTYPE(None, POINTER(MemStreamData), c_uint, c_uint, POINTER(c_uint)) def pystreamtell (contextH, pErr): print "telling... . . .etc... --------------------------/CODE-------------------------------------------- and the function call: --------------------------CODE-------------------------------------------- errorcode = cdsdk.CDGetReleasedData(devicehandle, byref(cbfunct), c_uint(0), c_uint(0), byref(datainfo), POINTER(cdStgMedium)(data)) --------------------------/CODE-------------------------------------------- while it's running my program prints the following and then exits/terminates: >>> opening...990001 >>> 2 >>> c_ulong(0L) >>> Script terminated. ##This is a message by my editor (SPE) I also tried different editors, but get the same result... Anyway, meanwhile decided to try a different approach. Maybe I have more luck by having the function write the data directly into a file on the HDD. Doe anyone know how to translate the following into Python/ctypes? I googled quite a lot before but all topic-related I found was my own posting here in this NG :S --------------------------CODE-------------------------------------------- pFilStrm->hFile = CreateFile( pFilStrm->szFileName, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL ); --------------------------/CODE-------------------------------------------- This function is obviously a default C-function that generates a file and returns a c-handle to that file. In my case I'd need exactly such a handle to get things working... Furthermore there's a writefile function I'd need to translate too: --------------------------CODE-------------------------------------------- WriteFile( pFilStrm->hFile, pBuf, dwNumberOfBytesToWrite, pBufsize, NULL ); --------------------------/CODE-------------------------------------------- Ideas? Thanks and best wishes, Matt From patrickstinson.lists at gmail.com Thu Jun 5 14:36:15 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Thu, 5 Jun 2008 10:36:15 -0800 Subject: Please unregister this mail-address out of mailing-list. In-Reply-To: <48482EF4.2060801@gmail.com> References: <48482EF4.2060801@gmail.com> Message-ID: <6214d7a20806051136t5a9bbac2l5008ba3c1794b53e@mail.gmail.com> you can unsubscribe yourself at the list info page (the same page you subscribed from) On Thu, Jun 5, 2008 at 10:22 AM, Hank @ITGroup wrote: > Dear Python Staff, > I am writing this letter to unsubscribe this mail-address from python > mail-list. One problem is that this python community is so active that I > always lost myself to find my business emails. So, I want to quit this > mail-address from you, and want to set up a specific mail-box to receive all > python mails. > Since could find a way to unsubscribe the mails, I need to write this letter > to you. Please help. > > BTW, python is indeed great, thank you all for any supports. > > Hank. > > -- > http://mail.python.org/mailman/listinfo/python-list > From bj_666 at gmx.net Tue Jun 3 01:05:55 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Jun 2008 05:05:55 GMT Subject: php vs python References: Message-ID: <6ak1pjF379qfdU2@mid.uni-berlin.de> On Mon, 02 Jun 2008 18:21:26 -0700, Joel Koltner wrote: > "Arnaud Delobelle" wrote in message > news:m2y75oa1xp.fsf at googlemail.com... >> This is wrong, because if you know well one language only, you tend to >> think that the principles that underpin it are universal. So you will >> try to shoehorn these principles into any other language you use. > > Fair point, although I guess I was assuming the language you were good in was > something that covers, say, 90% of contemporary programming practices, e.g., > something like C++ : If you're truly good at C++ (and percentage-wise of all > programmers, relatively few are), there are not many things that I'm aware of > that are tremendously different in any other programming language. Function > decorators from Java and some of the function programming stuff from Lisp, > perhaps, but those are pretty small additions (well within the "10%"). I think you are talking about something a little different than Arnaud. You are talking about the 10% that's new in another language that has to be learned additionally and Arnaud is talking about the stuff the programmer already knows about the old language that somewhat works in the new one but is all but optimal and thus has to be *unlearned*. From C++ to Python or Java this is RAII and deterministic destructors for instance. Other old habits from people coming to Python are: using indexes where they are not needed, trivial getters and setters, putting *everything* into classes and every class into a module, and so on. Another difference are internal versus external iterators. In Python you write the loop outside the iterable and pull the items out of it. In other languages (Ruby, Io, ?) iterables do internal iteration and you give them a function where all item are "pushed" into one at a time. > Perhaps I should reduce my claim to those good at programming in any "first > class" language like C++ are generally going to write at least above-average > code in any other language. :-) What makes C++ a "first class" language? And did you quote "first class" for the same reason than I did? ;-) Ciao, Marc 'BlackJack' Rintsch From martin at v.loewis.de Sun Jun 22 14:33:14 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 22 Jun 2008 20:33:14 +0200 Subject: Bind compiled code to name? In-Reply-To: References: Message-ID: <485e9aea$0$637$9b622d9e@news.freenet.de> > If string `source_code` contains Python source code, how can I execute > that code, and bind it to some name? I tried compiling with: > > code_object = compile(source_code, 'errorfile', 'exec') > > but then what to do with `code_object`? > > P.S. > If my intentions aren't that clear, this is what I'm trying to do. I want > to emulate this: > > import some_module as some_name > > but with my code in `some_module` string, and not in file. > d = {} exec source_code in d some_name = d['some_name'] HTH, Martin From alexnbryan at gmail.com Tue Jun 10 14:57:48 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 10 Jun 2008 11:57:48 -0700 (PDT) Subject: problems with opening files due to file's path In-Reply-To: <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> Message-ID: <17762276.post@talk.nabble.com> That would work, but not for what I want. See the file could be anywhere on the user's system and so the entire path will be unique, and that didn't work with a unique path. What is the subprocess module you are talking about? Mike Driscoll wrote: > > On Jun 10, 1:25?pm, "Thomas Morton" > wrote: >> maybe try string substitution... not sure if that's really the BEST way >> to >> do it but it should work >> >> startfile(r"%s"%variable) > > > I concur. That should work. A slightly more in depth example (assuming > Windows): > > os.startfile(r'C:\Documents and Settings\%s\Desktop\myApp.exe' % > username) > > or > > os.startfile(r'C:\Program Files\%s' % myApp) > > Hopefully this is what you are talking about. If you were referring to > passing in arguments, than you'll want to use the subprocess module > instead. > > >> >> -------------------------------------------------- >> From: "Alexnb" >> Sent: Tuesday, June 10, 2008 7:05 PM >> To: >> Subject: Re: problems with opening files due to file's path >> >> >> >> > Well, now i've hit another problem, this time being that the path will >> be >> > a >> > variable, and I can't figure out how to make startfile() make it raw >> with >> > a >> > variable, if I put startfile(r variable), it doesn't work and >> > startfile(rvariable) obviously won't work, do you know how to make that >> > work >> > or better yet, how to take a regular string that is given and make >> every >> > single "\" into a double "\\"? >> > > > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17762276.html Sent from the Python - python-list mailing list archive at Nabble.com. From bob at mellowood.ca Mon Jun 16 18:02:56 2008 From: bob at mellowood.ca (bvdp) Date: Mon, 16 Jun 2008 15:02:56 -0700 Subject: Simple and safe evaluator References: <1de31143-7d8e-42e9-ae9d-8b0a0274ddc3@e53g2000hsa.googlegroups.com> Message-ID: George Sakkis wrote: > On Jun 16, 4:47 pm, bvdp wrote: > >> 2. I thought I'd be happy with * / + -, etc. Of course now I want to add >> a few more funcs like int() and sin(). How would I do that? > > For the builtin eval, just populate the globals dict with the names > you want to make available: > > import math > > globs = {'__builtins__' : None} > > # expose selected builtins > for name in 'True False int float round abs divmod'.split(): > globs[name] = eval(name) > > # expose selected math constants and functions > for name in 'e pi sqrt exp log ceil floor sin cos tan'.split(): > globs[name] = getattr(math,name) > > return eval(s, globs, {}) > Thanks. That was easy :) > The change to the _ast version is left as an exercise to the reader ;) And I have absolutely no idea on how to do this. I can't even find the _ast import file on my system. I'm assuming that the _ast definitions are buried in the C part of python, but that is just a silly guess. Bob. From miller.paul.w at gmail.com Thu Jun 19 18:14:21 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Thu, 19 Jun 2008 15:14:21 -0700 (PDT) Subject: Google-like "Did you mean... ?" search algorithm Message-ID: <7a8313a1-1536-4754-ab4d-9cce4fa1b31a@y38g2000hsy.googlegroups.com> This is a wee bit OT, but I am looking for algorithms to implement search suggestions, similar to Google's "Did you mean... ?" feature. Can anyone point me to web pages, journal articles, implementations (preferably in Python!), or any other resources in this area? Thanks! From mnordhoff at mattnordhoff.com Sat Jun 14 05:59:55 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sat, 14 Jun 2008 09:59:55 +0000 Subject: write Python dict (mb with unicode) to a file In-Reply-To: References: Message-ID: <4853969B.6050909@mattnordhoff.com> dmitrey wrote: > hi all, > what's the best way to write Python dictionary to a file? > > (and then read) > > There could be unicode field names and values encountered. > Thank you in advance, D. pickle/cPickle, perhaps, if you're willing to trust the file (since it's basically eval()ed)? Or JSON (use simplejson or the enhanced version of cjson), though I doubt it would be super-fast. -- From __peter__ at web.de Sun Jun 15 07:48:23 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Jun 2008 13:48:23 +0200 Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> Message-ID: ram.rachum at gmail.com wrote: > Quick question: > I have python code that does a lot of floating point arithmetic. How > do I make it do the arithmetic in 64 bit? (I have a 64 bit CPU.) If > I'll install a 64-bit operating system, will that do the trick? The Python float type uses a C double internally which is 64 bit even on 32 bit CPUs. Peter From tgrav at mac.com Fri Jun 6 17:15:42 2008 From: tgrav at mac.com (Tommy Grav) Date: Fri, 6 Jun 2008 17:15:42 -0400 Subject: Q about object identity In-Reply-To: <48499D95.50006@stoneleaf.us> References: <48499D95.50006@stoneleaf.us> Message-ID: <4FF2364B-9F3C-4F15-A655-C86DB22C926E@mac.com> On Jun 6, 2008, at 4:27 PM, Ethan Furman wrote: > vronskij at gmail.com wrote: >> Hello, >> I am testing object identity. >> If I do it from the interpreter, I get strange results. >>>>> *print [] is []* >> *False* >>>>> print id([]), id([]) >> 3083942700 3083942700 >> Why is that? Isn't this an error? in the first statement the two []'s are in memory at the same time and have different id() signatures. For the second statement the first id([]) is evaluated and release from memory and then the second id([]) is evaluated and release from memory. Since only one of them exist at a time they can have the same id() signature. Cheers Tommy From kyosohma at gmail.com Mon Jun 9 10:42:49 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 9 Jun 2008 09:42:49 -0500 Subject: How to get full path to script? In-Reply-To: References: Message-ID: On Mon, Jun 9, 2008 at 12:37 AM, bukzor wrote: > On Jun 8, 12:52 pm, kj wrote: >> In "Mark Tolonen" writes: >> >> >import os >> >print os.path.abspath(__file__) >> >> Great. Thanks! >> >> Kynn >> >> -- >> NOTE: In my address everything before the first period is backwards; >> and the last period, and everything after it, should be discarded. > > Note that this doesn't quite work for symbolic links or compiled > scripts, depending on your requirements. > -- > http://mail.python.org/mailman/listinfo/python-list > For my compiled scripts, I usually use this variation: path = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))) It's always worked for me. Mike From kris at FreeBSD.org Tue Jun 24 11:31:17 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Tue, 24 Jun 2008 17:31:17 +0200 Subject: Bit substring search In-Reply-To: <5135a9f6-d8a5-4812-88b5-bc5fa28ece71@25g2000hsx.googlegroups.com> References: <5043fee7-444b-41dd-a419-77550595d273@79g2000hsk.googlegroups.com> <5135a9f6-d8a5-4812-88b5-bc5fa28ece71@25g2000hsx.googlegroups.com> Message-ID: <48611345.1070308@FreeBSD.org> bearophileHUGS at lycos.com wrote: > Kris Kennaway: >> Unfortunately I didnt find anything else useful here yet :( > > I see, I'm sorry, I have found hachoir quite nice in the past. Maybe > there's no really efficient way to do it with Python, but you can > create a compiled extension, so you can see if it's fast enough for > your purposes. > To create such extension you can: > - One thing that requires very little time is to create an extension > with ShedSkin, once installed it just needs Python code. > - Cython (ex-Pyrex) too may be okay, but it's a bit trikier on Windows > machines. > - Using Pyd to create a D extension for Python is often the faster way > I have found to create extensions. I need just few minutes to create > them this way. But you need to know a bit of D. > - Then, if you want you can write a C extension, but if you have not > done it before you may need some hours to make it work. Thanks for the pointers, I think a C extension will end up being the way to go, unless someone has beaten me to it and I just haven't found it yet. Kris From nospam at nospam.com Sun Jun 1 12:16:33 2008 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 01 Jun 2008 18:16:33 +0200 Subject: [Business apps for Windows] Good grid + calendar, etc.? References: <0fcd01c8c3e7$54919d70$0203a8c0@MOUSE> Message-ID: On Sun, 01 Jun 2008 11:24:17 -0400, python at bdurham.com wrote: >Instead of the COM approach, have you considered using a local, client >based Python server as a container for your business logic and GUI >(DHTML, AJAX)? But web-based apps are even worse, since the set of widgets is even more basic, and web programming is hell. That's why I don't bother, and write fat apps instead. It'd be awesome if someone came up with a commercial offer of widgets that are either missing or not feature-rich enough in wxPython for real business apps. From paddy3118 at googlemail.com Fri Jun 13 10:49:48 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 13 Jun 2008 07:49:48 -0700 (PDT) Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <878wx9leiv.fsf@ara.blue-cable.net> Message-ID: <26b1f5cb-54cf-4ab2-9630-054fa8a39acb@z72g2000hsb.googlegroups.com> On Jun 13, 1:12 pm, Karsten Heymann wrote: > Hi Mark, > > > > Mark writes: > > I have a scenario where I have a list like this: > > > User Score > > 1 0 > > 1 1 > > 1 5 > > 2 3 > > 2 1 > > 3 2 > > 4 3 > > 4 3 > > 4 2 > > > And I need to add up the score for each user to get something like > > this: > > > User Score > > 1 6 > > 2 4 > > 3 2 > > 4 8 > > > Is this possible? If so, how can I do it? I've tried looping through > > the arrays and not had much luck so far. > > Although your problem has already been solved, I'd like to present a > different approach which can be quite a bit faster. The most common > approach seems to be using a dictionary: > > summed_up={} > for user,vote in pairs: > if summed_up.has_key(user): > summed_up[user]+=vote > else: > summed_up[user]=vote > > But if the list of users is compact and the maximum value is known > before, the using a list and coding the user into the list position is > much more elegant: > > summed_up=list( (0,) * max_user ) > for user,vote in pairs: > summed_up[user] += vote > > I've run a quick and dirty test on these approaches and found that the > latter takes only half the time than the first. More precisely, with > about 2 million pairs, i got: > > * dict approach: 2s > (4s with "try: ... except KeyError:" instead of the "if") > * list approach: 0.9s > > BTW this was inspired by the book "Programming Pearls" I read some > years ago where a similar approach saved some magnitudes of time > (using a bit field instead of a list to store reserved/free phone > numbers IIRC). > > Yours, > Karsten How does your solution fare against the defaultdict solution of: d = collections.defaultdict(int) for u,s in zip(users,score): d[u] += s - Paddy From kaaveland at gmail.com Thu Jun 12 17:58:36 2008 From: kaaveland at gmail.com (=?iso-8859-1?q?Robin_K=E5veland?= Hansen) Date: Thu, 12 Jun 2008 21:58:36 +0000 (UTC) Subject: Python noob's simple config problem References: Message-ID: On Thu, 12 Jun 2008 21:32:34 +0000, kj wrote: > I'm sure this is a simple, but recurrent, problem for which I can't hit > on a totally satisfactory solution. > > As an example, suppose that I want write a module X that performs some > database access. I expect that 99.999% of the time, during the > foreseeable future, the database connection parameters will remain > unchanged. The only exception that I envision for this would be during > testing or debugging. > > Given all this, I am tempted to turn these connection parameters into > hard-coded module attributes that I can always override (i.e. overwrite) > when necessary. > > But for as long as I can remember the dogma has been that hard-coded > values are bad, and that one should use other techniques, such as > configuration files, or parameters to a suitable constructor, etc. > > This is where I begin to get confused: whose responsibility is it to > know of and read the config file? I can think of two distinct > scenarios: 1) module X is being used by a large, full-fledged > application A that already uses a config file for its own configuration; > 2) module X is being used by a simple script that has no need for a > config file. In case 1 I'd be glad to let application A set module X's > connection parameters using values read from its own (i.e. A's) config > file; this minimizes the number of config files that need to be > maintained. In case 2, however, it would be preferable for module X to > read its connection params from its own (i.e. X's) config file. In this > way the script won't have to bother setting some parameters that are in > fact practically constant... > > After going round and round on this, my original idea of hard-coding the > values as module attributes begins to look pretty attractive again. > > How would you handle such situations? > > Thanks! > > kynn I think I would just abstract it away with a "getter" for the connection, a function that takes some optional parameters, if not supplied, it simply fetches them from a default configuration. Ie: def connect(params=None): if params is None: return dblayer.connect(conf["default"]) else: return dblayer.connect(params) Unless I have misunderstood you completely? Now people can change your scripts config file, and if someone wants to use your code, they can use the getter directly. I hope this is of some help. From ThuongqDo at gmail.com Fri Jun 27 16:49:42 2008 From: ThuongqDo at gmail.com (Ryuke) Date: Fri, 27 Jun 2008 13:49:42 -0700 (PDT) Subject: How to get a multicast to wait for all nodes? References: <476d7eed-f0f2-4509-97be-152ea634fb0c@j1g2000prb.googlegroups.com> Message-ID: On Jun 27, 8:09?am, "Colin J. Williams" wrote: > Ryuke wrote: > > I have a code that receives gps information from nodes and gives off > > its own coordinates via radios connected by Ethernet. ?but the code > > continues to run after receiving only 1 set of coordinates, how do i > > get it to wait for multiple nodes to send before continuing > > You might provide wth significant part > of the code you have written. > > Colin W. oops. guess that's important, here's part of it #Get local node network view data from RIB using SNMP over Ethernet mynodeID = snmpget(RIB_HOST, MYNODE_ID) # print '[netge module] MYnode ID =',mynodeID netdict = snmpwalk(RIB_HOST,MIB_BASE) netdict[MYNODE_ID] = mynodeID print '[netge module] MyNode ID = ',netdict[MYNODE_ID] sorted_keys = sorted(netdict) # for key in sorted_keys: print '%s\t\t%s' % (key,netdict[key]) for c in netdict[NODE_LIST][1:]: print '[netge module] NbrNode %d'% ord(c) #Create heart beat data packet for multicast xfer # gpsdata.append(time.ctime()) print '[netge module] mynode location = ',netdict[MYNODE_LOCATION] # netdict[MYNODE_LOCATION] = ' '.join(gpsdata) netdict[MYNODE_LOCATION] = gpsdata print '[netge module] mynode location = ',netdict[MYNODE_LOCATION] heartbeat = ' '.join(netdict[MYNODE_LOCATION]) print '[netge module] heartbeat=',heartbeat #Send mulitcast heart beat packet of local node view of network sock.sendto(heartbeat,(MULTICAST_IP_ADDR, MULTICAST_PORT)) print '[netge module] multicast send' #Receive mulitcast heart beat data #ReceiveHB() print '[netge module] multicast receive=',sock.recv(1024) #Create KMZ file for local node view of network # CreateKMZfile(netdict) node = [] latitude = [] longitude = [] altitude = [] kml_nodes = '' kml_links = '' MAX_NUM = int(netdict[NUMBEROFNODES]) # MAX_NUM = len(netdict[NODE_LIST]) # print MAX_NUM From johnjsal at NOSPAMgmail.com Thu Jun 12 11:13:38 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 12 Jun 2008 11:13:38 -0400 Subject: Making wxPython a standard module? References: <48512f69$0$11262$c3e8da3@news.astraweb.com> <6bcqtpF3btl4sU1@mid.uni-berlin.de> Message-ID: <48513c49$0$11199$c3e8da3@news.astraweb.com> "Diez B. Roggisch" wrote in message news:6bcqtpF3btl4sU1 at mid.uni-berlin.de... > This has been discussed before. While tkInter might not be the greatest > toolkit out there it has two extreme advantages: > > - it is comparably small regarding the footprint. Few external > dependencies, small libraries, small python-wrapping. > > - it is available on a wide range of platforms. > > - it is very stable, not only wrt bugs but also regarding features. > There > is no external pressure to update it frequently. > > - it is easily maintainable. Ok, that was more than two advantages! :) But those are good points. I was wondering about the size of wx too. Probably huge compared to Tkinter. > And on a personal note: I find it *buttugly*. But that has nothing to do > with the reasons given above - nor do I have any weight in the decision to > include it or not... :) You find what ugly? The look of wxPython apps, or the code itself? To me it seems very nice, but what do I know! I also have started using XRC (putting the GUI in an xml file instead of in the program), so I see less of the code clutter my program. From ianb at colorstudy.com Wed Jun 11 12:19:12 2008 From: ianb at colorstudy.com (Ian Bicking) Date: Wed, 11 Jun 2008 09:19:12 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> Message-ID: On Jun 7, 6:30?am, Nick Craig-Wood wrote: > Here is an attempt at a killable thread > > ?http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496960 > > and > > ?http://sebulba.wikispaces.com/recipe+thread2 I use this recipe in paste.httpserver to kill wedged threads, and it works okay. It seems to kill threads that are genuinely wedged, e.g., if you try to read past the end of a socket. It takes surprisingly long, up to a minute to actually send the exception to a thread. But it's just a normal exception and seems to act reasonably. Obviously this is not a great system, but it's better than having a background process hang because of problem code elsewhere in the system. It also isn't any worse than kill -9, which is ultimately what a multiprocess system has to do to misbehaving worker processes. Still, to try to mitigate problems with this I set up a supervisor process and if there is a lot of problems with worker threads I'll have the entire process self-destruct so it can be restarted by the supervisor. The code is rather... organic in its development. But you can see it in the ThreadPool here: http://svn.pythonpaste.org/Paste/trunk/paste/httpserver.py Ian From mccredie at gmail.com Thu Jun 5 16:39:32 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 5 Jun 2008 13:39:32 -0700 (PDT) Subject: Token Error: EOF in multiline statement References: Message-ID: <8d7b532c-9801-4a56-b9fa-ca0e7e152bdf@e39g2000hsf.googlegroups.com> On Jun 5, 12:58 pm, maehhheeyy wrote: > I'm not sure what it means but it always highlights the last line with > nothing on it. My program has 63 lines and it highlights the 64th > line. This keeps popping up whenever I try to run my program. Can you > please help me fix this? You are going to have to post the code or at least the exception text. It sounds like the last line of your code is missing a needed parentheses, but it is impossible to know without more input. Matt From johnjsal at gmailNOSPAM.com Sat Jun 14 14:54:02 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sat, 14 Jun 2008 14:54:02 -0400 Subject: Creating a TCP/IP connection on already-networked computers In-Reply-To: <4854123f$0$5017$607ed4bc@cv.net> References: <4853f269$0$11615$607ed4bc@cv.net> <4854123f$0$5017$607ed4bc@cv.net> Message-ID: <485413d0$0$4997$607ed4bc@cv.net> John Salerno wrote: > ----- > #!/usr/bin/env python > > from socket import * > from time import ctime > > HOST = '192.168.1.100' > ----- > #!/usr/bin/env python > > from socket import * > > HOST = '192.168.1.100' A question about this. Is the "HOST" referring to the IP address of the server computer in both of these cases? Because when I ran the program and got to the part where it says "connected from:" on the server side, it shows this same IP address. Shouldn't it be something different, since the requests are coming from a different computer than the server computer? From fetchinson at googlemail.com Wed Jun 25 04:03:29 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 25 Jun 2008 01:03:29 -0700 Subject: automatically import modules upon interpreter invocation Message-ID: Hi folks, this seems like a very basic thing but I couldn't find a solution. I always do the following after starting the python interpreter (on linux): import rlcompleter import readline readline.parse_and_bind("tab: complete") Is there a way of making python execute the above whenever it starts up so that I don't have to type it all the time? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From i.i at i.i Sun Jun 22 14:35:26 2008 From: i.i at i.i (Josip) Date: Sun, 22 Jun 2008 20:35:26 +0200 Subject: Storing value with limits in object References: <2b0f1f77-98a2-4e1a-9427-7b7936ee7bf0@d77g2000hsb.googlegroups.com> Message-ID: > I bet you didn't even try this, unless your definition of "works" > includes a "RuntimeError: maximum recursion depth exceeded". Here's a > a working version: Actually, the version I'm using is somewhat bigger. I removed docstrings and recklessly stripped away some methods to make it shorter concise and incorrect. > For (most) math.* functions it suffices to define __float__, so the > above works. For making it behave (almost) like a regular number, > you'd have to write many more special methods: > http://docs.python.org/ref/numeric-types.html. > Here's a possible start: > (...) Yes, this is very close to what I was looking for. It implements all the functionality except asssigning values. And speed is not an issue for my application. Thanks. From russblau at hotmail.com Wed Jun 4 13:02:51 2008 From: russblau at hotmail.com (Russell Blau) Date: Wed, 4 Jun 2008 13:02:51 -0400 Subject: re References: <6anvi4F38ei08U1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote in message news:6anvi4F38ei08U1 at mid.uni-berlin.de... > David C. Ullrich schrieb: >> Say I want to replace 'disc' with 'disk', but only >> when 'disc' is a complete word (don't want to change >> 'discuss' to 'diskuss'.) The following seems almost >> right: >> >> [^a-zA-Z])disc[^a-zA-Z] >> >> The problem is that that doesn't match if 'disc' is at >> the start or end of the string. Of course I could just >> combine a few re's with |, but it seems like there should >> (or might?) be a way to simply append a \A to the first >> [^a-zA-Z] and a \Z to the second. > > Why not > > ($|[\w])disc(^|[^\w]) > > I hope \w is really the literal for whitespace - might be something > different, see the docs. No, \s is the literal for whitespace. http://www.python.org/doc/current/lib/re-syntax.html But how about: text = re.sub(r"\bdisc\b", "disk", text_to_be_changed) \b is the "word break" character, it matches at the beginning or end of any "word" (where a word is any sequence of \w characters, and \w is any alphanumeric character or _). Note that this solution still doesn't catch "Disc" if it is capitalized. Russ From pfreixes at gmail.com Thu Jun 19 18:27:37 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Fri, 20 Jun 2008 00:27:37 +0200 Subject: Google-like "Did you mean... ?" search algorithm In-Reply-To: <7a8313a1-1536-4754-ab4d-9cce4fa1b31a@y38g2000hsy.googlegroups.com> References: <7a8313a1-1536-4754-ab4d-9cce4fa1b31a@y38g2000hsy.googlegroups.com> Message-ID: <207312b70806191527j1ba14dd1jb7e558d97273cea2@mail.gmail.com> Do you need a [1] ngram theory, with this you can solve a orthographical problems, suggestion searches and other thinks [1] http://en.wikipedia.org/wiki/N-gram On Fri, Jun 20, 2008 at 12:14 AM, wrote: > This is a wee bit OT, but I am looking for algorithms to implement > search suggestions, similar to Google's "Did you mean... ?" feature. > Can anyone point me to web pages, journal articles, implementations > (preferably in Python!), or any other resources in this area? > > Thanks! > -- > http://mail.python.org/mailman/listinfo/python-list > -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From sri_annauni at yahoo.co.in Fri Jun 20 13:56:38 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Fri, 20 Jun 2008 23:26:38 +0530 (IST) Subject: Execute a script on a remote machine Message-ID: <515422.11724.qm@web7902.mail.in.yahoo.com> This is ok. Is there any other way to find it out? Thanks, Srini ----- Original Message ---- From: Gerhard H?ring To: python-list at python.org Sent: Friday, 20 June, 2008 10:03:30 PM Subject: Re: Execute a script on a remote machine srinivasan srinivas wrote: > Hi, > My requirement is i have to execute a python script on a remote machine as a subprocess from a python script and to get the subprocess pid of the process running the script. Is there anyway to do that?? > I have used subprocess.popen() method to do that. I have done as following: > executable = '/usr/bin/rsh' > args = [executable, hostname, scriptname] > pid = subprocess.popen(args) > It returned the pid of rsh. But i am interested in the pid of the process running the script. > Can anyone help me out here? Using os.getpid() you can find out the pid of the script and communicate it back to the caller. -- Gerhard -- http://mail.python.org/mailman/listinfo/python-list Save all your chat conversations. Find them online at http://in.messenger.yahoo.com/webmessengerpromo.php From Bob.Swithers at comcast.net Sat Jun 7 23:37:15 2008 From: Bob.Swithers at comcast.net (BobAtVandy) Date: Sat, 7 Jun 2008 23:37:15 -0400 Subject: How to get System.Timers.Timer Message-ID: <2KSdncr7xeVoztbVnZ2dnUVZ_qninZ2d@comcast.com> I'll greatly appreciate any help on this. Actually 2 questions: 1. I believe I need to use the Windows timer System.Timers.Timer . The examples I find on the web all access that timer by 'import System' . (That's System with a capital S.) I have pywin32 installed and 'import System' doesn't find System so I gather it's not in that package. Where does one get the package with Windows' System class? 2. The reason I've been looking at System.Timers.Timer is that I've written a windows-display app and I also use a timer from wx.PyTimer. However, I cannot close the window by clicking the X (Close button) at the top right of the window. And, I then tried explicitly capturing an OnClose event and that doesn't fire either. I then discovered that if I disable the wx.PyTimer, the window can be closed, and so I'm looking to try to use System.Timers.Timer under the theory (hope) that will avoid this problem of the window's not being close-able. Can anyone explain why the window won't close? Is System.Timers.Timer likely to solve my problem? If not, what would? Again, MANY thanks to anyone who can steer me in the right direction. From Russ.Paielli at gmail.com Thu Jun 5 21:09:40 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Thu, 5 Jun 2008 18:09:40 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> <4847d203$0$32733$426a74cc@news.free.fr> <87lk1jzgri.fsf@mulj.homelinux.net> Message-ID: <39a7805f-6590-4505-bfa2-0735090d553b@t12g2000prg.googlegroups.com> On Jun 5, 2:57 pm, Hrvoje Niksic wrote: > "Russ P." writes: > > By the way, my recollection is that in C++ access defaults to private > > if nothing is declared explicity. So normally the "private" > > declaration is unnecessary. If it is left out, your little trick won't > > work. > > How about #define class struct I never thought of that one. I wonder what the C++ gurus would say about that. Let me guess. They'd probably say that the access restrictions are for your own good, and bypassing them is bound to do you more harm than good in the long run. And they'd probably be right. Just because you can break into a box labeled "DANGER HIGH VOLTAGE," that doesn't make it a good idea. This just goes to show that the whole idea of using header files as simple text insertions is flaky to start with, and adding the preprocessor just compounds the flakiness. Needless to say, I'm not a big fan of C and C++. From fetchinson at googlemail.com Mon Jun 9 20:23:28 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 9 Jun 2008 17:23:28 -0700 Subject: access variables from one Python session to another on the same machine? In-Reply-To: <6ea6b084-3897-43f9-b8e0-dff52b47f1a0@w1g2000prd.googlegroups.com> References: <6ea6b084-3897-43f9-b8e0-dff52b47f1a0@w1g2000prd.googlegroups.com> Message-ID: > Suppose I have two different command windows going on the same > machine, each running their own Python interpreters. > > Is it possible to access the variables in one of the interpreter- > sessions from the other? > > It turns out I have limited control over one of the sessions (i.e. > cannot control all the code that is run from there), but complete > control over the other. > > I get the feeling this has been asked before, but I'm not sure how to > pose the question in such a way that it would show up on a search. > It's confusing. Depending on what 'limited control' means, the simplest choice would be writing stuff to a plain text file from the master and reading it from the slave. This may or may not work depending on your environment though. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From lajam at caramail.com Fri Jun 27 09:51:52 2008 From: lajam at caramail.com (lajam at caramail.com) Date: Fri, 27 Jun 2008 06:51:52 -0700 (PDT) Subject: where is the error? References: <8f8e1bf7-78b0-4292-9d56-396527b9dfb1@z66g2000hsc.googlegroups.com> <15ea1cb1-76a3-4fd3-8e4c-521b9aefcca2@m3g2000hsc.googlegroups.com> Message-ID: <014f77d9-0d16-4e70-8c6d-b1d728d14dff@25g2000hsx.googlegroups.com> > > I think that you mean that diff_temp will be an array of the numberS > (plural) of the lines (rows?) in values array that met the -2 < x < 2 > criterion. Now you want to be able to use diff_temp to get the > corresponding subset of some other array. Am I getting close? I think that you're getting close. I want to get the lines that met the criterion. Diff_temp is an array containing the values of the lines. So bascially, > Now you want to be able to use diff_temp to get the corresponding > subset of some other array. Am I getting close? yes > Perhaps you need something like other_array.take(diff_temp) ? And my problem was that the commands worked on windows but not on linux. > By the way, shouldn't you be using numpy? I thought numarray was going > away by mid-2008 i.e. now. I know, but i'm not sure that it's the problem. Thanks Cedric From george.sakkis at gmail.com Wed Jun 18 17:05:48 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 18 Jun 2008 14:05:48 -0700 (PDT) Subject: Function argument conformity check References: <0efa09ce-dbf9-4699-b87c-34c2c3b271f0@34g2000hsh.googlegroups.com> <9577cf2e-4440-4d97-b8e8-1dbc00bfca68@34g2000hsh.googlegroups.com> Message-ID: <69945a53-6e27-428a-a92a-5a9eab695134@e53g2000hsa.googlegroups.com> On Jun 18, 3:41?pm, dlists.... at gmail.com wrote: > On Jun 18, 3:13 pm, C?dric Lucantis wrote: > > > > > Hi, > > > Le Wednesday 18 June 2008 20:19:12 dlists.... at gmail.com, vous avez ?crit : > > > > Hi. I am looking for a way to check if some given set of (*args, > > > **kwds) conforms to the argument specification of a given function, > > > without calling that function. > > > > For example, given the function foo: > > > def foo(a, b, c): pass > > > > and some tuple args and some dict kwds, is there a way to tell if i > > > _could_ call foo(*args, **kwds) without getting an exception for those > > > arguments? I am hoping there is a way to do this without actually > > > writing out the argument logic python uses. > > > Each function object is associated to a code object which you can get with > > foo.func_code. Two of this object's attributes will help you: co_argcount and > > co_varnames. The first is the number of arguments of the function, and the > > second a list of all the local variables names, including the arguments > > (which are always the first items of the list). When some arguments have > > default values, they are stored in foo.func_defaults (and these arguments are > > always after non-default args in the co_argnames list). > > > Finally, it seems that some flags are set in code.co_flags if the function > > accepts varargs like *args, **kwargs, but I don't know where these are > > defined. > > > Note that I never found any doc about that and merely guessed it by playing > > with func objects, so consider all this possibly wrong or subject to change. > > > -- > > C?dric Lucantis > > I am aware of these attributes, although you can get them all in a > more organized form using the getfullargspec function in the inspect > module from the standard library. > > The problem is that using these attributes, I would essentially have > to re-write the logic python uses when calling a function with a given > set of arguments. I was hoping there is a way to get at that logic > without rewriting it. Sure; copy it from someone that has already done it ;-) http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/551779 HTH, George From jeff at jmcneil.net Wed Jun 4 16:26:23 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 4 Jun 2008 16:26:23 -0400 Subject: Unable to write output from os.path.walk to a file. In-Reply-To: <125994.42643.qm@web52909.mail.re2.yahoo.com> References: <125994.42643.qm@web52909.mail.re2.yahoo.com> Message-ID: <82d28c40806041326m2a26695t233d019ffa583c8c@mail.gmail.com> What exactly are you trying to accomplish? If you're just looking for the contents of a directory, it would be much easier to simply call os.listdir(dirinput) as that will return a list of strings that represent the entries in dirinput. As it stands, 'os.path.walk' will return None in your example, thus the reason f.writelines is failing, the error says something about a required iterable, no? You ought to look at os.walk anyways, as I believe it is the preferred approach when walking a directory hierarchy. It's a generator that will yield a tuple that contains (dirname, subdirectories, filenames). It seems that is what you're looking for? Thanks, Jeff On Wed, Jun 4, 2008 at 2:54 PM, Paul Lemelle wrote: > I Am trying to output the os.path.walk to a file, but the writelines method complains.... > > Below is the code, any helpful suggestions would be appreciated. > > def visit(arg, dirnames, names): > print dirnames > > > > > dirinput = raw_input("Enter directory to read: ") > > listdir = os.path.walk (dirinput, visit, None) > > f = open("walktxt", "w") > > f.writelines(listdir) > > f.close() > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From ptmcg at austin.rr.com Thu Jun 12 09:45:56 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 12 Jun 2008 06:45:56 -0700 (PDT) Subject: get keys with the same values References: Message-ID: <3fdafa74-2043-4052-bdec-843f69d9e5fa@e39g2000hsf.googlegroups.com> On Jun 12, 6:41?am, David C. Ullrich wrote: > On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader > wrote: > > >Hello, > > >I have a dictionary and will get all keys which have the same values. > > > d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} > > dd = {} > > for key, value in d.items(): > ? try: > ? ? dd[value].append(key) > ? except KeyError: > ? ? dd[value] = [key] > Instead of all that try/except noise, just use the new defaultdict: >>> from collections import defaultdict >>> >>> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} >>> >>> dd = defaultdict(list) >>> for key, value in d.items(): ... dd[value].append(key) ... >>> for k,v in dd.items(): ... print k,':',v ... 1 : ['a', 'e'] 2 : ['c'] 3 : ['b', 'd'] 4 : ['f'] -- Paul From basti.wiesner at gmx.net Tue Jun 10 07:56:21 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Tue, 10 Jun 2008 13:56:21 +0200 Subject: Separators inside a var name References: Message-ID: Rainy at Dienstag 10 Juni 2008 02:53: > Well, I agree, this is terrible. If I were Guido I'd > make a very explicit rule that a certain naming > scheme is preferred and other schemes are very bad. FWIW, there is a preferred naming scheme outlined in PEP 8. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From jaraco at jaraco.com Fri Jun 13 12:28:45 2008 From: jaraco at jaraco.com (Jason R. Coombs) Date: Fri, 13 Jun 2008 10:28:45 -0600 Subject: namedtuple suggestions In-Reply-To: References: <318037bd-e126-4c41-ac65-c2afb9fd768d@w7g2000hsa.googlegroups.com> Message-ID: <750B64C66078B34D918257A1AC004DB20307B0@messiah.jaraco.com> I also agree with your point on concatting. I used that syntax because it seemed more clear, given the already awkward syntax. And while the original motivation of namedtuple might be to avoid having to make a class or subclass, subclasses have already emerged even within the standard library (see lib/urlparse for a prime example of extending the namedtuple class). Regards, Jason -----Original Message----- From: Calvin Spealman [mailto:ironfroggy at socialserve.com] Sent: Friday, 13 June, 2008 12:17 To: Jason R. Coombs Cc: python-list at python.org Subject: Re: namedtuple suggestions On Jun 13, 2008, at 11:17 AM, Jason R. Coombs wrote: > I see a new function in (python 2.6) lib/collections called > namedtuple. This is a great function. I can see many places in my > code where this will be immensely useful. > > I have a couple of suggestions. > > My first suggestion is to use self.__class__.__name__ instead of the > hard-coded typename in __repr__, so that subclasses don't have to > override these methods just to use the correct name. > > def __repr__(self): > return self.__class__.__name__ + '(%(reprtxt)s)' %% self > \n I feel like a large point of NamedTuple is for those cases where you need a small object with some attributes _without_ creating a subclass. Useful for mocks, for example, or when you need to trick a function into dealing with a quick proxy or stub. If a large point is not needing to create a class but instead creating a cheap object, should it be a good idea to then subclass the very thing that was intended to help you avoid creating a class in the first place? What do you gain subclassing it? However, I always think a repr reflecting a type name should reflect the correct type, so I'm not disagreeing on that point. But, just don't use concating :-) -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 6580 bytes Desc: not available URL: From nick at craig-wood.com Sat Jun 28 07:32:35 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 28 Jun 2008 06:32:35 -0500 Subject: C++ or Python References: Message-ID: Kurda Yon wrote: > I would like to know what are advantages of Python in comparison with C > ++? In which cases and why Python can be a better tool than C++? Python is a lot more fun than C++ ;-) Anyway no need to use one or the other... I've done projects where we've embedded python into into a large C++ program to give easy scriptability to our application in a real language. I've also done the reverse - embedded C/C++ into python. And for the really easy option there is ctypes. Given a blank canvas I'd start with python and then add a bit of C/C++ if some part of it was running too slowly. If there were existing C/C++ libraries then I'd use ctypes to interface with them. I don't think I ever want to start another large C++ app - been there, done that, got the (mental) scars to prove it ;-) All my humble opinion of course! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From gagsl-py2 at yahoo.com.ar Fri Jun 13 13:31:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Jun 2008 14:31:18 -0300 Subject: GIL cpu multi core usage problem References: <207312b70806091126t6d9c3479hfe39368cd06b029e@mail.gmail.com> <207312b70806130455h4db9c6dn91485837b7a4bf1c@mail.gmail.com> Message-ID: En Fri, 13 Jun 2008 08:55:30 -0300, Pau Freixes escribi?: > When you say this "C extensions (usually) release the GIL when they don't > call into any Python code" do you talk about this macros ? > > Py_BEGIN_ALLOW_THREADS > > Py_END_ALLOW_THREADS Exactly. -- Gabriel Genellina From kurdayon at yahoo.com Mon Jun 30 19:44:07 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Mon, 30 Jun 2008 16:44:07 -0700 (PDT) Subject: Functions associated with a class. Message-ID: Hi, I start to learn the object oriented programing in Python. As far as I understood, every class has a set of corresponding methods and variables. For me it is easy to understand a method as a one-argument function associated with a class. For example, if I call "x.calc" and "y.calc" and if "x" and "y" belongs to different classes I, actually, call to different function (the first one is associated with the first class and the second one with the second class). If "x" and "y" belongs to the same class, the "x.calc" and "y.calc" refer to the same function (but called with different arguments ("x" and "y", respectively)). In the above described case we have one-argument function. But what should we do if we one two have a two-argument function. For example, we want to have a method "calc" which take two objects and returns one value. How do we call this method? Like "x&y.calc"? Or just calc(x,y)? In the case of the one-argument functions Pythons automatically decide which function to call (associated with the first class or with the second class). Will it be the same in the case of the two-argument function. I am not sure that I am clear. If I am not clear, just ask me. I will try to reformulate my questions. Thank you. From mccredie at gmail.com Wed Jun 18 13:54:29 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 18 Jun 2008 10:54:29 -0700 (PDT) Subject: How to split a string containing nested commas-separated substrings References: <0b568cf3-ecce-4da0-9d23-1cbfe47a5fe7@m36g2000hse.googlegroups.com> Message-ID: <31c424a3-15cf-4ecb-bcf6-5edd24aa19ca@s50g2000hsb.googlegroups.com> On Jun 18, 10:19 am, Robert Dodier wrote: > Hello, > > I'd like to split a string by commas, but only at the "top level" so > to speak. An element can be a comma-less substring, or a > quoted string, or a substring which looks like a function call. > If some element contains commas, I don't want to split it. > > Examples: > > 'foo, bar, baz' => 'foo' 'bar' 'baz' > 'foo, "bar, baz", blurf' => 'foo' 'bar, baz' 'blurf' > 'foo, bar(baz, blurf), mumble' => 'foo' 'bar(baz, blurf)' 'mumble' > > Can someone suggest a suitable regular expression or other > method to split such strings? > > Thank you very much for your help. > > Robert You might look at the shlex module. It doesn't get you 100%, but its close: >>> shlex.split('foo, bar, baz') ['foo,', 'bar,', 'baz'] >>> shlex.split( 'foo, "bar, baz", blurf') ['foo,', 'bar, baz,', 'blurf'] >>> shlex.split('foo, bar(baz, blurf), mumble') ['foo,', 'bar(baz,', 'blurf),', 'mumble'] Using a RE will be tricky, especially if it is possible to have recursive nesting (which by definition REs can't handle). For a real general purpose solution you will need to create a custom parser. There are a couple modules out there that can help you with that. pyparsing is one: http://pyparsing.wikispaces.com/ Matt From martin at v.loewis.de Sun Jun 1 14:43:54 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 01 Jun 2008 20:43:54 +0200 Subject: ValueError: unknown locale: UTF-8 In-Reply-To: References: Message-ID: <4842edea$0$25496$9b622d9e@news.freenet.de> > ValueError: unknown locale: UTF-8 >>>> > > This is on open bug or is there more to it? Do you have an environment variable set who is named either LANG or starts with LC_? Regards, Martin From ironfroggy at socialserve.com Mon Jun 16 09:20:35 2008 From: ironfroggy at socialserve.com (Calvin Spealman) Date: Mon, 16 Jun 2008 09:20:35 -0400 Subject: PEP 372 -- Adding an ordered directory to collections In-Reply-To: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> Message-ID: <745B0ED0-F59E-4588-9209-A90282AEDD5E@socialserve.com> This gets my +1, for what its worth. I don't really see a good reason not to include the insert() method, however. I don't see that it would complicate things much, if at all. >>> d = odict([('a', 42), ('b', 23)]) >>> d.insert(1, ('c', 19)) >>> d collections.odict([('a', 42), ('c', 19), ('b', 23)]) On Jun 16, 2008, at 4:37 AM, Armin Ronacher wrote: > Abstract > ======== > > This PEP proposes an ordered dictionary as a new data structure for > the ``collections`` module, called "odict" in this PEP for short. The > proposed API incorporates the experiences gained from working with > similar implementations that exist in various real-world applications > and other programming languages. > > > Rationale > ========= > > In current Python versions, the widely used built-in dict type does > not specify an order for the key/value pairs stored. This makes it > hard to use dictionaries as data storage for some specific use cases. > > Some dynamic programming languages like PHP and Ruby 1.9 guarantee a > certain order on iteration. In those languages, and existing Python > ordered-dict implementations, the ordering of items is defined by the > time of insertion of the key. New keys are appended at the end, keys > that are overwritten and not moved. > > The following example shows the behavior for simple assignments: > >>>> d = odict() >>>> d['parrot'] = 'dead' >>>> d['penguin'] = 'exploded' >>>> d.items() > [('parrot', 'dead'), ('penguin', 'exploded')] > > That the ordering is preserved makes an odict useful for a couple of > situations: > > - XML/HTML processing libraries currently drop the ordering of > attributes, use a list instead of a dict which makes filtering > cumbersome, or implement their own ordered dictionary. This affects > ElementTree, html5lib, Genshi and many more libraries. > > - There are many ordererd dict implementations in various libraries > and applications, most of them subtly incompatible with each other. > Furthermore, subclassing dict is a non-trivial task and many > implementations don't override all the methods properly which can > lead to unexpected results. > > Additionally, many ordered dicts are implemented in an inefficient > way, making many operations more complex then they have to be. > > - PEP 3115 allows metaclasses to change the mapping object used for > the class body. An ordered dict could be used to create ordered > member declarations similar to C structs. This could be useful, for > example, for future ``ctypes`` releases as well as ORMs that define > database tables as classes, like the one the Django framework ships. > Django currently uses an ugly hack to restore the ordering of > members in database models. > > - Code ported from other programming languages such as PHP often > depends on a ordered dict. Having an implementation of an > ordering-preserving dictionary in the standard library could ease > the transition and improve the compatibility of different libraries. > > > Ordered Dict API > ================ > > The ordered dict API would be mostly compatible with dict and existing > ordered dicts. (Note: this PEP refers to the Python 2.x dictionary > API; the transfer to the 3.x API is trivial.) > > The constructor and ``update()`` both accept iterables of tuples as > well as mappings like a dict does. The ordering however is preserved > for the first case: > >>>> d = odict([('a', 'b'), ('c', 'd')]) >>>> d.update({'foo': 'bar'}) >>>> d > collections.odict([('a', 'b'), ('c', 'd'), ('foo', 'bar')]) > > If ordered dicts are updated from regular dicts, the ordering of new > keys is of course undefined again unless ``sort()`` is called. > > All iteration methods as well as ``keys()``, ``values()`` and > ``items()`` return the values ordered by the the time the key-value > pair was inserted: > >>>> d['spam'] = 'eggs' >>>> d.keys() > ['a', 'c', 'foo', 'spam'] >>>> d.values() > ['b', 'd', 'bar', 'eggs'] >>>> d.items() > [('a', 'b'), ('c', 'd'), ('foo', 'bar'), ('spam', 'eggs')] > > New methods not available on dict: > > ``odict.byindex(index)`` > > Index-based lookup is supported by ``byindex()`` which returns > the key/value pair for an index, that is, the "position" of a > key in the ordered dict. 0 is the first key/value pair, -1 > the last. > >>>> d.byindex(2) > ('foo', 'bar') > > ``odict.sort(cmp=None, key=None, reverse=False)`` > > Sorts the odict in place by cmp or key. This works exactly > like ``list.sort()``, but the comparison functions are passed > a key/value tuple, not only the value. > >>>> d = odict([(42, 1), (1, 4), (23, 7)]) >>>> d.sort() >>>> d > collections.odict([(1, 4), (23, 7), (42, 1)]) > > ``odict.reverse()`` > > Reverses the odict in place. > > ``odict.__reverse__()`` > > Supports reverse iteration by key. > > > Questions and Answers > ===================== > > What happens if an existing key is reassigned? > > The key is not moved but assigned a new value in place. This is > consistent with existing implementations and allows subclasses to > change the behavior easily:: > > class movingcollections.odict): > def __setitem__(self, key, value): > self.pop(key, None) > odict.__setitem__(self, key, value) > > What happens if keys appear multiple times in the list passed to the > constructor? > > The same as for regular dicts: The latter item overrides the > former. This has the side-effect that the position of the first > key is used because the key is actually overwritten: > >>>> odict([('a', 1), ('b', 2), ('a', 3)]) > collections.odict([('a', 3), ('b', 2)]) > > This behavior is consistent with existing implementations in > Python, the PHP array and the hashmap in Ruby 1.9. > > Why is there no ``odict.insert()``? > > There are few situations where you really want to insert a key at > an specified index. To avoid API complication, the proposed > solution for this situation is creating a list of items, > manipulating that and converting it back into an odict: > >>>> d = odict([('a', 42), ('b', 23), ('c', 19)]) >>>> l = d.items() >>>> l.insert(1, ('x', 0)) >>>> odict(l) > collections.odict([('a', 42), ('x', 0), ('b', 23), ('c', 19)]) > > > Example Implementation > ====================== > > A poorly performing example implementation of the odict written in > Python is available: > > `odict.py odict.py>`_ > > The version for ``collections`` should be implemented in C and use a > linked list internally. > > Other implementations of ordered dicts in various Python projects or > standalone libraries, that inspired the API proposed here, are: > > - `odict in Babel`_ > - `OrderedDict in Django`_ > - `The odict module`_ > - `ordereddict`_ (a C implementation of the odict module) > - `StableDict`_ > - `Armin Rigo's OrderedDict`_ > > > .. _odict in Babel: http://babel.edgewall.org/browser/trunk/babel/ > util.py?rev=374#L178 > .. _OrderedDict in Django: > http://code.djangoproject.com/browser/django/trunk/django/utils/ > datastructures.py?rev=7140#L53 > .. _The odict module: http://www.voidspace.org.uk/python/odict.html > .. _ordereddict: http://www.xs4all.nl/~anthon/Python/ordereddict/ > .. _StableDict: http://pypi.python.org/pypi/StableDict/0.2 > .. _Armin Rigo's OrderedDict: http://codespeak.net/svn/user/arigo/ > hack/pyfuse/OrderedDict.py > > > Future Directions > ================= > > With the availability of an ordered dict in the standard library, > other libraries may take advantage of that. For example, ElementTree > could return odicts in the future that retain the attribute ordering > of the source file. > > > Copyright > ========= > > This document has been placed in the public domain. > -- > http://mail.python.org/mailman/listinfo/python-list From rdabane at gmail.com Wed Jun 4 02:48:38 2008 From: rdabane at gmail.com (rdabane at gmail.com) Date: Tue, 3 Jun 2008 23:48:38 -0700 (PDT) Subject: Help need with subprocess communicate References: <0312b7e9-bffe-4360-bf3a-f5b3b26d243d@l64g2000hse.googlegroups.com> <530ccda9-818e-4abe-9f82-0720e27c48fd@z72g2000hsb.googlegroups.com> Message-ID: <8aef95d4-065d-4afe-bed6-bb3b4aabe04e@u12g2000prd.googlegroups.com> On Jun 3, 11:23 pm, Dennis Lee Bieber wrote: > On Tue, 3 Jun 2008 18:04:40 -0700 (PDT), rdab... at gmail.com declaimed the > following in comp.lang.python: > > > > > Hi Daniel, > > Thanks for your reply.. > > I've done exactly as you suggested...but I'm still having problem with > > the read...it just gets stuck in > > the read ( I think because its a blocking read...) > > And it is likely blocking because the subprocess is doing buffered > output -- ie, nothing is available to be read because the output has not > been flushed. > > This is a problem with most programs when run as a subprocess -- it > is common for stdout, when routed to a pipe or file, to behave as a > buffered stream that only flushes when some x-bytes have been written; > unlike stdout to a console which gets flushed on each new-line. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ Is there way to configure the stdout buffer size so that it flushes earlier.. Is there a way to make above mentioned piece code working? From timr at probo.com Wed Jun 18 03:11:20 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 18 Jun 2008 07:11:20 GMT Subject: Python GC does not work as it should be References: Message-ID: "Jaimy Azle" wrote: > >Jean-Paul Calderone wrote: > >> A system exception? What's that? C doesn't have exceptions. > >How could I determine it? I dont know GCC implementation, and others, but C >on MSVC does have it. My application were not written in C, an exception >raised was something like "access violation at address xxxx on module >python25.dll", and MSVC debugger shows collecting state were not reset (1), >that is why GC would never happen. Correct. That error is not recoverable. If the garbage collector crashes, the collector is in an indeterminate state, so it is quite reasonable to prevent it from being called again. Here is an excellent rule: Never check for an exception that you are not prepared to handle. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ivan.illarionov at gmail.com Thu Jun 5 10:56:42 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 5 Jun 2008 07:56:42 -0700 (PDT) Subject: Tuples part 2 References: <6d3e6d40-63a6-40d1-8ea4-5ddf40238d8d@m44g2000hsc.googlegroups.com> Message-ID: <99bc30fb-532a-4c4f-9f5e-e7a18c28d2a5@z72g2000hsb.googlegroups.com> On 5 ???, 18:19, "victor.hera... at gmail.com" wrote: > On Jun 5, 3:49 pm, Ivan Illarionov wrote: > > > > > On 5 ???, 01:57, "victor.hera... at gmail.com" > > wrote: > > > > Hi Everyone, > > > > i have another question. What if i wanted to make n tuples, each with > > > a list of coordinates. For example : > > > > coords = list() > > > for h in xrange(1,11,1): > > > for i in xrange(1, 5, 1) : > > > for j in xrange(1, 5, 1) : > > > for k in xrange(1,2,1) : > > > coords.append((i,j,k)) > > > lista+str(h)= tuple coords > > > print tuple(coords) > > > > so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do > > > it the way i show you above but it is not working properly. I wish you > > > could help me with that. Thanks again, > > >>> from itertools import repeat, izip > > >>> coords = tuple((i,j,k) for i in xrange(1,5) for j in xrange(1,5) for k in xrange(1,2)) > > >>> locals().update(("tuple%s" % i, coord) for i, coord in izip(xrange(1,11), repeat(coords))) > > >>> tuple1 > > > ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (2, 1, 1), (2, 2, 1), (2, > > 3, 1), (2 > > , 4, 1), (3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1), (4, 1, 1), (4, 2, > > 1), (4, 3 > > , 1), (4, 4, 1)) > > > Does this help? > > > But I don't understand why you need this? > > > Ivan > > Hi, > > What i need is, for example: > > tuple 1=((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)) > > tuple 2=((2, 1, 1), (2, 2, 1), (2, 3, 1), (2, 4, 1)) > > tuple 3=((3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1)) > > and so on. Please help me and sorry for not taking the time to post my > questions properly. > > Victor Or even so: locals().update(("tuple_%s" % i, tuple((i,j,k) for j in range(1,5) for k in range(1,2))) for i in range(1,5)) Ivan From spoier at gmail.com Mon Jun 9 17:32:08 2008 From: spoier at gmail.com (Skye) Date: Mon, 9 Jun 2008 14:32:08 -0700 (PDT) Subject: Question by someone coming from C... References: <9d40211d-e03f-4f0c-a512-3ac78b0ede21@i18g2000prn.googlegroups.com> Message-ID: <4789a069-1038-4ee2-a2d6-933a9eaf6e2e@s21g2000prm.googlegroups.com> OK, sounds good. So if not bitfields, what would be a good Python-y way to do it? Flip booleans in a "debug config" dictionary or something? Skye From usenet at janc.be Sat Jun 7 18:27:38 2008 From: usenet at janc.be (Jan Claeys) Date: Sat, 07 Jun 2008 22:27:38 GMT Subject: definition of a highlevel language? References: <2759eed3-956d-45c7-8dfb-9557f74133b3@56g2000hsm.googlegroups.com> <26d0b3d2-01cc-49bd-b284-1a849b0b835f@y38g2000hsy.googlegroups.com> <34dcbdc1-5285-41ec-be06-c88c56bb0372@i76g2000hsf.googlegroups.com> <45f03028-a86c-4357-9aa2-0148f7cc84dc@d45g2000hsc.googlegroups.com> Message-ID: Op Mon, 26 May 2008 15:49:33 -0400, schreef Dan Upton: > The point about them looking very little like x86/ARM/etc chips is the > important part though--IIRC, part of the failure of Java machines was > lousy support for preexisting code, due to the optimizations for Java > bytecode, and I expect the same would be true of a Python > bytecode-optimized processor. AFAIK "Java processors" are mostly used as coprocessors next to an ARM core (or similar), allowing you to run Java applications at a reasonable speed on otherwise relatively slow mobile phone CPUs and the like. In theory, it's possible to design a processor that can run some form of Python-oriented bytecode quite effici?ntly, but I fear that nobody really wants to invest the money to do so at the moment? -- JanC From __peter__ at web.de Tue Jun 3 04:22:55 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Jun 2008 10:22:55 +0200 Subject: Merging ordered lists References: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> <8140b81b-bfa1-463b-a92a-19c0f6453444@k30g2000hse.googlegroups.com> Message-ID: etal wrote: > > def unique(items): > > ? ? u = set(items) > > ? ? if len(u) == len(items): > > ? ? ? ? return items > > ? ? result = [] > > ? ? for item in items: > > ? ? ? ? if item in u: > > ? ? ? ? ? ? result.append(item) > > ? ? ? ? ? ? u.remove(item) > > ? ? return result > > You did right by preserving the original (non-alphabetical) ordering, > but I'm less enthusiastic about the shape of this function. My > original function used 7 lines of code, and only 1 for the unique() > step. This uses up to three container objects. Is it really an > improvement? Yes :) Seriously, you are using O(n) containers and O(n) lookup where mine uses O(1). For short lists it doesn't matter, but as the list length grows the difference gets huge: $ cat unique.py def unique(items): u = set(items) if len(u) == len(items): return items result = [] for item in items: if item in u: result.append(item) u.remove(item) return result def unique_lc(ref): return [r for i, r in enumerate(ref) if r and r not in ref[i+1:]] sample_a = range(1000) sample_b = range(1000) import random for i in random.sample(sample_b, 10): sample_b[i] = 0 $ python -m timeit -s"from unique import unique as u, sample_a as s" "u(s)" 10000 loops, best of 3: 52.8 usec per loop $ python -m timeit -s"from unique import unique_lc as u, sample_a as s" "u(s)" 10 loops, best of 3: 44.2 msec per loop 3 orders of magnitude for the shortcut. $ python -m timeit -s"from unique import unique as u, sample_b as s" "u(s)" 1000 loops, best of 3: 646 usec per loop $ python -m timeit -s"from unique import unique_lc as u, sample_b as s" "u(s)" 10 loops, best of 3: 39 msec per loop Still 2 orders of magnitude if my unique() does some actual work. Peter From sturlamolden at yahoo.no Tue Jun 3 22:53:25 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 3 Jun 2008 19:53:25 -0700 (PDT) Subject: How to perform a nonblocking read from a process References: <15c889d4-3e06-4ffd-a86e-10cfa87d3bc5@k37g2000hsf.googlegroups.com> Message-ID: On Jun 4, 3:20 am, rdab... at gmail.com wrote: > It seems that stdout.readline() is a blocking read and it just gets > stuck their.. > How to fix this .. Threads are the simplest remedy for blocking i/o. From michele.simionato at gmail.com Tue Jun 24 05:37:48 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 24 Jun 2008 02:37:48 -0700 (PDT) Subject: Python 3000 vs Perl 6 References: <89fbe834-68b7-49e6-8136-62dee53c2f40@t54g2000hsg.googlegroups.com> Message-ID: <7bad9ebd-81ab-48c4-854b-05f085e9d936@27g2000hsf.googlegroups.com> On Jun 24, 11:16?am, cokofree... at gmail.com wrote: > Towards it being more advanced than Python 3k, time will tell. It is worth reminding that, in more than one sense, the most advanced language is the one with less features ... Michele Simionato From pfreixes at gmail.com Sun Jun 15 10:22:22 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Sun, 15 Jun 2008 16:22:22 +0200 Subject: please critique my thread code In-Reply-To: <222a1935-20dd-44a0-bc42-71a25be96d30@79g2000hsk.googlegroups.com> References: <222a1935-20dd-44a0-bc42-71a25be96d30@79g2000hsk.googlegroups.com> Message-ID: <207312b70806150722o4f678v6ab404d79dba2f34@mail.gmail.com> Hi, The main while in main thread spend all cpu time, it's more convenient put one little sleep between each iteration or use a some synchronization method between threads. And about your questions IMO: > --- Are my setup and use of threads, the queue, and "while True" loop > correct or conventional? May be, exist another possibility but this it's good, another question is if iterate arround the 240000 numbers it's the more efficient form for retrieve all projects. --- Should the program sleep sometimes, to be nice to the SourceForge > servers, and so they don't think this is a denial-of-service attack? You are limiting your number of connections whit you concurrent threads, i don't believe that SourceForge have a less capacity for request you concurrent threads. > > --- Someone told me that popen is not thread-safe, and to use > mechanize. I installed it and followed an example on the web site. > There wasn't a good description of it on the web site, or I didn't > find it. Could someone explain what mechanize does? I don't know , but if you don't sure you can use urllib2. > > --- How do I choose the number of threads? I am using a MacBook Pro > 2.4GHz Intel Core 2 Duo with 4 GB 667 MHz DDR2 SDRAM, running OS > 10.5.3. For default phtreads in linux flavor spend 8MB for thread stack, i dont know in you MacBook. i think between 64 to 128 threads it's correct. > > > Thank you. > > Winston > > > > #!/usr/bin/env python > > # Winston C. Yang > # Created 2008-06-14 > > from __future__ import with_statement > > import mechanize > import os > import Queue > import re > import sys > import threading > import time > > lock = threading.RLock() > > # Make the dot match even a newline. > error_pattern = re.compile(".*\n\n.*", re.DOTALL) > > def now(): > return time.strftime("%Y-%m-%d %H:%M:%S") > > def worker(): > > while True: > > try: > id = queue.get() > except Queue.Empty: > continue > > request = mechanize.Request("http://sourceforge.net/project/"\ > "memberlist.php?group_id=%d" % > id) > response = mechanize.urlopen(request) > text = response.read() > > valid_id = not error_pattern.match(text) > > if valid_id: > f = open("%d.csv" % id, "w+") > f.write(text) > f.close() > > with lock: > print "\t".join((str(id), now(), "+" if valid_id else > "-")) > > def fatal_error(): > print "usage: python application start_id end_id" > print > print "Get the usernames associated with each SourceForge project > with" > print "ID between start_id and end_id, inclusive." > print > print "start_id and end_id must be positive integers and satisfy" > print "start_id <= end_id." > sys.exit(1) > > if __name__ == "__main__": > > if len(sys.argv) == 3: > > try: > start_id = int(sys.argv[1]) > > if start_id <= 0: > raise Exception > > end_id = int(sys.argv[2]) > > if end_id < start_id: > raise Exception > except: > fatal_error() > else: > fatal_error() > > # Print the start time. > start_time = now() > print start_time > > # Create a directory whose name contains the start time. > dir = start_time.replace(" ", "_").replace(":", "_") > os.mkdir(dir) > os.chdir(dir) > > queue = Queue.Queue(0) > > for i in xrange(32): > t = threading.Thread(target=worker, name="worker %d" % (i + > 1)) > t.setDaemon(True) > t.start() > > for id in xrange(start_id, end_id + 1): > queue.put(id) > > # When the queue has size zero, exit in three seconds. > while True: > if queue.qsize() == 0: > time.sleep(3) > break > > print now() > -- > http://mail.python.org/mailman/listinfo/python-list > -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Mon Jun 23 11:14:08 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 23 Jun 2008 08:14:08 -0700 (PDT) Subject: Regular expression problem References: <181fe17d-61f0-40f4-89b4-99fe4c483bf7@k30g2000hse.googlegroups.com> Message-ID: On Jun 22, 10:13?pm, abranches wrote: > Hello everyone. > > I'm having a problem when extracting data from HTML with regular > expressions. > This is the source code: > > You are ready in the next
    style="display: inline;">12 span>M 48S > > And I need to get the remaining time. Until here, isn't a problem > getting it, but if the remaining time is less than 60 seconds then the > source becomes something like this: > > You are ready in the next
    style="display: inline;">36 span>S > > I'm using this regular expression, but the minutes are always None... > You are ready in the next.*?(?:>(\d+)M
    )?.*?(?:>(\d+) span>S) > > If I remove the ? from the first group, then it will work, but if > there are only seconds it won't work. > I could resolve this problem in a couple of python lines, but I really > would like to solve it with regular expressions. > Your regex is working like this: 1. Match 'You are ready in the next'. 2. Match an increasing number of characters, starting with none ('.*?'). 3. Try to match a pattern ('(?:>...)?') from where the previous step left off. This doesn't match, but it's optional anyway, so continue to the next step. (No characters consumed.) 4. Match an increasing number of characters, starting from none ('.*?'). It's this step that consumes the minutes. It then goes on to match the seconds, and the minutes are always None as you've found. I've come up with this regex: You are ready in the next(?:.*?>(\d+)M)?(?:.*?>(\d+)S) Hope that helps. From roy at panix.com Sun Jun 15 21:29:12 2008 From: roy at panix.com (Roy Smith) Date: Sun, 15 Jun 2008 21:29:12 -0400 Subject: newbie question: for loop within for loop confusion References: Message-ID: In article , takayuki wrote: > Hi, > > I'm studying python via the exellent book "How to think like a python > programmer" by Allen Downey. > > Noob question follows... > > animals.txt is a list of animals, each on a separate line: "aardvard, > bat, cat, dog, elephant, fish, giraffe, horse, insect, jackelope" > > I want to loop through the list of words and print words that don't > have any "avoid" letter in them. > > def hasnolet(avoid): > fin = open('animals.txt') > for line in fin: > word = line.strip() > for letter in avoid: > if letter in word: > break > else: > print word > > hasnolet('abcd') > I could give you a fish, or I could teach you to fish. I'd rather do the latter. So... Take your inner loop: > for letter in avoid: > if letter in word: > break > else: > print word and instrument it so you can see exactly what's happening. Try something like: > for letter in avoid: > print "letter = %s" % letter > if letter in word: > print "it's in word" > break > else: > print "no it's not" > print word and see if that helps. From ptmcg at austin.rr.com Mon Jun 16 09:46:59 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 16 Jun 2008 06:46:59 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> Message-ID: <8ec4632c-2cae-40d1-ba5d-8d88854dae52@m73g2000hsh.googlegroups.com> 1. With the current dict, the following code a = { "A" : 1, "B" : 2 } b = { "B" : 2, "A" : 1 } a==b evaluates to True. I assume that if these were odicts, this would evaluate to False. 2. Will odict.byindex support slicing? 3. Will odict inherit from dict? 4. The current dict API (as of Python 2.5) is given by dir as: ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] If I read your PEP correctly, you propose adding: byindex sort reverse __reverse__ (should be '__reversed__', to match list's reverse iterator) (This isn't really a question, your PEP was not completely explicit about what odict's API would be, so I thought enumerating what dict does currently might illuminate some other unresolved aspects of odict. For instance, since odict is somewhat list-like in its notion of keys and values, will pop support list-like popping as well as what dict currently provides? Will you need a 'popbyindex' for the same reason you need 'byindex', so that you have unambiguous lookup of items by index vs. by key. Perhaps doing dir(list) will help you to see other items to resolve/clarify.) 5. The more I think and write about this, the more struck I am at the similarity of odict and the ParseResults class in pyparsing. For instance, in ParseResults, there is also support for dict-style and list-style item referencing, and I chose to restrict some cases so that using [] notation would not be ambiguous. You might want to add pyparsing.ParseResults as another reference of current "odicts in the wild" (although ParseResults implements quite a bit of additional behavior that would not be required or necessarily appropriate for odict). I vote +0 on this PEP - I've never personally needed an odict, but I can see how some of the XML and ORM coding would be simplified by one. -- Paul (I could go either way on the name 'odict' or 'ordereddict'. Given the desire for this to evenutally become a built-in, keep the name short. On the other hand, collections already has 'defaultdict', so is 'ordereddict' so bad?) From sturlamolden at yahoo.no Wed Jun 4 18:16:19 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 4 Jun 2008 15:16:19 -0700 (PDT) Subject: multiprocessing module (PEP 371) References: <877a5774-d3cc-49d3-bb64-5cab8505a419@m3g2000hsc.googlegroups.com> <2953a72d-cdc7-4360-ac25-36618fe9229f@s50g2000hsb.googlegroups.com> Message-ID: On Jun 4, 11:29 pm, Paul Boddie wrote: > tested the executable on Windows. COW (copy-on-write, for those still > thinking that we're talking about dairy products) would be pretty > desirable if it's feasible, though. There is a well known C++ implementation of cow-fork on Windows, which I have slightly modified and ported to C. But as the new WDK (Windows driver kit) headers are full of syntax errors, the compiler choke on it. :( I am seriously considering re-implementing the whole cow fork in pure Python using ctypes. If you pass NULL as section handle to ZwCreateProcess (or NtCreateProcess) you do get a rudimentary cow fork. But the new process image has no context and no active threads. The NT kernel is designed to support several subsystems. Both the OS/2 and SUA subsystems provide a functional COW fork, but the Win32 subsystem do not expose the functionality. I honestly don't understand why, but maybe it is backwards compatibility that prevents it (it's backlog goes back to DOS, in which forking was impossible due to single- tasking.) But anyway ... what I am trying to say is that pyprocessing is somewhat inefficient (and limited) on Windows due to lack of a fork (cow or not). From eckhardt at satorlaser.com Thu Jun 19 08:21:46 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 19 Jun 2008 14:21:46 +0200 Subject: Simple Python class questions References: Message-ID: John Dann wrote: > Let's say I define the class in a module called comms.py. The class > isn't really going to inherit from any other class (except presumably > in the most primitive base-class sense, which is presumably automatic > and implicit in using the class keyword). Let's call the class > serial_link. So in comms.py I have: > > class serial_link: > def __init__(self): > Try > Import serial # the pyserial library Stop, this can't work. Other than VB, Python actually is case sensitive, so you must write 'try' and not 'Try' and also 'import' and not 'Import'. Further, many (all?) statements that cause an indention are usually terminated with a colon, so like with 'class ..:' and 'def ..:' you also must use 'try:' and not just 'try'. Fix all these and try again, I guess this will already help a lot. One more thing: you are abusing exceptions. Typically, in such a short program you only have one try-except pair in the main entry function and all other code only throws the exceptions. In particular the __init__ function of a class should always signal errors using exceptions. However, this is not a strict yes/no question but rather a stylistic one. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From allendowney at gmail.com Mon Jun 9 13:03:18 2008 From: allendowney at gmail.com (allendowney at gmail.com) Date: Mon, 9 Jun 2008 10:03:18 -0700 (PDT) Subject: Can I find out (dynamically) where a method is defined? References: Message-ID: Thanks Maric! That's very close to what I want, although using dir() can be misleading because if you invoke it on class B you get all of class A's methods as well. I took your idea and wrote it up like this: def find_defining_class(obj, meth_name): """find and return the class object that will provide the definition of meth_name (as a string) if it is invoked on obj. """ for ty in type(obj).mro(): if meth_name in ty.__dict__: return ty return None Cheers, Allen On Jun 9, 12:01?pm, Maric Michaud wrote: > Le Monday 09 June 2008 17:28:45 allendow... at gmail.com, vous avez ?crit?: > > > So, is there any way to inspect a method to see where (in what class) > > it > > is defined? > > In [56]: class a(object) : > ? ? def a() : return > ? ? def b() : ?return > ? ?....: > ? ?....: > > In [59]: class b(a) : > ? ? def b() : return > ? ? def c() : return > ? ?....: > ? ?....: > > In [62]: i=b() > > In [63]: for m in 'a', 'b', 'c' : > ? ?....: ? ? print [ t for t in type(i).mro() if m in dir(t) ] > ? ?....: > ? ?....: > [] > [, ] > [] > > mro stands for "method resolution order", check the reference on this > and "super", it worths the effort. > From stef.mientki at gmail.com Sun Jun 1 13:32:05 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 01 Jun 2008 19:32:05 +0200 Subject: [Business apps for Windows] Good grid + calendar, etc.? In-Reply-To: <0fc701c8c3e2$dc883b80$0203a8c0@MOUSE> References: <0fc701c8c3e2$dc883b80$0203a8c0@MOUSE> Message-ID: <4842DD15.3020604@gmail.com> Ryan Ginstrom wrote: >> On Behalf Of Gilles Ganault >> Is it hopeless, or did I overlook things? Are there other >> solutions I should look at (FLTK, etc.)? For those of you >> writing business apps in Python for Windows, how do things go >> as far as GUI widgets are concerned? >> > > To do a bit of shameless plugging, I wrote an overview of Python GUI > platforms for Windows a month or two ago: > http://ginstrom.com/scribbles/2008/02/26/python-gui-programming-platforms-fo > r-windows/ > > For your stated needs, I'd advise checking out IronPython or Python.NET > (which allow use of .NET GUI libraries). > AFAIK, Venster is (at least for windows-mobile-like platforms) replaced by the very good and stable PocketPyGUI. cheers, Stef > Regards, > Ryan Ginstrom > > -- > http://mail.python.org/mailman/listinfo/python-list > From taygunkekec at gmail.com Fri Jun 27 08:40:57 2008 From: taygunkekec at gmail.com (Taygun Kekec) Date: Fri, 27 Jun 2008 05:40:57 -0700 (PDT) Subject: Windows OS , Bizarre File Pointer Fact References: <864ab9f2-7d99-49f0-9d41-93ec41e26203@y38g2000hsy.googlegroups.com> Message-ID: Allright i figured it out . Very stupid but very forgottable fact. I should close the file before deleting it with shell command... From rentlong at gmail.com Sat Jun 14 03:18:52 2008 From: rentlong at gmail.com (rent) Date: Sat, 14 Jun 2008 00:18:52 -0700 (PDT) Subject: How to sort very large arrays? References: Message-ID: On Jun 14, 1:54 am, kj wrote: > I'm downloading some very large tables from a remote site. I want > to sort these tables in a particular way before saving them to > disk. In the past I found that the most efficient way to do this > was to piggy-back on Unix's highly optimized sort command. So, > from within a Perl script, I'd create a pipe handle through sort > and then just print the data through that handle: This is a python clone of your code from a python rookie :) from os import popen p = popen("sort -t '\t' -k1,1 -k2,2 -u > %s" % out_file) for line in data: print >> p, line there is no "die $!" here, I think it is good to let python throw the exception to your console > > open my $out, "|$sort -t '\t' -k1,1 -k2,2 -u > $out_file" or die $!; > print $out $_ for @data; > > But that's distinctly Perlish, and I'm wondering what's the "Python > Way" to do this. > > TIA! > > kynn > > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. From eckhardt at satorlaser.com Wed Jun 4 06:12:44 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 04 Jun 2008 12:12:44 +0200 Subject: Best way to modify code without breaking stuff. References: <2531546.63WkQjL8G4@news.perlig.de> Message-ID: Andr? Malo wrote: > As mentioned in another posting revision control is a good thing as well. > Not just for that task. >From my point of view revision control is not a question but a fact. Seriously, if you are not using any RCS already, it is about time you start doing so. I even use it for my private toy projects. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From jeffrey at fro.man Mon Jun 23 16:23:12 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Mon, 23 Jun 2008 13:23:12 -0700 Subject: Using Python to run SSH commands on a remote server References: <03a078c8$0$3229$c3e8da3@news.astraweb.com> <86adnQ8H4MFYdcLVnZ2dnUVZ_sHinZ2d@cablespeedwa.com> <03a08853$0$3220$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > I guess a blanket process might be a tad risky, but don't you want all CGI > files to be executable by all? Typically, I prefer CGI scripts to be executable only the owner. If the web server runs those scripts as a different user, then that user must also be permitted to execute the scripts of course. Also note that "all .py files on my web server" is not necessarily restricted to CGI scripts -- and therein lies the real gist of my cautionary note. Jeffrey From jeff at jmcneil.net Fri Jun 13 12:11:11 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Fri, 13 Jun 2008 12:11:11 -0400 Subject: urllib (54, 'Connection reset by peer') error In-Reply-To: <92ecee86-ba92-4f14-b4f8-05064ef5406c@f63g2000hsf.googlegroups.com> References: <92ecee86-ba92-4f14-b4f8-05064ef5406c@f63g2000hsf.googlegroups.com> Message-ID: <82d28c40806130911p91f959v1a5107cb5061aaaf@mail.gmail.com> It means your client received a TCP segment with the reset bit sent. The 'peer' will toss one your way if it determines that a connection is no longer valid or if it receives a bad sequence number. If I had to hazard a guess, I'd say it's probably a network device on the server side trying to stop you from running a mass download (especially if it's easily repeatable and happens at about the same byte range). -Jeff On Fri, Jun 13, 2008 at 10:21 AM, wrote: > Hi, > > I have a small Python script to fetch some pages from the internet. > There are a lot of pages and I am looping through them and then > downloading the page using urlretrieve() in the urllib module. > > The problem is that after 110 pages or so the script sort of hangs and > then I get the following traceback: > >>>>> > Traceback (most recent call last): > File "volume_archiver.py", line 21, in > urllib.urlretrieve(remotefile,localfile) > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/urllib.py", line 89, in urlretrieve > return _urlopener.retrieve(url, filename, reporthook, data) > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/urllib.py", line 222, in retrieve > fp = self.open(url, data) > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/urllib.py", line 190, in open > return getattr(self, name)(url) > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/urllib.py", line 328, in open_http > errcode, errmsg, headers = h.getreply() > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/httplib.py", line 1195, in getreply > response = self._conn.getresponse() > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/httplib.py", line 924, in getresponse > response.begin() > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/httplib.py", line 385, in begin > version, status, reason = self._read_status() > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/httplib.py", line 343, in _read_status > line = self.fp.readline() > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/socket.py", line 331, in readline > data = recv(1) > IOError: [Errno socket error] (54, 'Connection reset by peer') >>>>>>> > > My script code is as follows: > ----------------------------------------- > import os > import urllib > > volume_number = 149 # The volumes number 150 to 544 > > while volume_number < 544: > volume_number = volume_number + 1 > localfile = '/Users/Chris/Desktop/Decisions/' + str(volume_number) + > '.html' > remotefile = 'http://caselaw.lp.findlaw.com/scripts/getcase.pl? > court=us&navby=vol&vol=' + str(volume_number) > print 'Getting volume number:', volume_number > urllib.urlretrieve(remotefile,localfile) > > print 'Download complete.' > ----------------------------------------- > > Once I get the error once running the script again doesn't do much > good. It usually gets two or three pages and then hangs again. > > What is causing this? > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From aahz at pythoncraft.com Wed Jun 11 16:39:25 2008 From: aahz at pythoncraft.com (Aahz) Date: 11 Jun 2008 13:39:25 -0700 Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: In article , Frank Millman wrote: > >My approach is based on expressing a decimal number as a combination >of an integer and a scale, where scale means the number of digits to >the right of the decimal point. You should probably use one written by an expert: http://www.pythoncraft.com/FixedPoint.py -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From gh at ghaering.de Tue Jun 17 07:49:55 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 17 Jun 2008 13:49:55 +0200 Subject: Numeric type conversions In-Reply-To: References: Message-ID: John Dann wrote: > I'm new to Python and can't readily find the appropriate function for > the following situation: > > I'm reading in a byte stream from a serial port (which I've got > working OK with pyserial) and which contains numeric data in a packed > binary format. Much of the data content occurs as integers encoded as > 2 consecutive bytes, ie a 2-byte integer. [...] Use the unpack() function from the struct module. -- Gerhard From mccredie at gmail.com Fri Jun 20 14:10:44 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 20 Jun 2008 11:10:44 -0700 (PDT) Subject: Tkinter canvas drag/drop obstacle References: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> Message-ID: <09ec833f-7751-4991-8d09-45c200fb4c18@z72g2000hsb.googlegroups.com> On Jun 20, 9:11?am, Peter Pearson wrote: > Tkinter makes it very easy to drag jpeg images around on a > canvas, but I would like to have a "target" change color when > the cursor dragging an image passes over it. ?I seem to be > blocked by the fact that the callbacks that might tell the > target that the mouse has entered it (, , > even ) aren't called if the mouse's button is down. > What am I missing? ?Have I failed to find the right Tkinter > document? ?Is Tkinter the wrong tool for this job? ?Thanks. > > -- > To email me, substitute nowhere->spamcop, invalid->net. I have used a combination of and . You might also throw in a event to keep track of whether or not the mouse button was down when it entered the widget or not. Depending on what you really want to do though, you might take advantage of the 'active' state: import Tkinter as tk can = tk.Canvas() can.pack(fill=tk.BOTH, expand=True) can.create_rectangle( 10,10,100,100, fill="black", activewidth=5, activeoutline="blue" ) can.mainloop() The 'active*' options take effect when the mouse is on top of that item. If all you are _really_ interested in is a visual indicator, this should work for you. Note that there is also a disabled state. I only discovered this by looking at the options available and guessing. >>> from pprint import pprint >>> import Tkinter as tk >>> can = tk.Canvas() >>> can.pack(fill=tk.BOTH, expand=True) >>> r = can.create_rectangle(10,10,100,100) >>> pprint(can.itemconfig(r)) {'activedash': ('activedash', '', '', '', ''), 'activefill': ('activefill', '', '', '', ''), 'activeoutline': ('activeoutline', '', '', '', ''), 'activeoutlinestipple': ('activeoutlinestipple', '', '', '', ''), 'activestipple': ('activestipple', '', '', '', ''), 'activewidth': ('activewidth', '', '', '0.0', '0.0'), 'dash': ('dash', '', '', '', ''), 'dashoffset': ('dashoffset', '', '', '0', '0'), 'disableddash': ('disableddash', '', '', '', ''), 'disabledfill': ('disabledfill', '', '', '', ''), 'disabledoutline': ('disabledoutline', '', '', '', ''), 'disabledoutlinestipple': ('disabledoutlinestipple', '', '', '', ''), 'disabledstipple': ('disabledstipple', '', '', '', ''), 'disabledwidth': ('disabledwidth', '', '', '0.0', '0'), 'fill': ('fill', '', '', '', ''), 'offset': ('offset', '', '', '0,0', '0,0'), 'outline': ('outline', '', '', 'black', 'black'), 'outlineoffset': ('outlineoffset', '', '', '0,0', '0,0'), 'outlinestipple': ('outlinestipple', '', '', '', ''), 'state': ('state', '', '', '', ''), 'stipple': ('stipple', '', '', '', ''), 'tags': ('tags', '', '', '', ''), 'width': ('width', '', '', '1.0', '1.0')} The 'state' option can be set to 'normal', 'hidden' or 'disabled'. So if you want to make your canvas items look different when they are disabled, set the disabled* options and set 'state' to 'disabled'. Matt From n.emami at gmail.com Mon Jun 9 09:27:44 2008 From: n.emami at gmail.com (Nader) Date: Mon, 9 Jun 2008 06:27:44 -0700 (PDT) Subject: lists to save in a tuple Message-ID: <130e261e-1e1a-4657-b8db-8a7704fb083d@z66g2000hsc.googlegroups.com> Hello, I have two lists and would save them in a tuple. a = [1,2,3] b = ['a','b','c'] with the next statement I can do that: t = [(x,y), for x in a for y in b] This gives the next list: [(1,'a'),(1,'b'),(1,'c'), (2,'a'),(2,'b'),(2,'c'), (3,'a'),(3,'b'), (3,'c')] But I want the next list: [(1,'a'),(2,'b'),(3,'c')] Would somebody tell me how I can solve this problem? Regards, Nader From jason.scheirer at gmail.com Fri Jun 27 15:51:05 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Fri, 27 Jun 2008 12:51:05 -0700 (PDT) Subject: Django or TurboGears for a new project References: <8763ru6cra.fsf@internal.daycos.com> Message-ID: On Jun 27, 9:52?am, Kirk Strauser wrote: > We're looking to migrate a Zope site to Django, but before getting beyond > the dreaming stage, I thought I'd see what others are doing these days. > > If you were going to start a fairly complex site today with lots of DB > integration, would you begin with Django or TurboGears, or something else > entirely? > > I'm more interested in social, rather than technical reasons (unless there's > something you absolutely love or despise about one or the other). > Popularity is actually a pretty big consideration because I'd like to work > with an eager community who's doing cool new things. > > I know asking for comparisons like this is potentially flamebait-ish, but I > really don't mean it that way. ?It's just that I don't have a lot of friends > in the industry in this particular development niche who I can ask for > recommendations, and this seems like as good a place as any to find subject > matter experts. > > Thanks, > -- > Kirk Strauser > The Day Companies I've noticed I write a lot less code with TurboGears (as in my apps are done faster and smaller), but you're going to find more Django programmers and therefore a larger developer force and more recipes online. From disappearedng at gmail.com Tue Jun 10 12:09:24 2008 From: disappearedng at gmail.com (disappearedng at gmail.com) Date: Tue, 10 Jun 2008 09:09:24 -0700 (PDT) Subject: Web Crawler - Python or Perl? References: <484D7329.6060107@behnel.de> <1a91e16d-ccfc-487a-80fc-4d9992455eb9@p25g2000hsf.googlegroups.com> <484d9bdc$0$6606$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <91cbb629-b085-45bd-aeec-5b3dba8f34c7@r66g2000hsg.googlegroups.com> As to why as opposed to what, I am attempting to build a search engine right now that plans to crawl not just html but other things too. I am open to learning, and I don't want to learn anything that doesn't really contribute to building my search engine for the moment. Hence I want to see whether learning PERL will be helpful to the later parts of my search engine. Victor From google at mrabarnett.plus.com Tue Jun 17 11:58:11 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 17 Jun 2008 08:58:11 -0700 (PDT) Subject: Numeric type conversions References: Message-ID: On Jun 17, 12:28 pm, John Dann wrote: > I'm new to Python and can't readily find the appropriate function for > the following situation: > > I'm reading in a byte stream from a serial port (which I've got > working OK with pyserial) and which contains numeric data in a packed > binary format. Much of the data content occurs as integers encoded as > 2 consecutive bytes, ie a 2-byte integer. > > I'm guess that there should be a function available whereby I can say > something like: > > My2ByteInt = ConvertToInt(ByteStream[12:13]) > > to take a random example of the 2 bytes occurring at positions 12 and > 13 in the byte stream. > [snip] Please note that in slicing the start position is included and the end position is excluded, so that should be ByteStream[12:14]. From maric at aristote.info Mon Jun 23 08:40:57 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 23 Jun 2008 14:40:57 +0200 Subject: listcomprehension, add elements? In-Reply-To: References: <13452c64-ef91-49a2-bb73-7f33c088660e@d45g2000hsc.googlegroups.com> Message-ID: <200806231440.57737.maric@aristote.info> Le Monday 23 June 2008 13:51:34 John Machin, vous avez ?crit?: > On Jun 23, 9:16 pm, Maric Michaud wrote: > > Le Monday 23 June 2008 11:39:44 Boris Borcic, vous avez ?crit : > > > John Machin wrote: > > > > Instead of sum(a + b for a, b in zip(foo, bar)) > > > > why not use sum(foo) + sum(bar) > > > > ? > > > > > > or even sum(foo+bar) as may apply. > > > > Because some are better than others : > > > > sum(foo+bar) is the worst, it create a superfluous list of len(foo) + > > len(bar) elements. > > > > sum(a + b for a, b in zip(foo, bar)), creates a list of max(len(foo), > > len(bar)) elements, in most cases it is the same as the former. > > > > This could have been corrected using itertools.izip. > > > > So the winner is sum(foo) + sum(bar), which does not create anything not > > needed. > > > > But if the question is "how to build the list and sum up all elements in > > a efficient way for sequences of arbitrary length ", it's important to > > make it in the same iteration, so the most effective/clear, and so > > "pythonic", way to do this is (untested) : > > > > res, sum = [], 0 > > Please use tot or total, not sum! > > > for s in (a + b for a, b > > in zip(itertools.izip(xrange(1, 51), > > Perhaps you should not have left zip() in there ... > > > xrange(50, 0, > > -1)))): sum += s > > res.append(sum) > > Do you mean res.append(s) ? > Yes, my mistakes, all remarks are indeed true. Sorry for this out of thoughts sketch. > I would have thought that it would have been better to create the list > and then sum it: > res = [a + b for a, b in itertools.izip(foo_iter, bar_iter)] > total = sum(res) > This is good enough if you accept the overhead of iterating twice over the whole list. But this may be a bit more complicated, for efficiency, there is a better way of allocating memory than successively appending new item. I guess this should be a far better solution, but you'll need to know the required number of iteration (the size of your iterators, the xrange in this sample) : res, total = [None] * n, 0 for i, s in enumerate(a + b for a, b in izip(xrange(1, n+1), xrange(n, 0, -1)): total += s res[i] =s -- _____________ Maric Michaud From tgrav at mac.com Wed Jun 4 18:58:34 2008 From: tgrav at mac.com (Tommy Grav) Date: Wed, 4 Jun 2008 18:58:34 -0400 Subject: gcc error in Mac OS X In-Reply-To: <12956470806041550k7e2815b4ga6823ee7967a8718@mail.gmail.com> References: <12956470806041550k7e2815b4ga6823ee7967a8718@mail.gmail.com> Message-ID: What happens when you run which gcc Cheers Tommy On Jun 4, 2008, at 6:50 PM, Zhaojie Boulder wrote: > Hello, > > I am new to Mac and used python in linux before. What I am trying to > do is to install "Ipython" and "PyCogent" in Mac OS X. > > For PyCogent, after entering the package path, I typed "python > setup.py install". The results are as follows: > > Didn't find Pyrex - will compile from .c files > running install > running build > running build_py > running build_ext > building 'cogent.align._compare' extension > gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused- > madd -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes - > DMACOSX -I/usr/include/ffi -DENABLE_DTRACE -arch i386 -arch ppc - > pipe -I/Users/zhaojie/Downloads/PyCogent-1.0.1/include -I/System/ > Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 - > c cogent/align/_compare.c -o build/temp.macosx-10.5-i386-2.5/cogent/ > align/_compare.o -w > unable to execute gcc: No such file or directory > error: command 'gcc' failed with exit status 1 > > After google, I installed Xcode,but it did not help. Also, the Xcode > folder is not within "applications" folder, but a separate one > parallel with "applications". Dragging Xcode folder into the > applications folder did not make a difference, either. > > Hope someone familiar with Mac can help me out. > > Thank you, > > Jie > -- > http://mail.python.org/mailman/listinfo/python-list From gh at ghaering.de Tue Jun 3 11:07:02 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 03 Jun 2008 17:07:02 +0200 Subject: Please solve me the problem In-Reply-To: <905b76210806022159l1bcb0165r1096c491f665e914@mail.gmail.com> References: <905b76210806022159l1bcb0165r1096c491f665e914@mail.gmail.com> Message-ID: sagar panda wrote: > Hi > > I am sagar. I want to write a python script that will run the python > scripts automatically from a directory. Please help me out to sovle this > problem? You can use the execfile() builtin function to execute Python scripts. And you can use glob.glob("/some/path/*.py") to find the Python scripts. You'll need to import the glob module first, of course. That should help you implement the solution. -- Gerhard From joemacbusiness at yahoo.com Thu Jun 26 18:31:57 2008 From: joemacbusiness at yahoo.com (joemacbusiness at yahoo.com) Date: Thu, 26 Jun 2008 15:31:57 -0700 (PDT) Subject: Need help capturing output of re.search Message-ID: <771ef68a-d976-4f61-a3cc-7ed56fddc756@k37g2000hsf.googlegroups.com> Hi - I need help capturing the output of a RegEx search. I dont understand why this conditional fails. Here is the code: #================================= start snip ====================================== #!/usr/local/bin/python import os import re dirName = '/home/user/bin/logs' os.chdir(dirName) files = os.listdir(dirName) for myFile in files: # print 'checking ...', myFile reCheck = '' reCheck = re.search(r'\bCC_', myFile) # print 'reCheck = ', '=', reCheck, '=' if reCheck == "None": print myFile, ' ..... does not qualify' else: print ' ', myFile, 'qualifies...', reCheck #================================= end snip ====================================== The problem is that reCheck never == None. So all of the files "qualify". My understanding of the re.search (re.search(r'\bCC_', myFile)) is ... 1) give me only files that start with a word boundary (\b) 2) followed by a (CC_) 3) in myFile Why doesn't the output of the re.search load reCheck with valid data? (like "None") Thanks From python at rcn.com Wed Jun 4 07:36:51 2008 From: python at rcn.com (Raymond Hettinger) Date: Wed, 4 Jun 2008 04:36:51 -0700 (PDT) Subject: defaultdict.fromkeys returns a surprising defaultdict References: Message-ID: <81be85b4-978e-423d-8a1a-11f54e11cf18@x1g2000prh.googlegroups.com> On Jun 3, 1:11?pm, Matthew Wilson wrote: > I used defaultdict.fromkeys to make a new defaultdict instance, but I > was surprised by behavior: > ? ? >>> b = defaultdict.fromkeys(['x', 'y'], list) > ? ? >>> b > ? ? defaultdict(None, {'y': , 'x': }) One other thought: Even after correcting the code as shown in other posts, I don't think you're on the right track. If you know the full population of keys at the outset and just want them to all have an initial value, the defaultdict isn't the right tool. Instead, just populate a regular dict in usual way: >>> dict((k, []) for k in 'xyz') {'y': [], 'x': [], 'z': []} The time to use defaultdict is when you *don't* want to pre-populate a dict. The factory gets run during the lookup phase and creates your default just-in-time for use: >>> d = defaultdict(list) >>> for k in 'zyzygy': d[k].append(1) # empty list created on lookup if needed >>> d defaultdict(, {'y': [1, 1, 1], 'z': [1, 1], 'g': [1]}) Raymond From xdicry at gmail.com Mon Jun 23 04:50:30 2008 From: xdicry at gmail.com (Evan) Date: Mon, 23 Jun 2008 01:50:30 -0700 (PDT) Subject: how to send a "Multiline" mail with smtplib? References: <72daf82c-1921-4aba-b41a-3bf13d3f0e51@s21g2000prm.googlegroups.com> Message-ID: <243cbf35-d9a3-4d98-a4fa-2b991b38e71b@s21g2000prm.googlegroups.com> On Jun 19, 6:12 pm, Lie wrote: > On Jun 19, 4:02 pm, Justin Ezequiel > wrote: > > > perhaps change html > > > body=MIMEText('hello,\r\n > > ok',_subtype='html',_charset='windows-1255') > > > to plain > > > body=MIMEText('hello,\r\n > > ok',_subtype='plain',_charset='windows-1255') > > If that was the case, and you needed a line break in html-mode, use >
    or

    tags. Thanks all, and yes, if I use "plain" or use HTML tag "
    ", it worked: (1) HTML: I use tag "
    " and " ", and when I reply that mail, I will see "
    " tag in mail content, it is not a good option. thanks, Evan From brad.navarro at wni.com Wed Jun 11 14:33:10 2008 From: brad.navarro at wni.com (Brad Navarro) Date: Wed, 11 Jun 2008 13:33:10 -0500 Subject: Programming question Message-ID: <31C3FE622274D44A8FE8E8D649AE178805E738D4@exch1.wni.com> Greetings, Being extremely new to Python, I haven't got the experience to figure this one out on my own and frankly I am not sure I would know where to look. Basically, what I am trying to do is get a list of each file's attributes within a directory. Basically, the information that the 'ls -l' command would give you in a linux shell, except the results for each file in the directory are stored as a list. I am presently using version 1.5 on a linux machine. I have kindly requested my system administrator to upgrade to 2.5.2, but until then I am afraid I am stuck with 1.5. Thanks, Brad -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Jun 13 12:52:41 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Jun 2008 18:52:41 +0200 Subject: Finding a sense of word in a text References: <2b696ed5-bb4c-4c02-8d35-ac6235d8584b@y21g2000hsf.googlegroups.com> <2a6c26f6-5aea-4bf1-9cf8-866bf1d1f86d@w1g2000prd.googlegroups.com> Message-ID: Sengly wrote: > Thank you. I have tried but no luck :( NLTK, maybe? Searching for "synonym" within nltk.org gives http://nltk.org/doc/en/words.html Peter From mnordhoff at mattnordhoff.com Wed Jun 18 05:18:46 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 18 Jun 2008 09:18:46 +0000 Subject: reading from an a gzip file In-Reply-To: <4e9ff9ad-6fe5-413c-b81f-c76e33c043d0@f36g2000hsa.googlegroups.com> References: <4e9ff9ad-6fe5-413c-b81f-c76e33c043d0@f36g2000hsa.googlegroups.com> Message-ID: <4858D2F6.4060004@mattnordhoff.com> Nader wrote: > Hello, > > I have a gzip file and I try to read from this file withe the next > statements: > > gunziped_file = gzip.GzipFile('gzip-file') > input_file = open(gunziped_file,'r') > > But I get the nezt error message: > > Traceback (most recent call last): > File "read_sfloc_files.py", line 131, in ? > input_file = open(gunziped_file,'r') > TypeError: coercing to Unicode: need string or buffer, instance found > > I think that I do some mistake. Would some body tell me what is my > mistake? > > Nader gzip.GzipFile() creates a file-like object. You don't call open() on it; you use it directly. $ echo foo >test $ gzip test $ python >>> import gzip >>> gfh = gzip.GzipFile('test.gz', 'rb') >>> gfh.read() 'foo\n' >>> gfh.close() -- From sajmikins at gmail.com Wed Jun 11 17:05:59 2008 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 11 Jun 2008 14:05:59 -0700 (PDT) Subject: Simple and safe evaluator References: Message-ID: <8ffd23bc-d7e9-49a0-a166-79baa174b265@u12g2000prd.googlegroups.com> On Jun 11, 1:25 pm, bvdp wrote: > Is there a simple/safe expression evaluator I can use in a python > program. I just want to pass along a string in the form "1 + 44 / 3" or > perhaps "1 + (-4.3*5)" and get a numeric result. > > I can do this with eval() but I really don't want to subject my users to > the problems with that method. > > In this use I don't need python to worry about complex numbers, > variables or anything else. Just do the math on a set of values. Would > eval() with some restricted list of permitted operators do the trick? > > I'm feeling too lazy to write/debug my own parser for this :) > > Thanks, Bob. Funny, I need exactly the same kind of parser myself right now. Fredrik Lundh has posted some code-and-explanation on an excellent simple parser that's easy to extend. http://effbot.org/zone/simple-iterator-parser.htm Just make it recognize the operator tokens you're interested in and if a string parsers w/o errors then you know it's safe to eval(). I probably won't get to writing this myself for a few days or a week, but if you do will you post it here (or send me a copy)? I'll do the same if I get to it sooner. Regards, ~Simon From ncoghlan at gmail.com Wed Jun 4 07:29:38 2008 From: ncoghlan at gmail.com (NickC) Date: Wed, 4 Jun 2008 04:29:38 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> Message-ID: <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> On Jun 4, 4:09 am, "Russ P." wrote: > What is it about leading underscores that bothers me? To me, they are > like a small pebble in your shoe while you are on a hike. Yes, you can > live with it, and it does no harm, but you still want to get rid of it. With leading underscores, you can see *at the point of dereference* that the code is accessing private data. With a "this is private" keyword you have no idea whether you're accessing private or public data, because the two namespaces get conflated together. I'll keep my pebble, thanks. Cheers, Nick. From guillermo.listas at googlemail.com Tue Jun 3 19:33:53 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Tue, 3 Jun 2008 16:33:53 -0700 (PDT) Subject: Keep a script running in the background References: <210b7fc6-ed52-461d-8b53-455e247d7a29@e39g2000hsf.googlegroups.com> Message-ID: These are the basic requirements: Script A must keep a dictionary in memory constantly and script B must be able to access and update this dictionary at any time. Script B will start and end several times, but script A would ideally keep running until it's explicitly shut down. I have the feeling the way to do this is Python is by pickling the dict, but I need the method that gives the best performance. That's why I'd rather want to keep it in memory, since I understand pickling involves reading from and writing to disk. I'm using SQLite as a database. But this dict is an especial index that must be accessed at the highest speed possible. From mail at timgolden.me.uk Fri Jun 27 09:59:38 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 27 Jun 2008 14:59:38 +0100 Subject: shorten path to files In-Reply-To: References: Message-ID: <4864F24A.6030602@timgolden.me.uk> > On 2008-06-27, cesco wrote: >> Hi, >> >> I need to retrieve the content of some files which are placed on a >> network drive so in order to open them I need the full path to the >> file. >> Unfortunately some times the path is longer than 256 characters and in >> Windows such a path is too long with the result that the file is not >> found (though it is there). >> >> Is there any way around this? It's not clear from your description whether this applies, but there is an API to obtain the short version of a Windows path: http://timgolden.me.uk/pywin32-docs/win32api__GetShortPathName_meth.html (NB this is obviously the pywin32 project; I'm simply hosting a copy of the docs). Also, on more recent versions of the NT family, you can map drive letters to deep paths, you can do something like this: NET USE * \\server\share\path1\path2\path3\path4 and then do things with x:\path5\path6\ etc. And you may find that passing a version of the filename as in the example below will bypass the limit anyway. Note that this uses the \\?\ prefix. contents = open (ur"\\?\c:\some\really\long\path").read () TJG From __peter__ at web.de Sun Jun 15 07:41:23 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Jun 2008 13:41:23 +0200 Subject: marshal.dumps quadratic growth and marshal.dump not allowing file-like objects References: Message-ID: John Machin wrote: >> Here's how marshal resizes the string: >> >> newsize = size + size + 1024; >> if (newsize > 32*1024*1024) { >> newsize = size + 1024*1024; >> } >> >> Maybe you can split your large objects and marshal multiple objects to >> keep the size below the 32MB limit. >> > > But that change went into the svn trunk on 11-May-2008; perhaps the OP > is using a production release which would have the previous version, > which is merely "newsize = size + 1024;". That is indeed much worse. Depending on what the OP means by "large objects" the problem may be fixed in subversion then. > Do people really generate 32MB pyc files, or is stopping doubling at > 32MB just a safety valve in case someone/something runs amok? A 32MB pyc would correspond to a module of roughly the same size. So someone/something runs amok in either case. Peter From lists at cheimes.de Tue Jun 10 18:43:57 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 11 Jun 2008 00:43:57 +0200 Subject: Question by someone coming from C... In-Reply-To: <1213049846.3030.28.camel@jmk> References: <70c02bf1-b26f-4fba-9a33-38e79e3e34eb@p25g2000pri.googlegroups.com> <1213049846.3030.28.camel@jmk> Message-ID: John Krukoff wrote: > Since you probably want access to these from many different places in > your code, I find the simplest way is to create a logging module of your > own (not called logging, obviously) and instantiate all of your loggers > in that namespace, then import that one module as needed. No, don't do that. Simple do import logging log = logging.getLogger("some_name") The logging module takes care of the rest. The logging.getLogger() function creates a new logger *only* when the name hasn't been used yet. Christian From metalkeys404 at gmail.com Sun Jun 29 02:09:04 2008 From: metalkeys404 at gmail.com (Ampedesign) Date: Sat, 28 Jun 2008 23:09:04 -0700 (PDT) Subject: lxml and links References: <4865C579.9010401@behnel.de> Message-ID: On Jun 27, 10:00?pm, Stefan Behnel wrote: > Ampedesign wrote: > > I'm trying to extract all the links on a page with lxml. Ideally, I > > would like it to return me a list of hrefs of each link on the page, > > in a list. > > > How would I go about doing this? > > Read the manual? > > http://codespeak.net/lxml/dev/lxmlhtml.html#working-with-linkshttp://codespeak.net/lxml/dev/tutorial.html#tree-iterationhttp://codespeak.net/lxml/dev/xpathxslt.html#xpath > > Stefan Yeah, I was just having some trouble understanding it. But nevermind, I think I figured it out. From larry.bates at websafe.com` Sat Jun 14 13:43:52 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 14 Jun 2008 12:43:52 -0500 Subject: Python + RDBM framework? In-Reply-To: References: Message-ID: <9PGdnQYEHsf_nsnVnZ2dnUVZ_t3inZ2d@comcast.com> bukzor wrote: > It seems that whenever I have an application that uses a database > (MySQL) I end up writing a database framework from scratch. Is there > some accepted pre-existing project that has done this? > > I see Django, but that seems to have a lot of web-framework that I > don't (necessarily) need. I just want to have my objects go in and out > of the database in a consistent manner without writing a ton of code. > Can you just use the database part without making a full-blow web app? > > I see Zope, but that doesn't use MySQL (as far as I can tell), which > I've invested a lot of time learning to use and optimize. Also, my > manager wants to be able to log into a MySQL prompt and be able to > look at the data. > > --Buck Zope definitely has MySQL interface, but if you think Django is a lot then Zope is even more. If I'm understanding your correctly what you want is ORM/ These links should help: http://pythonnotes.blogspot.com/2004/09/python-orm-tools.html http://www.sqlalchemy.org/ http://www.sqlobject.org/ -Larry From francis.girard07 at gmail.com Wed Jun 18 07:55:46 2008 From: francis.girard07 at gmail.com (Francis Girard) Date: Wed, 18 Jun 2008 07:55:46 -0400 Subject: Interpreting string containing \u000a Message-ID: Hi, I have an ISO-8859-1 file containing things like "Hello\u000d\u000aWorld", i.e. the character '\', followed by the character 'u' and then '0', etc. What is the easiest way to automatically translate these codes into unicode characters ? Thank you Francis Girard From carsten.haese at gmail.com Tue Jun 10 15:09:33 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Tue, 10 Jun 2008 15:09:33 -0400 Subject: problems with opening files due to file's path In-Reply-To: References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> Message-ID: Alexnb wrote: > No this time it perhaps gave me the worst of all heres what I entered, and > the output > >>>> startfile(r"%s"%full) ***full is the path*** > > startfile(r"%s"%full) > > WindowsError: [Error 2] The system cannot find the file specified: > '"C:\\Documents and Settings\\Alex\\My Documents\\My > Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I\'m Yours (Single)\x01 - I\'m > Yours.wma"' Contrary to what other posters have asserted, doing the above can't make a difference. Putting 'r' in front of a string literal tells Python not to give backslashes in the string literal any special treatment. Since there are no backslashes in "%s", the 'r' does nothing. Therefore, (r"%s"%full) is the same as ("%s"%full), which is the same as (full), assuming that `full` is the name of a string. The real answer lies in fixing the code where you're assigning the pathname to 'full', which you haven't posted. Please post the code where you're assigning the pathname, or better yet, post the complete code you're running. -- Carsten Haese http://informixdb.sourceforge.net From samslists at gmail.com Fri Jun 20 18:44:56 2008 From: samslists at gmail.com (samslists at gmail.com) Date: Fri, 20 Jun 2008 15:44:56 -0700 (PDT) Subject: Time-out for regular expressions... Message-ID: I'm doing a lot of regular expressions these days. Sometimes when I'm crafting them I mess up, and make them too complicated. So that when my program runs, they take forever. (Maybe not literally forever---I abort the program after a few seconds.) What I'd like to have happen is every time I search using a regular expression is after a few seconds (the exact number being user definable), it will stop searching, perhaps by raising an exception. How can I implement this? Thanks From tracyde at gmail.com Fri Jun 6 09:24:23 2008 From: tracyde at gmail.com (Derek Tracy) Date: Fri, 6 Jun 2008 09:24:23 -0400 Subject: Python CGI Upload from Server Status In-Reply-To: <608040960806060616ja7fbc89ya9c5f92c881b14d@mail.gmail.com> References: <9999810b0806060550w5a7297dbm8ba5cc902cad6f8b@mail.gmail.com> <608040960806060616ja7fbc89ya9c5f92c881b14d@mail.gmail.com> Message-ID: <9999810b0806060624j23639fc5r3c90e010489801eb@mail.gmail.com> On Fri, Jun 6, 2008 at 9:16 AM, John Dohn wrote: > On Sat, Jun 7, 2008 at 12:50 AM, Derek Tracy wrote: > >> I am trying to create a simple python cgi app that allows the user to kick >> off an ftp from the server the cgi is on to another server; I have that >> piece working using ftplib but since the files in question are usually very >> large (500mb to 2gb) in size I want to be able to display some sort of >> status to the user, preferrably a progress bar of some sort. > > > You'll need some AJAX progress bar (hint: google for this term ;-) that > will be getting updates from the server or request an update every second or > so. > > The question is if your upload code can provide progress tracking? If it's > just a call to some xyz.upload("/here/is/my-500M-file.bin") that only > returns after several minutes of uploading without giving you any updates on > how fast things go you're probably out of luck. > OTOH if it can do e.g.callbacks for progress reporting or if it can run in > a separate thread that you could query somehow you can hook that to that > AJAX thing of your choice. > > JDJ > > -- > http://mail.python.org/mailman/listinfo/python-list > I will look for the AJAX Progress Bar, but I will admit I have never touched AJAX and haven't written javascript in years. I patched Pythons ftplib.py storbinary() to send callbacks to the specified method, so I have the callbacks locked down. The thing to note is that this app isn't allowing the user to upload to the server the cgi is on but rather allowing the user to kick off an ftp process on the server to another server. Would there be a way to do this with python cgi and automatically append or update information on the page it is displaying? -- --------------------------------- Derek Tracy tracyde at gmail.com --------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From circularfunc at yahoo.se Sun Jun 22 18:27:56 2008 From: circularfunc at yahoo.se (cirfu) Date: Sun, 22 Jun 2008 15:27:56 -0700 (PDT) Subject: rightclick-copy in IDLE? Message-ID: <6b40b216-65b8-40da-9072-7b3249086c7c@m44g2000hsc.googlegroups.com> when i rightclick in python idle i get set breakpoint or something. n options i dont find a way to change to the normal copy/paste options. From goldnery at gmail.com Sun Jun 1 08:32:45 2008 From: goldnery at gmail.com (Gandalf) Date: Sun, 1 Jun 2008 05:32:45 -0700 (PDT) Subject: Need Tutorial For the following lib References: <9950cf3f-e58a-413a-bdff-a40cc1c6cf6d@8g2000hse.googlegroups.com> <0bdd04b8-23b6-4a68-bda2-6984428ce7bd@b1g2000hsg.googlegroups.com> <4KCdnQj2nvh7F9_VnZ2dnUVZ_uidnZ2d@comcast.com> Message-ID: On Jun 1, 1:41 pm, Larry Bates wrote: > Gandalf wrote: > > Hi scott, you couldn't be more wrong about my laziness. I straggle > > with my poor English for hours to fined what I'm looking for. > > I found a very simple and not comprehensive tutorial for the pyWinAuto > > lib in this addresshttp://pywinauto.openqa.org/ > > but it only show how to do the basic, and my knowledge at this point > > is not enough to figure the rest I need to know by myself > > I found another simple lib for the watsup that based on winGuiAuto > > lib in this address > >http://www.tizmoi.net/watsup/intro.html > > But for some risen I couldn't manage to ran it in my computer > > > I'm trying to generate auto mouse double click or auto selecting text > > (the selecting text part is the one I interest in. mouse double click > > just do the same effect if the mouse cursor is on text) > > > I'm sorry you feel I'm lazy. The truth is that event writing this > > message takes me an enormous power. > > weather you choose to help me or not I still going to keep trying , > > But you have the opportunity to save me lots of trouble, So maybe one > > day I could help others. > > > so if you familiar with any good tutorial for this library please let > > me know and if not then thank you anyway for wonting to help > > > Y.G > > What you want is an easy solution to what isn't an easy problem, but (as with > your other post) you refuse to provide enough information to allow us to help > you. If I were you, I would download wxPython and go through the demos that it > includes. comp.python.wxpython list is excellent (at least as good as this one) > for any follow-up questions. Windows events and mouse clicks are going to take > a concerted effort (on your part) to learn (especially if you haven't > accomplished such a task in another language). > > -Larry Hi, Larry. thank you for your interaction. I did manage to do half of the things I was asking you about them. I manage to create an application which react to a mouse and keyboard events that occur anywhere in the O.P (that done easily by the phHook library here http://mindtrove.info/articles/monitoring-global-input-with-pyhook/#toc-references ) And I manage to find lib which auto generate event they event show you with video how simple it's to get done http://pywinauto.openqa.org/ and this is the video. it's interesting http://showmedo.com/videos/video?name=UsingpyWinAutoToControlAWindowsApplication&fromSeriesID=7 The only problem is that they show only how to automatically open notepad. they have this DoubleClick method as I saw in the documentation (i think this is what I'm looking for) but they don't show how to use it. I'm telling you that because I believe it's not as complex as you think it is. I think I'm close. if i could just fine a manual which show more examples or a bit more information i can do this. Thank you From exarkun at divmod.com Mon Jun 16 14:46:54 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 16 Jun 2008 14:46:54 -0400 Subject: String Concatenation O(n^2) (was: Re: Explaining Implementing a Binary Search Tree.) In-Reply-To: <3fc761710806161030r35e9b21gfe0f76326adb66b9@mail.gmail.com> Message-ID: <20080616184654.4714.1818914611.divmod.quotient.9798@ohm> On Mon, 16 Jun 2008 11:30:19 -0600, Ian Kelly wrote: >On Mon, Jun 16, 2008 at 11:09 AM, Jean-Paul Calderone > wrote: >> It will depend what version of Python you're using and the *exact* details >> of the code in question. An optimization was introduced where, if the >> string being concatenated to is not referred to anywhere else, it will be >> re-sized in place. This means you'll probably see sub-quadratic behavior, >> but only with a version of Python where this optimization exists and only >> if the code can manage to trigger it. > >AFAICT, PyString_Concat never calls _PyString_Resize. Am I looking in >the wrong place? Yep. The optimization is done directly from the eval loop. Take a look at ceval.c, if you search for _PyString_Resize you should see it. Jean-Paul From kyosohma at gmail.com Tue Jun 10 13:11:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 10 Jun 2008 10:11:13 -0700 (PDT) Subject: Instructions on how to build py2exe 0.6.8 (or an installer would be nice, too!) References: <5426baaf-2ba6-41b0-a0ec-1070429b5195@x35g2000hsb.googlegroups.com> <7f3360e4-8a12-45cf-99fa-6172cb5a1aaa@a1g2000hsb.googlegroups.com> Message-ID: <5cde3ec8-2e8d-4c1e-bee9-1ee51f649cd8@d45g2000hsc.googlegroups.com> On Jun 10, 10:47?am, chard... at gmail.com wrote: > On Jun 10, 11:34?am, Mike Driscoll wrote: > > > > > Maybe I'm missing something, but I can rename the executables I create > > using py2exe 0.6.6 to anything I want after they're created. > > > Or are you talking about a Windows installer for the py2exe module > > itself? Where are you finding this 0.6.8 version anyway? I can't find > > it onwww.py2exe.org > > > Anyway, what Thomas is talking about is that the only way to create a > > usable installer of py2exe on Windows is to use the same compiler that > > the Python you are using. As I understand it, Python 2.4 and 2.5 used > > Visual Studio 2003. I think 2.3 used VS6. I have both, so I can try to > > compile an installer for any of those versions if you can link me to > > the source. > > > Mike > > > Python Extension Building Network: ? ? http:\\www.pythonlibrary.org > > The issue with renaming executables only applies to single-file > executables, i.e. ones created with zipfile = None as an argument to > setup() and --bundle 1 as a command line argument. This is a known > issue as of 0.6.6:http://py2exe.org/index.cgi/ProblemsToBeFixed I'm using GUI2Exe to wrap my 0.6.6 version of py2exe. I use the bundle into a single file option in it and have zipfile=None too. But maybe one of my other switches is different. > > I found sources for 0.6.8 on CVS at:http://sourceforge.net/cvs/?group_id=15583 > > A Windows installer for the 0.6.8 py2exe module would be ideal, but > somehow I doubt that's going to happen anytime soon since there hasn't > been a new installer since 2006. If you are willing to build that for > me (since I don't have VS) I'd really appreciate it : ) I'm using 32- > bit WinXP on this computer. I finally figured out how to check out the code. I'm at work now, where I only have VS2008 installed so I'll have to wait until I get home this evening to try compiling it. I'll let you know if I have any luck. --------------------- Mike Python Extension Building Network: http:\\www.pythonlibrary.org From jgodoy at gmail.com Wed Jun 25 06:38:38 2008 From: jgodoy at gmail.com (Jorge Godoy) Date: Wed, 25 Jun 2008 07:38:38 -0300 Subject: IDE on the level of Eclipse or DEVc++? References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> <486214ae$0$9742$426a34cc@news.free.fr> <87ej6lq02c.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Bruno Desthuilliers writes: > >> If you're into clickodroms, you may want to have a look at Eric too. >> As far as i'm concerned, I still wait for something that would be >> worth dropping emacs + python-mode + ecb. > > I'm having the most success with this combination, yes. Though ecb is > rather non-Emacs-like in its configuration, and seems to strongly > expect to be run in graphical mode, it is still very powerful. Heh... I'm another one that keeps trying new things but comes back to Emacs all the time. Eclipse is too heavy, NetBeans has a poor support, Eric is too "mousy"... -- Jorge Godoy From xkenneth at gmail.com Thu Jun 26 21:59:01 2008 From: xkenneth at gmail.com (xkenneth) Date: Thu, 26 Jun 2008 18:59:01 -0700 (PDT) Subject: Design principles and architecture of an information transfer standard based on XML and SOAP Message-ID: <070a2cec-5c4b-44ab-93ff-a0811f7c226b@u6g2000prc.googlegroups.com> All, So i'm just about to undertake my first real open source project, and I'm looking for a bit of advice. There's an oilfield standard called WITSML (Wellsite Information Transfer Standard Markup Language - witsml.org), it's basically a collection of XML schemas and a spec for an client-server based communication standard based on SOAP and WSDL. I'm looking for advice and past experience on how to architect this project and implement it properly. I'm fairly new with concepts such as threading, ORM, etc in a server/client context. If anyone has any past experience they'd like to contribute, architecture theory, documentation, anything at all, I'd be very grateful. You can find our project here: (also feel more than welcome to join and help!) http://www.openplans.org/projects/openwitsml/summary Regards, Kenneth Miller xkenneth at gmail.com From cjw at ncf.ca Mon Jun 23 18:46:14 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 23 Jun 2008 18:46:14 -0400 Subject: IDE on the level of Eclipse or DEVc++? In-Reply-To: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> Message-ID: cirfu wrote: > is there an IDE for python of the same quality as Eclipse or DEVC++? > > I am currently using the editor that coems iwth python and it is all > fine but for bigger projects it would be nice to have some way to > easier browse the projectfiles for example. I don't know these but you might look at PyScripter. Colin W. From kusumi.tomohiro at jp.fujitsu.com Wed Jun 4 22:00:30 2008 From: kusumi.tomohiro at jp.fujitsu.com (Tomohiro Kusumi) Date: Thu, 05 Jun 2008 11:00:30 +0900 Subject: Question regarding re module Message-ID: <484748BE.4000704@jp.fujitsu.com> Hi, I have a question regarding re module. # By the way I'm not in this list, so I'm sorry but please CC me. I tried following code in Python shell using a regular expression. Why doesn't the result of dir(reg) have 'pattern', 'flags', and 'groupindex' although they exist as members of _sre.SRE_Pattern instance ? It sort of irritates me, because whenever I write Python code using a module which I'm not used to using, I often try Python shell with TAB complete to find out the member of module/instance. Tomohiro Kusumi ------------------------------------------------- Python 2.5 (r25:51908, May 16 2008, 13:41:55) [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> reg = re.compile(r"[0-9]+") >>> reg.pattern '[0-9]+' >>> reg.flags 0 >>> reg.groupindex {} >>> dir(reg) ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] >>> reg. reg.__copy__ reg.finditer reg.search reg.subn reg.__deepcopy__ reg.match reg.split reg.findall reg.scanner reg.sub From cwitts at gmail.com Fri Jun 27 05:59:51 2008 From: cwitts at gmail.com (Chris) Date: Fri, 27 Jun 2008 02:59:51 -0700 (PDT) Subject: Question on List References: <7f03fa3f-c8fd-45a8-b4a5-d7c66982aa4a@q27g2000prf.googlegroups.com> Message-ID: <8131e1be-a767-42c0-9409-b7353c7466ab@y38g2000hsy.googlegroups.com> On Jun 27, 9:51?am, subhabrata.i... at hotmail.com wrote: > Dear All, > I am trying to write the following code: > > def try1(n): > ? ? ? ? a1="God Godess Borother Sister Family" > ? ? ? ? a2=a1.split() > ? ? ? ? a3=raw_input("PRINT A WORD") > ? ? ? ? a4=a1.find(a3) > ? ? ? ? print a4 > ? ? ? ? a5=[] > ? ? ? ? if a4>0: > ? ? ? ? ? ? ? ? a5=a2.index(a3) > ? ? ? ? ? ? ? ? a6=a5+1 > ? ? ? ? ? ? ? ? a7=a2[a6] > ? ? ? ? ? ? ? ? print "The new word is" > ? ? ? ? ? ? ? ? print a7 > ? ? ? ? ? ? ? ? a8=a5.append(a7) > ? ? ? ? ? ? ? ? print a5 > ? ? ? ? elif a4<0: > ? ? ? ? ? ? ? ? a11=a3 > ? ? ? ? ? ? ? ? print "The word is not availiable in String" > ? ? ? ? ? ? ? ? print a11 > ? ? ? ? ? ? ? ? a6=a5.append(a11) > ? ? ? ? ? ? ? ? print a5 > ? ? ? ? else: > ? ? ? ? ? ? ? ? print "Error" > > Now, my question is I like to see a5 or the empty list as appended > with elements. Results I am getting is a5 giving single value like > ['God'],['Godess']... but I like to see it as ['God','Godess'...] etc. > Am I going wrong? > Do I have to rethink it in some other way? > If any one can kindly let me know. > Best Regards, > Subhabrata. First notes, the string .find() method return -1 for not found and zero or above if the search string is present. Remember you count from zero. Secondly, list .append() methods do not return a new list but modify the list in place. Thirdly, the .index() method of a list requires an integer and not a string. And lastly, indentation should be 4 spaces not 8. Just doing a sloppy job on the code (and my interpretation of what you wanted) def try1(n): new_list = [] input_string="God Godess Borother Sister Family" while n: user_selection=raw_input("PRINT A WORD") if input_string.find(user_selection) > -1: s = input_string.split() i = [i for i,j in enumerate(s) if j == user_selection] new_word = s[i+1] print 'The new word is %s' % new_word new_list.append(new_word) print new_list else: print 'User selection of "%s" not in the string.' % user_selection new_list.append(user_selection) print new_list n -= 1 Obviously I'm going to assume that the code you posted excluded your loop control for the "try n amount of times". What was most likely the cause is that you loop through your structure for every attempt of the n times but each time you reset your list when you re-create it. Hope that helps some. Chris From boggom at comcast.net Thu Jun 26 07:54:34 2008 From: boggom at comcast.net (boggom at comcast.net) Date: Thu, 26 Jun 2008 04:54:34 -0700 (PDT) Subject: very large graph References: <135bba90-a9dd-4fcd-9220-6271e5a7c876@59g2000hsb.googlegroups.com> Message-ID: Drawing a large graph like this is not very insightful by itself, and doing this well is still an art form. Many cool visualizations, and all very domain and question dependent, can be found at http://www.visualcomplexity.com/vc/ You can also search on flickr for network and graph drawing. Much of it is eyecandy though. What do you really want to know? Your graph is not overly huge for python, provided you do not want to compute nonlocal statistics such as betweenness metrics. (If you have a laptop running windows and with less than 1GB RAM, then you have a really large graph.) Given that you do not know much about graph theory, I would suggest that networkx applied to a subset of your large website --- one of the representative branches --- will allow for the fastest way to figure out what you want to do. Python provides access to many other libraries for html mangling or even webpage analysis. Imagine writing C code to ask questions like: how many pdfs and images? how big are they? when were these pages last updated? etc. You can come up with 10 questions faster than you can write C code, and this where python has its great advantage. You can learn graph theory while using these libraries, on one of the smaller branches of your website tree. Even interactively by using ipython. This provides at least a feeling of great power while stumbling in the dark. Many of your edges are probably repetitions associated with navigation menus to provide a standard look-and-feel. See how much of that you can strip out and find the cross-links that took effort to insert an manage. (I suggest doing the analyis on a digraph rather than a graph, even if you want to draw it as graph.) For visualization, the new ubigraph is quite fast compared to graphviz. See the cool networkx + ubigraph video at http://ubietylab.net/blog/ Ask on the networkx mailinglist when stuck. From lane at ubixum.com Fri Jun 27 23:37:33 2008 From: lane at ubixum.com (Lane Brooks) Date: Fri, 27 Jun 2008 21:37:33 -0600 Subject: CAPI and thread safety In-Reply-To: <4eb6ab80-7280-47fb-b8bc-366154f6274d@d1g2000hsg.googlegroups.com> References: <4eb6ab80-7280-47fb-b8bc-366154f6274d@d1g2000hsg.googlegroups.com> Message-ID: <4865B1FD.9060300@ubixum.com> Thanks for the pointer. I'll check it out. That is what I was looking for. Lane Benjamin wrote: > On Jun 27, 4:33 pm, Lane Brooks wrote: > >> I am writing an extension module that needs to release the global >> interpreter lock during some blocking I/O calls, but I need a mutex in >> the C code to make some of the shared data in the extension module are >> kept thread safe. Can anyone recommend a portable way to do this? I >> could use a pthread mutex, but I do not think that is portable. >> >> Are any of the python mutexes or locks exposed through the C API? I >> could not find anything. >> > > Look at Include/pythread.h. You can use PyThread_allocate_lock to get > the threading abstractions that Python uses. > > >> Thanks, >> Lane >> > > -- > http://mail.python.org/mailman/listinfo/python-list > From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jun 5 09:48:46 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 05 Jun 2008 15:48:46 +0200 Subject: Python and Harry Potter? References: <6aprloF38p4l7U1@mid.dfncis.de> Message-ID: <6aq95uF35vu95U1@mid.individual.net> Casey wrote: > Python fan??? Harry speaks Python fluently. We should all be so > lucky! > > I'm told Harry is looking forward to Py3K and getting rid of all > the old (hog)warts .... Well, how about another Python renaming flame thread then? Let's call Python 3.0 "Parselmouth" instead ... Regards, Bj?rn -- BOFH excuse #83: Support staff hung over, send aspirin and come back LATER. From google at mrabarnett.plus.com Fri Jun 20 10:56:32 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 20 Jun 2008 07:56:32 -0700 (PDT) Subject: Named tuples and projection References: Message-ID: <3ec6ca53-9ec9-42b4-8ee2-cb56a6aed375@z66g2000hsc.googlegroups.com> On Jun 20, 9:38?am, Giuseppe Ottaviano wrote: > I found the namedtuple very convenient for rapid prototyping code, for ? > functions that have to return a number of results that could grow as ? > the code evolves. They are more elegant than dicts, and I don't have ? > to create a new explicit class. Unfortunately in this situation they ? > lose the convenience of tuple unpacking: changing tuple's parameters ? > would break other functions unpacking the result. > One solution, with 3.0 syntax, would be unpacking only the used ? > parameters, using always a *rest > a, b, *rest = f() > so that if the tuple grows, the code keeps working. > However I find this confusing (and not avaliable in python 2.5). > I don't know if similar solutions have been proposed, I came up with ? > this one: > [snip] Provided you don't change the order of the items in the tuple, you can just use slicing: a, b = f()[ : 2] From wuwei23 at gmail.com Wed Jun 4 20:18:47 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 4 Jun 2008 17:18:47 -0700 (PDT) Subject: how should i use this function? References: <99ed3c04-bd62-4456-ae12-eca4179005dc@r66g2000hsg.googlegroups.com> Message-ID: <38e6c38a-d84c-486d-b9bc-f256c0a3e21c@a32g2000prf.googlegroups.com> On Jun 5, 4:14 am, Gandalf wrote: > I tried to import win32ui.PyCRichEditCtrl, But the shell told me > their's no such module. > > If anyone can show me an example it would be great For starters, you're looking at the documentation for ActivePython 2.2 rather than 2.5. Do you know about pythons introspective abilities? That you can find a list of available methods & objects by doing 'dir(win32ui)' in the interpreter? Having said that, here's how to get a PyCRichEditCtrl object: ActivePython 2.5.1.1 (ActiveState Software Inc.) based on Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import win32ui >>> rec = win32ui.CreateRichEditCtrl() >>> type(rec) It's worth noting that win32ui is basically just a wrapper around the Microsoft Foundation Classes, so you'll need to look through the MFC documentation rather than that of the wrapper. This might help get you started: http://www.onlamp.com/pub/a/python/excerpts/chpt20/pythonwin.html From jamitwidme at gmail.com Thu Jun 26 16:01:39 2008 From: jamitwidme at gmail.com (jamitwidme at gmail.com) Date: Thu, 26 Jun 2008 13:01:39 -0700 (PDT) Subject: ConfigParser: Can I read(ConfigParser.get()) a configuration file and use it to call a funciton? References: <34b51593-d787-4f12-9cc2-473d3832ff0d@k37g2000hsf.googlegroups.com> <7fd37b8c-b96d-480c-94c4-e53f8598830e@d45g2000hsc.googlegroups.com> Message-ID: <63176df7-2d7d-4679-ae2a-cdb5404741df@z72g2000hsb.googlegroups.com> Thank you for the answers. Now I understood how to call a function, let me ask you another question. configuration.cfg --------------------------------------- [1234] title: abcd function: efgh --------------------------------------- reading.py -------------------------------------------------------- import ConfigParser class Functions: def efgh(self): print 'blah' fcn = Functions() config = ConfigParser.ConfigParser() config.read('configuration.cfg') title = config.get('1234','title') # number 1 function_name = config.get('1234','function') title = getattr(fcn, function_name) title() -------------------------------------------------------- instead of assigning string value('abcd') to title at number 1 I want to assign this function(fcn.efgh()) to abcd and make abcd a FunctionType. so later on, I want to call it by abcd(), not title(). The reason is I will have a loop reading from configuration file, so I need to have different names for each function. abcd is a string I read got it from config.get('1234','title') Thanks again. From software at ginstrom.com Sun Jun 1 08:27:30 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Sun, 1 Jun 2008 21:27:30 +0900 Subject: [Business apps for Windows] Good grid + calendar, etc.? In-Reply-To: References: Message-ID: <0fc701c8c3e2$dc883b80$0203a8c0@MOUSE> > On Behalf Of Gilles Ganault > Is it hopeless, or did I overlook things? Are there other > solutions I should look at (FLTK, etc.)? For those of you > writing business apps in Python for Windows, how do things go > as far as GUI widgets are concerned? To do a bit of shameless plugging, I wrote an overview of Python GUI platforms for Windows a month or two ago: http://ginstrom.com/scribbles/2008/02/26/python-gui-programming-platforms-fo r-windows/ For your stated needs, I'd advise checking out IronPython or Python.NET (which allow use of .NET GUI libraries). Regards, Ryan Ginstrom From carbonimax at gmail.com Mon Jun 23 08:51:48 2008 From: carbonimax at gmail.com (Carbonimax) Date: Mon, 23 Jun 2008 05:51:48 -0700 (PDT) Subject: py2exe, PyQT, QtWebKit and jpeg problem References: Message-ID: <37ce3f9c-034e-4a3d-8524-310810894715@s50g2000hsb.googlegroups.com> On Jun 21, 12:21?am, David Boddie wrote: > On Friday 20 June 2008 17:24, Phil Thompson wrote: > > > On Fri, 20 Jun 2008 08:04:57 -0700 (PDT),Carbonimax > > wrote: > >> I have a problem with py2exe and QtWebKit : > >> I make a program with a QtWebKit view. > >> If I launch the .py directly, all images (jpg, png) are displayed but > >> if I compile it with py2exe I have only png images. No jpg ! > >> No error message, nothing. > > >> Have you a solution ? Thank you. > > > At a guess, the JPEG support is implemented as a Qt plugin which you are > > not including. > > Yes, that would appear to the be most obvious cause. See here for another > report about this: > > http://lists.trolltech.com/qt4-preview-feedback/2008-03/msg00064.html > > David How can I do that ? If I copy the dll in the dist directory, and I use QLibrary() and load(), it does work in the .py but it doesn't in .exe made with py2exe my code : dll = QLibrary(path_to_dll) res = dll.load() res == true in the .py res == false in the .exe :-/ From ivan.illarionov at gmail.com Fri Jun 20 04:27:06 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Fri, 20 Jun 2008 01:27:06 -0700 (PDT) Subject: advanced listcomprehenions? References: Message-ID: <3b92811d-a029-440f-9e56-1d4ca2fa064e@d1g2000hsg.googlegroups.com> On 20 ???, 11:31, Duncan Booth wrote: > Terry Reedy wrote: > >> [['Fizz', 'Buzz', 'FizzBuzz', str(i)][62/(pow(i, 4, 15) + 1)%4] for i > >> in xrange(1, 101)] > > > These make the lookup table variable, so it has to be recalculated for > > each i. > > So what? Mark Wooding was posting about mathematical elegance and came up > with that really neat pow() call. If runtime came into it then one of the > previous solutions or (as Mark already said) a straightforward sometable[i% > 15] is going beat something like this hands-down. > > This is coding for fun not profit. > > -- > Duncan Boothhttp://kupuguy.blogspot.com I can't resist... [[i,"Fizz","Buzz","FizzBuzz"][(not i%3)+(not i%5)*2] for i in range(1, 101)] Ivan From gabriela.soares.fcup at gmail.com Wed Jun 11 11:42:06 2008 From: gabriela.soares.fcup at gmail.com (Gabriela Soares) Date: Wed, 11 Jun 2008 16:42:06 +0100 Subject: [Tutor] python gui In-Reply-To: <333efb450806110825i376b9e45we2e6d98d6bdb0396@mail.gmail.com> References: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> <333efb450806110818g134b930cj6e36f7bd79a9083@mail.gmail.com> <9d68e4e90806110818q18c57bd2v8b3219de9b2a1ca1@mail.gmail.com> <333efb450806110825i376b9e45we2e6d98d6bdb0396@mail.gmail.com> Message-ID: <9d68e4e90806110842i51e3cf4fsbf8540a301db5a7f@mail.gmail.com> Hello, With all respect, I posed the question as a noob who has NO ideia how to solve the problem at hand. All I asked for were some references, such as known applications that use such technology to guide me to where I should focus. It never crossed my mind to ask for code. If I wanted to do so, I wouldn't use a mailing list and would go to search engines such as google code or krugle. I am sorry you got the wrong impression. If I didn't explain myself the most correct way, then I present my apologies. The link I gave was in flex, so redirecting me to a page about flex is useless. I was asking about how can I get a similar effect but using just python. There fits the python mailing list and the **possible** broad question. If you can't help me I surelly understand. But please do not take me for a fool kind sir/madam. Thank you, Gabriela Soares. On Wed, Jun 11, 2008 at 4:25 PM, W W wrote: > On Wed, Jun 11, 2008 at 10:18 AM, Gabriela Soares > wrote: > > How ? > > That's an extremely broad question, and shows little initiative, and > offers little information. Most of us are happy to help you solve > problems for free, but few, if any, are willing to write your programs > for free. > > > Any references ? > > www.google.com > > Norman linked to a fairly interesting project. > > Hope this helps, > Wayne > > > On Wed, Jun 11, 2008 at 4:18 PM, W W wrote: > >> > >> On Wed, Jun 11, 2008 at 8:03 AM, Gabriela Soares > >> wrote: > >> > Greetings, > >> > > >> > I want to make a dynamic dashboard, something like: > >> > > >> > http://examples.adobe.com/flex3/labs/dashboard/main.html# > >> > > >> > but using python. Is it possible ? > >> > >> Yes. > >> > >> -Wayne > > > > > > > > -- > > Gabriela Soares > > > > "I learned that courage was not the absence of fear, but the triumph over > > it. The brave man is not he who does not feel afraid, but he who conquers > > that fear." > > Nelson Mandela > > > > -- > To be considered stupid and to be told so is more painful than being > called gluttonous, mendacious, violent, lascivious, lazy, cowardly: > every weakness, every vice, has found its defenders, its rhetoric, its > ennoblement and exaltation, but stupidity hasn't. - Primo Levi > -- Gabriela Soares "I learned that courage was not the absence of fear, but the triumph over it. The brave man is not he who does not feel afraid, but he who conquers that fear." Nelson Mandela -------------- next part -------------- An HTML attachment was scrubbed... URL: From dp at admailinc.com Wed Jun 18 13:26:31 2008 From: dp at admailinc.com (Ethan Furman) Date: Wed, 18 Jun 2008 09:26:31 -0800 Subject: Does '!=' equivelent to 'is not' [drifting a little more] In-Reply-To: References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> Message-ID: <48594547.8090305@admailinc.com> Gabriel Genellina wrote: > (This thread is getting way above 10000cp...) What is 10000cp? -- Ethan From jeff_d_harper at hotmail.com Sat Jun 21 01:15:37 2008 From: jeff_d_harper at hotmail.com (jeff_d_harper at hotmail.com) Date: Fri, 20 Jun 2008 22:15:37 -0700 (PDT) Subject: Sqlite3 textfactory and user-defined function Message-ID: I've run into a problem with text encoding in the Sqlite3 module. I think it may be a bug. By default sqlite3 converts strings in the database from UTF-8 to unicode. This conversion can be controlled by changing the connection's text_factory. I have a database that stores strings in 8-bit ISO-8859. So, I set the text_factory to do no conversion. In my database I use user defined functions. I noticed that even when I set text_factory = lambda x:x, it appears to do UTF-8 to unicode conversion on strings that are passed to my user defined function. I've included a small program that illustrates the problem. It creates a database and table in memory and then populates 2 rows. One row contains an ASCII string. The other row contains a string with the non-ascii string, "T?st". Then, the program does an SQL select which calls the user-defined function, my_func(). The resulting row tuples contain 8-bit strings. But, my_func() is passed unicode strings. Notice, my_func is called with None instead of "T?st". I suspect this is because the binary representation of "T?st" is not valid UTF-8. Is there a way to turn off the UTF-8 to unicode when my_func() is called? Is this a bug or intended behavior? import sqlite3 def create_table(dbase): #dbase.execute(r"""PRAGMA encoding = "UTF-16le";""") dbase.execute(r"""CREATE TABLE `my_table` ( 'id' INTEGER, 'column' BLOB); """) def add_rows(dbase): c = dbase.cursor() string1 = "Test" string2 = "T\xe9st" try: print string1 c.execute(r"""INSERT INTO `my_table` ('id', 'column') VALUES (?,?)""", (1,string1)) print string2 c.execute(r"""INSERT INTO `my_table` ('id', 'column') VALUES (?,?)""", (2,string2,)) finally: c.close() def select_rows(dbase): c = dbase.cursor() try: c.execute(r"""SELECT *, my_func(`column`) FROM `my_table`""") for row in c: print row finally: c.close() def factory(x): print 'x =', x return x def my_func(p): print 'my_func(%r) type = %s' % (p,type(p)) def my_test(): db_path = ":memory:" try: os.remove(db_path) except: pass dbase = sqlite3.connect(db_path) dbase.text_factory = lambda x:x dbase.create_function('my_func', 1, my_func) try: create_table(dbase) add_rows(dbase) select_rows(dbase) finally: dbase.commit() dbase.close() my_test() From socyl at 987jk.com.invalid Thu Jun 19 17:17:35 2008 From: socyl at 987jk.com.invalid (kj) Date: Thu, 19 Jun 2008 21:17:35 +0000 (UTC) Subject: Why no output from xml.dom.ext.PrettyPrint? Message-ID: OK, the following should work but doesn't, and I can't figure out why: >>> from xml.marshal.generic import dumps >>> dumps( ( 1, 2.0, 'foo', [3,4,5] ) ) '12.0foo345' >>> from xml.dom.ext import PrettyPrint >>> PrettyPrint( dumps( ( 1, 2.0, 'foo', [3,4,5] ) ) ) >>> import sys >>> PrettyPrint( dumps( ( 1, 2.0, 'foo', [3,4,5] ) ), sys.stdout ) >>> Why am I seeing no output from PrettyPrint? TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From python at hope.cz Mon Jun 9 11:02:51 2008 From: python at hope.cz (Johny) Date: Mon, 9 Jun 2008 08:02:51 -0700 (PDT) Subject: How to find the first space? Message-ID: <7a91cc8f-2e93-46e9-8360-a01da9170187@m44g2000hsc.googlegroups.com> How can I find the first space using regex? For example I have text Text=' This is a sample ' The last space I can remove by Text=re.sub(r"\s(?!\w)",'',Text) but I do not know how to remove the first space. Can anyone help? Thanks L. From circularfunc at yahoo.se Tue Jun 24 14:30:55 2008 From: circularfunc at yahoo.se (cirfu) Date: Tue, 24 Jun 2008 11:30:55 -0700 (PDT) Subject: NameError: name 'maketrans' is not defined, pythonchallenge References: <50a56351-b875-4a08-b19c-3ac6092fd509@e39g2000hsf.googlegroups.com> Message-ID: import string text = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." table = string.maketrans(string.ascii_lowercase, string.ascii_lowercase[2:]+string.ascii_lowercase[:2]) print string.translate(text,table) From Russ.Paielli at gmail.com Tue Jun 3 00:11:58 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 2 Jun 2008 21:11:58 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> Message-ID: <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> On Jun 2, 6:21 pm, alex23 wrote: > On Jun 3, 9:41 am, "Russ P." wrote: > > > Here's what I think Python should have. I think it should have a > > keyword, something like "priv," to identify data or functions as > > "private." > > As I stated earlier in this thread, if you want a public interface and > a private implementation, rather than adding another language feature > why not just separate them into two classes? This is exactly what the > Bridge pattern provides and would clearly denote your intention in the > code. Yes, that looks interesting, but I think it has a couple of drawbacks. First, it requires another completely separate class for the "implementation" (although perhaps that could be a nested class). Secondly, I think it essentially just adds a sort of inner namespace through which the "private" data is accessed. That might be a good idea, but I don't think it's quite the same as encapsulation. From bignose+hates-spam at benfinney.id.au Tue Jun 17 22:26:57 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 18 Jun 2008 12:26:57 +1000 Subject: Annoying message when interrupting python scripts References: <578d1ef8-231b-46fa-a181-e320fe1cc368@s33g2000pri.googlegroups.com> Message-ID: <87y753wk9a.fsf@benfinney.id.au> John Machin writes: > On Jun 18, 12:51 am, geoffbache wrote: > [snip] > > Is this a bug? I couldn't find any code, but I imagine something like > > try: > > import site > > except: > > sys.stderr.write("import site failed; use -v for traceback\n") > > > > which should surely allow a KeyboardInterrupt exception through? > > Surely?? A bare "except" catches *all* remaining uncaught exceptions. I parsed that "should" as "this should be changed". > Allowing a KeyboardInterrupt exception through would require: > except KeyboardInterrupt: > pass Actually, to allow it through would require re-raising it: except KeyboardInterrupt: raise Yes, I think that's what Geoff is saying "should" be done :-) -- \ "When I was born I was so surprised I couldn't talk for a year | `\ and a half." -- Gracie Allen | _o__) | Ben Finney From chardish at gmail.com Tue Jun 10 14:01:02 2008 From: chardish at gmail.com (chardish at gmail.com) Date: Tue, 10 Jun 2008 11:01:02 -0700 (PDT) Subject: Instructions on how to build py2exe 0.6.8 (or an installer would be nice, too!) References: <5426baaf-2ba6-41b0-a0ec-1070429b5195@x35g2000hsb.googlegroups.com> <7f3360e4-8a12-45cf-99fa-6172cb5a1aaa@a1g2000hsb.googlegroups.com> <5cde3ec8-2e8d-4c1e-bee9-1ee51f649cd8@d45g2000hsc.googlegroups.com> Message-ID: <9af1adfb-5bce-48e8-b17f-4d838f788b90@d77g2000hsb.googlegroups.com> On Jun 10, 1:11?pm, Mike Driscoll wrote: > On Jun 10, 10:47?am, chard... at gmail.com wrote: > > > > > On Jun 10, 11:34?am, Mike Driscoll wrote: > > > > Maybe I'm missing something, but I can rename the executables I create > > > using py2exe 0.6.6 to anything I want after they're created. > > > > Or are you talking about a Windows installer for the py2exe module > > > itself? Where are you finding this 0.6.8 version anyway? I can't find > > > it onwww.py2exe.org > > > > Anyway, what Thomas is talking about is that the only way to create a > > > usable installer of py2exe on Windows is to use the same compiler that > > > the Python you are using. As I understand it, Python 2.4 and 2.5 used > > > Visual Studio 2003. I think 2.3 used VS6. I have both, so I can try to > > > compile an installer for any of those versions if you can link me to > > > the source. > > > > Mike > > > > Python Extension Building Network: ? ? http:\\www.pythonlibrary.org > > > The issue with renaming executables only applies to single-file > > executables, i.e. ones created with zipfile = None as an argument to > > setup() and --bundle 1 as a command line argument. This is a known > > issue as of 0.6.6:http://py2exe.org/index.cgi/ProblemsToBeFixed > > I'm using GUI2Exe to wrap my 0.6.6 version of py2exe. I use the bundle > into a single file option in it and have zipfile=None too. But maybe > one of my other switches is different. > > > > > I found sources for 0.6.8 on CVS at:http://sourceforge.net/cvs/?group_id=15583 > > > A Windows installer for the 0.6.8 py2exe module would be ideal, but > > somehow I doubt that's going to happen anytime soon since there hasn't > > been a new installer since 2006. If you are willing to build that for > > me (since I don't have VS) I'd really appreciate it : ) I'm using 32- > > bit WinXP on this computer. > > I finally figured out how to check out the code. I'm at work now, > where I only have VS2008 installed so I'll have to wait until I get > home this evening to try compiling it. I'll let you know if I have any > luck. > > --------------------- > Mike > > Python Extension Building Network: ? ? http:\\www.pythonlibrary.org Thanks, Mike. Hopefully you'll have more luck than I've had : ) Evan From kumarvs06561 at gmail.com Tue Jun 10 13:25:37 2008 From: kumarvs06561 at gmail.com (kumarvs06561 at gmail.com) Date: Tue, 10 Jun 2008 10:25:37 -0700 (PDT) Subject: make more money Message-ID: make more money internet jobs easy way to make money http://kumarpracticals.blogspot.com/ From kyosohma at gmail.com Tue Jun 17 13:49:57 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 17 Jun 2008 10:49:57 -0700 (PDT) Subject: text alignment References: <39d1c620-9923-46e7-999d-ed86c8b465ff@34g2000hsh.googlegroups.com> Message-ID: <114f3f4c-4004-488b-86c5-4bf6416e15bd@l42g2000hsc.googlegroups.com> On Jun 17, 11:45?am, Gandalf wrote: > On Jun 17, 6:43?pm, Gandalf wrote: > > > Hi every one. What is the similar python WX style property for CSS > > text-align? > > > I need this item text to start from the right direction: > > > aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60)) > > ? ? ? ? aaa.LoadPage('../../aa.html') > > > Thanks! > > *right to the left direction... > > And I'm using pythin 2.5 on XP (I forget to mention...) The HtmlWindow widget can only display simple html. So, while you cannot use CSS, you should be able to use the simple html alignment directives. Check out the following site for pointers: http://www.htmlite.com/lite008.php If you want to be able to use CSS and javascript, you'll want to use the ActiveX_IEHtmlWindow (wx.lib.iewin) widget instead as it embeds Internet Explorer. Mike From Lie.1296 at gmail.com Sat Jun 21 08:55:12 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 21 Jun 2008 05:55:12 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <79a1c500-1844-4405-8f52-21e845a85f9b@z66g2000hsc.googlegroups.com> Message-ID: <5678904d-93ee-40f1-97b2-78d49ce29fb7@f24g2000prh.googlegroups.com> On Jun 21, 2:02?pm, eliben wrote: > On Jun 21, 8:52 am, Peter Otten <__pete... at web.de> wrote: > > > > > eliben wrote: > > > On Jun 20, 2:44 pm, Peter Otten <__pete... at web.de> wrote: > > >> eliben wrote: > > >> > Additionally, I've found indentation to be a problem in such > > >> > constructs. Is there a workable way to indent the code at the level of > > >> > build_func, and not on column 0 ? > > > >> exec"if 1:" + code.rstrip() > > > >> Peter > > > > Why is the 'if' needed here ? I had .strip work for me: > > > A simple .strip() doesn't work if the code comprises multiple lines: > > > >>> def f(): > > > ... ? ? return """ > > ... ? ? x = 42 > > ... ? ? if x > 0: > > ... ? ? ? ? ? ? print x > > ... ? ? """ > > ...>>> exec "if 1:\n" + f().rstrip() > > 42 > > >>> exec f().strip() > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? File "", line 2 > > ? ? if x > 0: > > ? ? ^ > > IndentationError: unexpected indent > > I see. In my case I only evaluate function definitions with 'exec', so > I only need to de-indent the first line, and the others can be > indented because they're in a new scope anyway. What you suggest works > for arbitrary code and not only function definitions. It's a nice > trick with the "if 1:" :-) Have you actually profiled your code? Or are you just basing this assumptions on guesses? From goldnery at gmail.com Wed Jun 4 14:59:33 2008 From: goldnery at gmail.com (Gandalf) Date: Wed, 4 Jun 2008 11:59:33 -0700 (PDT) Subject: how should i use this function? References: <99ed3c04-bd62-4456-ae12-eca4179005dc@r66g2000hsg.googlegroups.com> <5a09fa94-b3ce-4a13-af42-b9a1e6980900@25g2000hsx.googlegroups.com> Message-ID: On Jun 4, 8:21 pm, sturlamolden wrote: > On Jun 4, 8:14 pm, Gandalf wrote: > > > I tried to import win32ui.PyCRichEditCtrl, But the shell told me > > their's no such module. > > There isn't, as it is a class. win32ui is a module. If you cannot > import that, you don't have pywin32 installed. Go get it from > Sourceforge. But I pywin32 use it all the time i have pywinauto From none at this.time Thu Jun 26 00:07:16 2008 From: none at this.time (The Pythonista) Date: Thu, 26 Jun 2008 00:07:16 -0400 Subject: Any GUI lib wiget is capable of a WYSIWYG editor? References: Message-ID: On Tue, 24 Jun 2008 14:23:12 +0800, oyster wrote: > that is an html editor with text and picture, while the picture is > linked to the local image file. > > for wxPython, the richtextcontrol save the image as en embedded object, > so it is not my choice > > is there any other GUI lib and/or sample code to do so? > > thanks Consider TkHtml. You can find a Tix wrapper for it here: http://tix.sourceforge.net/Tixapps/src/Python/TkHtml.py -- code.py: A blog about life, the universe, and Python http://pythonista.wordpress.com ** Posted from http://www.teranews.com ** From mccredie at gmail.com Tue Jun 24 18:45:42 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 24 Jun 2008 15:45:42 -0700 (PDT) Subject: Sequence iterators with __index__ References: Message-ID: <433c6aca-745e-4c9f-b182-d76291449829@m73g2000hsh.googlegroups.com> On Jun 24, 3:29?pm, schickb wrote: > I think it would be useful if iterators on sequences had the __index__ > method so that they could be used to slice sequences. I was writing a > class and wanted to return a list iterator to callers. ?I then wanted > to let callers slice from an iterator's position, but that isn't > supported without creating a custom iterator class. > > Are there reasons for not supporting this generally? I realize not all > iterators would have the __index__ method, but that seems ok. > > In Python 3, maybe this could be called a SequenceIterator > > -Brad Could you post an example of what you are talking about? I'm not getting it. In any case, the first step is writing a PEP. http://www.python.org/dev/peps/ Matt From mensanator at aol.com Sat Jun 7 13:24:23 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 7 Jun 2008 10:24:23 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> Message-ID: <0f156f41-3c84-48c4-bfa0-391cf11ce119@c58g2000hsc.googlegroups.com> On Jun 7, 5:21?am, Paul Miller wrote: > On Fri, 06 Jun 2008 18:01:45 -0700, Mensanator wrote: > > What happens if your iterables aren't the same length? > > I chose not to consider that case, That's a bad habit to teach a newbie, isn't it? > since they were the same length in the > original post. ? The issue I'm stressing is HOW they got to be the same size. If I was teaching programming and the OP turned in that example, I would mark him down. Not because he got the answer wrong. Not because he used zip. Not because he failed to use enumerate or itertools. But because he hardcoded the array bounds and THAT'S the lesson the OP should take away from this. > Based on the variable names, it seemed reasonable that > there would always be a 1-to-1 correspondence between > elements of each list. ? Yes, reasonable at the time. But this is Python, not C. Lists can change size under program control, a feature that's extremely useful. But there's a price for that usefulness. Practices that made sense in C (define a constant to set array bounds) aren't transportable over to systems that simply don't have the restrictions that require those practices. > However, if you do > > score_costs = [(base_scores[i], score_costs[i]) for i in range (min (len > (base_scores), len (score_costs))] > > then you get exactly what you would get using zip. ? And if the iterables change size dynamically, you could get either a crash due to index out of range or else silently a wrong answer. > That's one heck of a > long line, though, hence my earlier comment: I have no problem telling the OP this method. But I think you should warn him about potential problems. Surely you didn't intend to leave him to twist in the wind so that he learns a thing or two when his programs crash? > > >> But, I'd rather just use zip. :-) > > > And with zip() you won't get an error, but it won't be correct, either. > > If it doing what zip() does makes sense, then just use zip(). ?Otherwise, > check for the case where the iterables are of different length, and do > the appropriate thing (raise an error, pad the shorter one, whatever). That's all I'm suggesting. Along with pointing out that enumerate or itertools can do this for him. > > -- > code.py: a blog about Python. ?http://pythonista.wordpress.com > ** Posted fromhttp://www.teranews.com** From deets at nospam.web.de Mon Jun 9 18:15:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 10 Jun 2008 00:15:29 +0200 Subject: Question by someone coming from C... In-Reply-To: References: Message-ID: <6b5oc2F38ti2mU1@mid.uni-berlin.de> Skye schrieb: > Writing this app in Python, not sure what the "best practice" would > be. > > I want a bitfield global logging level that allows me to turn specific > debugging modules on and off. If I was doing this in C, I'd just use > some globals like: > > unsigned int debug_level = 0; > #define DEBUG_GENERAL 0x0001 > #define DEBUG_CONFIG 0x0002 > #define DEBUG_OPTIONS 0x0004 > etc etc For debugging - use the module logging. And configure properly. Diez From rcdailey at gmail.com Fri Jun 6 13:31:37 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 6 Jun 2008 12:31:37 -0500 Subject: Where to find Visual Studio Syntax Highlighting (for python)? Message-ID: <496954360806061031y52a1312chce74619442097620@mail.gmail.com> Hi, Does anyone know of a way to get syntax coloring working in Visual Studio 2008 for Python? I did some googling but I couldn't find anything. Help is appreciated, thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From circularfunc at yahoo.se Sun Jun 22 18:32:24 2008 From: circularfunc at yahoo.se (cirfu) Date: Sun, 22 Jun 2008 15:32:24 -0700 (PDT) Subject: listcomprehension, add elements? Message-ID: <13452c64-ef91-49a2-bb73-7f33c088660e@d45g2000hsc.googlegroups.com> [a+b for a,b in zip(xrange(1,51), xrange(50,0,-1))] [51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51] i want to add all the elemtns a s well. can i do this all in a listcomprehension? i can do this ofc: reduce(lambda x,y:x+y,[a+b for a,b in zip(xrange(1,51), xrange(50,0,-1))]) but reduce is a functional way of doing it, what is the more pythonic way of doing this? From kris at FreeBSD.org Tue Jun 24 07:44:49 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Tue, 24 Jun 2008 13:44:49 +0200 Subject: Bit substring search Message-ID: <4860DE31.1040407@FreeBSD.org> I am trying to parse a bit-stream file format (bzip2) that does not have byte-aligned record boundaries, so I need to do efficient matching of bit substrings at arbitrary bit offsets. Is there a package that can do this? This one comes close: http://ilan.schnell-web.net/prog/bitarray/ but it only supports single bit substring match. Kris From nwinters3000 at gmail.com Tue Jun 10 09:47:13 2008 From: nwinters3000 at gmail.com (nwinters3000 at gmail.com) Date: Tue, 10 Jun 2008 06:47:13 -0700 (PDT) Subject: PEP on breaking outer loops with StopIteration References: Message-ID: <98d87e96-3e6e-4b13-acf3-1f7db4409a42@x1g2000prh.googlegroups.com> On Jun 9, 10:50?pm, Dan Bishop wrote: > On Jun 9, 8:07?pm, "Kris Kowal" wrote: > > > I had a thought that might be pepworthy. ?Might we be able to break > > outer loops using an iter-instance specific StopIteration type? > > > You can break out of outer loops now with the proper (ab)use of > exceptions: > > class BreakInner(Exception): > pass > class BreakOuter(Exception): > pass > try: > for letter in string.lowercase: > try: > for number in xrange(10): > print letter, number > if letter == 'a' and number == 5: > raise BreakInner() > if letter == 'b' and number == 5: > raise BreakOuter() > except BreakInner: > pass > except BreakOuter: > pass I prefer having a new function wrapping the inner loop and using both break and return, but this doesn't allow you to "break 1 loop up and 2 loops up", and doesn't help to continue a particular loop further up def innerLoop(letter): for number in xrange(10): print letter, number if letter == 'a' and number == 5: break if letter == 'b' and number == 5: return for letter in string.lowercase: innerLoop(letter) In response to the suggested syntax, I have found occasions where I iterate through the same variable [say searching for duplicates within some tolerance to merge into one item] in an inner loop. I also don't see how it would extend to something like: for evenNumber in [x*2+1 for x in xrange(5)]: print evenNumber From afriere at yahoo.co.uk Tue Jun 24 21:35:58 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 24 Jun 2008 18:35:58 -0700 (PDT) Subject: how to convert '8868' to u'\u8868' References: <5268385d-04c7-4726-ab55-0f729ce8d883@a9g2000prl.googlegroups.com> Message-ID: <5580a767-367b-44c0-8ef4-5c8585ed86cd@a32g2000prf.googlegroups.com> On Jun 25, 11:30 am, CodeHunter wrote: > a = '8868' > b = u'\u8868' > > I want to convert a to b > > who can help me ? > > thank you very much! unicode(a) From hv at tbz-pariv.de Wed Jun 4 05:22:49 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Wed, 04 Jun 2008 11:22:49 +0200 Subject: Image Processing (batch) In-Reply-To: <48454198$0$12642$3b214f66@aconews.univie.ac.at> References: <6akqd5F37rofnU1@mid.individual.net> <48454198$0$12642$3b214f66@aconews.univie.ac.at> Message-ID: <6an58hF37ifogU1@mid.individual.net> Weinhandl Herbert schrieb: > Thomas Guettler schrieb: >> Hi, >> >> I tried PIL for image batch processing. But somehow I don't like it >> - Font-Selection: You need to give the name of the font file. >> - Drawing on an image needs a different object that pasting and saving. >> - The handbook is from Dec. 2006. >> >> What image libraries do you suggest? > > try : > http://photobatch.stani.be/ This is a GUI, my processing needs to be done on the server. I need a library with Python API. photobatch uses PIL, so I think I would not gain much. Does photobatch improve font loading? BTW, the homepage of this project uses frames. The URL does not change, ... you can't send links or bookmark pages. Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From rurpy at yahoo.com Mon Jun 2 19:26:35 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Mon, 2 Jun 2008 16:26:35 -0700 (PDT) Subject: Checking each item in m.group()? References: <2d1b2ac1-3fa1-41c7-a2c2-560c8322b6fb@z72g2000hsb.googlegroups.com> Message-ID: miller.paul.w at gmail.com wrote: > On Jun 2, 5:06 pm, Peter Otten <__pete... at web.de> wrote: > >> You are taking the wrong approach here. >> >> Don't build SQL statements as strings; you are enabling the next SQL >> injection attack. Pass parameters using the DB API instead. >> >> Don't use regular expressions to parse a CSV file. Python's csv module is >> more likely to deal correctly with the quirks of that standard. >> > > I'd like to second both these statements. Regardless of whether these > CSV files are from a trusted source or not, it's a virtual truism of > programming that eventually, any application will be used in ways it > was not intended. Since using a parameterized query is a simple way > to avoid a common security hole, even if such a thing could never be > exploited by the app in its current configuration, you should do > things the Right Way. That way, even if your code is twisted to some > other use in the future, it's less likely to cause problems. I don't have a problem with a response saying "it's a good idea to use parameterized queries and explaining why", but I have seen way too many responses like this which are basically FUD. I'm not sure what a "virtual" truism is, but if it is like a truism, it's not true. There are many cases where one can accurately predict that the code will not be used in the future in some different app. I don't know what the OP was doing, but I have done many data conversion jobs where I have done things similar to the OP. The jobs were one-time, move data from system A to system B (with some munging in between) and I could and did predict the conversion code would not get reused. My accuracy rate is 100%. And if you do reuse code where you feed it untrusted input in a security sensitive context, and you don't bother to verify the security of said, code, you already have so many problems, one more probably won't make much difference. To the OP: The advice to use parameterized queries is good but overstated. There are cases when it is quite safe to use non-parameterized statements: * When you control the data going into the query )e.g., you've generated it yourself). * When the data come from trusted sources (including something like sys.input if the only people with access to the program are trusted). * When you can reliably check the data yourself, for example in: sql = "SELECT * FROM foo WHERE id=%d" % int(some_string) cursor.execute (sql) it doesn't really matter what "some_string" contains (if you are prepared for a Python exception). But note that checking and escaping strings in more general or complicated cases can be quite tricky.) In most cases a good reason to use a parameterized query is that it is no harder than to not use one, so why not and get the additional safety for free? A parameterized query can often run faster than a non-parameterized one since the database can reuse the cached compiled query. (But sometimes the opposite is true, see below). A parameterized form of the above is: sql = "SELECT * FROM foo WHERE id=?" % int(some_string) cursor.execute (sql, int(some_string)) so it is just as easy. There are times though when it is slightly harder. If idnums is an arbitrary list of ints: sql = "SELECT * FROM foo WHERE id IN(%s) % ','.join(idnums) cursor.execute (sql) Using a parameterized query might look like: sql = "SELECT * FROM foo WHERE id IN(%s) % ','.join(['?']*len(idnums)) cursor.execute (sql, idnums) When you have written such code a few times it becomes a natural idiom, but if you only do so occasionally, you are in a hurry, and the conditions above apply, then there is no reason not to go with the first form. And if you you already have a text string of comma-separated digits, the ease of using the direct sql form becomes even greater: sql = "SELECT * FROM foo WHERE id IN(%s) % idnums_string cursor.execute (sql) But of course, if "idnums_strings" came from an untrusted source, then you need to validate it first, e.g.: if idnums_string.strip("0123456789 ,"): then raise Error There are also times when using a parameterized query can dramatically (and I mean two or three *orders of magnitude*) slow down your query when using prepared queries. For example: sql = "SELECT * FROM foo WHERE txt LIKE "%s%%" % some_string cursor.execute (sql) can be expected to run quite quickly in most database systems, since the database knows that the searched for text starts with a constant string and can thus use an index. The parameterized form: sql = "SELECT * FROM foo WHERE txt LIKE ?" cursor.execute (sql, [some_string + "%"]) will often run very very slowly, because when the query is prepared the database has no idea if the argument will start with a constant string of not, and thus can only assume the worst, and prepare the query so that it doesn't use an index. The bottom line is, as in all things, understanding the issues will lead to much better decisions than blindly following some dumbed down advice like, "always use parameterized queries". (And to the OP. if you already know all this, my apologies if I sound like I'm talking down to you, but perhaps other people may benefit. I get tired of reading simplistic "do X, period." responses sometimes.) From wmcbrine at users.sf.net Wed Jun 25 21:13:10 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Thu, 26 Jun 2008 01:13:10 GMT Subject: Newbie question about tuples and list comprehensions References: Message-ID: On Wed, 25 Jun 2008 16:02:52 -0700, John Machin wrote: > Here's one approach (requires Python 2.5 or later): > [(50 if x < 50 else x, 50 if y < 50 else y, 50 if z < 50 else z) for > (x, y, z) in source] [(max(x, 50), max(y, 50), max(z, 50)) for (x, y, z) in source] -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From Lie.1296 at gmail.com Tue Jun 10 19:09:29 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 10 Jun 2008 16:09:29 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> <484ad07b$0$25721$607ed4bc@cv.net> <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> <484b3464$0$25724$607ed4bc@cv.net> <09d98480-c834-42bd-b97f-481133be9cb4@s50g2000hsb.googlegroups.com> <77d2d56a-7ab6-4d33-81d4-b15cc8fc63d6@u36g2000prf.googlegroups.com> Message-ID: On Jun 8, 11:11?pm, Mensanator wrote: > On Jun 8, 4:04?am, Lie wrote: > > > > > On Jun 8, 8:56?am, Mensanator wrote: > > > > On Jun 7, 8:22?pm, John Salerno wrote: > > > > > Mensanator wrote: > > > > > What I DID say was that how the builtins actually > > > > > work should be understood and it APPEARED that the > > > > > OP didn't understand that. Maybe he understood that > > > > > all along but his example betrayed no evidence of > > > > > that understanding. > > > > > Well, the truth is that I know zip truncates to the shorter of the two > > > > arguments, > > > > Ok, sorry I thought otherwise. > > > > > and also in my case the two arguments would always be the > > > > same length. > > > > Yes, because you're controlling the source code. > > > But since lists are mutable, source code literals > > > don't always control the length of the list. > > > Since when source code literals ever control the length of a list? > > Isn't score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] > considered a literal? Yep, but it's not the sole controller of the length of a list. There are other things that might control the length of the list like del, append, etc. > > What controls the length of the list is the semantic meaning of the > > list, > > Wha do you mean by that? The list contains 11 objects. > How could the length be any different? What I meant is in some cases (not all) the list might semantically be nonsense if it is of different length (i.e. it have fixed length). > > in some cases it just makes no sense that the list would ever > > have different length. > > And in such case there won't be any problem, will there? > > Is that a good habit to teach a newbie? To write > code that only works for special cases? I think it is up to the programmer to decide whether special case is enough or a general case is necessary. From roopesh.raj at gmail.com Fri Jun 20 03:37:32 2008 From: roopesh.raj at gmail.com (Roopesh) Date: Fri, 20 Jun 2008 00:37:32 -0700 (PDT) Subject: poplib - retr() getting stuck Message-ID: <3504f6cc-5cb7-4115-8d79-a7a5cd810689@d19g2000prm.googlegroups.com> Hi, I am using poplib's retr() to fetch mails from my gmail account. It works fine, in some cases it gets stuck inside the retr() method and does not come out. >From the logs I could find that when retr() is called, it stops executing further statements, nor does it throw an exceptions but simply stops. My code is roughly like the foll: try: print "1" mymsg = M.retr(msg_no) print "2" except poplib.error_proto, e: print "exception1" except Exception, e: print "exception2" What can be the reason for this? Can anyone help me. Thanks Roopesh From rasmussen.bryan at gmail.com Fri Jun 20 04:15:12 2008 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Fri, 20 Jun 2008 10:15:12 +0200 Subject: don't make it worse! - was Re: SPAM In-Reply-To: <485B5F5F.8070207@gmail.com> References: <88f0c3ba-46e1-4b30-a61d-482e5ecf339a@t12g2000prg.googlegroups.com> <485A0E77.2050009@gmail.com> <485AE162.8050407@gmail.com> <485B5F5F.8070207@gmail.com> Message-ID: <3bb44c6e0806200115g5101faa3jd6e4c253978a7d52@mail.gmail.com> I guess it didn't because I was reading through Google Mail, and it wasn't filtered. Best Regards, Bryan Rasmussen On Fri, Jun 20, 2008 at 9:42 AM, Aspersieman wrote: > Michael Torrie wrote: > > Aspersieman wrote: > > > SPAM > > > Obviously. Please refrain from replying to the SPAM on this list. It > just makes the problem worse. > > Thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list > > > > Errr....Ok. > > I read somewhere that replying to potential spam with 'SPAM' in subject will > add it (the message sender you are replying to) to google's spam filters. > Can't find the link now though. > > Sorry though, if doing this didn't help - or made it worse. :) > > Nicol > > -- > > The three things to remember about Llamas: > 1) They are harmless > 2) They are deadly > 3) They are made of lava, and thus nice to cuddle. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From jeff at jmcneil.net Sat Jun 14 21:55:16 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Sat, 14 Jun 2008 18:55:16 -0700 (PDT) Subject: Socket Programming References: Message-ID: <1dfab813-2491-4d6e-a46f-f3616e9d88f4@f63g2000hsf.googlegroups.com> On Jun 14, 5:38?pm, srinivasan srinivas wrote: > Hi, > Is there any way(method) to find whether the socket got closed or not?? > Thanks, > Srini > > ? ? ? Best Jokes, Best Friends, Best Food and more. Go tohttp://in.promos.yahoo.com/groups/bestofyahoo/ That's slightly difficult to answer without knowing any context. Do you want to know if the other end has closed the connection? Assuming that's the case and you're just using the standard socket library, it's largely the same as it would be should you do it in C. A TCP socket with a closed peer will select as 'ready' for read. When you attempt to read that socket, you'll have a 0 length return. If you attempt to write to a socket that's been closed by the other end, you ought to receive a "Broken pipe' socket error. If you attempt to write to a socket that *you've* already closed, then you should just get a standard 'Bad file descriptor' socket.error. Google's your friend with topics like this. There's a lot out there pertaining to the standard POSIX socket calls. From vlastimil.brom at gmail.com Sun Jun 8 15:37:04 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sun, 8 Jun 2008 21:37:04 +0200 Subject: Need help porting Perl function In-Reply-To: References: Message-ID: <9fdb569a0806081237r1c564c82va52bbfc8202cf862@mail.gmail.com> 2008/6/7, kj : > > > > ... The original Perl function takes a reference to an array, removes > from this array all the elements that satisfy a particular criterion, > > and returns the list consisting of the removed elements. ... > > > > Just out of curiosity, as I didn't find any mention of filter() in the suggestions in this thread, I'd like to ask, whether there are some reasons, why not to use it (or the itertools equivalent); actually it seems to me to be the simplest way to acomplish the mentioned task (as the solutions not modifying the original list were proposed too). e.g.: >>> lst=range(14) >>> odd = filter(lambda x: x % 2, lst) >>> even = filter(lambda x: not x % 2, lst) >>> lst, odd, even (or a version using itertools.ifilter, ifilterfalse) Are there maybe some significant performance disadvantages in the two subsequent implied loops over the input list? Regards, Vlastimil Brom -------------- next part -------------- An HTML attachment was scrubbed... URL: From jphalip at gmail.com Sun Jun 29 09:39:17 2008 From: jphalip at gmail.com (Julien) Date: Sun, 29 Jun 2008 06:39:17 -0700 (PDT) Subject: Unnormalizing normalized path in Windows Message-ID: <2fd61534-2370-452c-8ca2-269ee01ed8e7@r37g2000prm.googlegroups.com> Hi, In Windows, when a path has been normalized with os.path.normpath, you get something like this: C:/temp/my_dir/bla.txt # With forward slashes instead or backward slashes. Is it possible to revert that? >>> magic_function('C:/temp/my_dir/bla.txt') 'C:\temp\my_dir\bla.txt' I wonder if there's a standard function to do that... Thanks a lot! Julien From n.emami at gmail.com Thu Jun 12 08:15:28 2008 From: n.emami at gmail.com (Nader) Date: Thu, 12 Jun 2008 05:15:28 -0700 (PDT) Subject: get keys with the same values References: <7334507d-24e7-43f9-baa3-4e9e87eb20fa@w7g2000hsa.googlegroups.com> Message-ID: On Jun 12, 2:05 pm, Chris wrote: > On Jun 12, 1:48 pm, Nader wrote: > > > > > On Jun 12, 1:35 pm, bearophileH... at lycos.com wrote: > > > > Nader: > > > > > d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} > > > > I will something as : > > > > d.keys(where their values are the same) > > > > That's magic. > > > > > With this statement I can get two lists for this example: > > > > l1= ['a','e'] > > > > l2=['b','d'] > > > > Would somebody tell me how I can do it? > > > > You can create a new dict where the keys are the values of the input > > > dict and the values are a list of the keys of the original dict. So > > > scanning the keys, values of the input dict, you can fill the second > > > dict. Then you can scan the second dict, and create a list that > > > contains only value lists longer than one. > > > > Bye, > > > bearophile > > > Is it niet possible with one or two statement, maybe with list > > comprehension. For exmple: > > > l = [(k,v) for k in d.keys() for v in d.values() | en here we need > > some extra logic (v = 1)] > > > I don;t konw how we can define a logic statement in a list > > comprehension. > > It will be very compact, if it would possible. > > > Nader > > If you are going to use this reverse look-up alot you'd be better off > building another dictionary with the original values being keys and > the original keys being values, if it is used infrequently enough you > can search for it with result_list = [k for k,v in dictionary.items() > if v == search_value] Thank you! It is the anwser which I was looking for. [(k,v) for k,v in d.items() if v is pattern]. But I don't understand what tou mean of "reverse look-up a lot"! I have to read some informations inclusive (latitudes and longitudes) form a file and after some processing to save part of this information to other file. Why do I make a new dictionary? Nader From tamim.shahriar at gmail.com Mon Jun 9 14:07:38 2008 From: tamim.shahriar at gmail.com (subeen) Date: Mon, 9 Jun 2008 11:07:38 -0700 (PDT) Subject: Web Crawler - Python or Perl? References: Message-ID: On Jun 9, 11:48 pm, disappeare... at gmail.com wrote: > Hi all, > I am currently planning to write my own web crawler. I know Python but > not Perl, and I am interested in knowing which of these two are a > better choice given the following scenario: > > 1) I/O issues: my biggest constraint in terms of resource will be > bandwidth throttle neck. > 2) Efficiency issues: The crawlers have to be fast, robust and as > "memory efficient" as possible. I am running all of my crawlers on > cheap pcs with about 500 mb RAM and P3 to P4 processors > 3) Compatibility issues: Most of these crawlers will run on Unix > (FreeBSD), so there should exist a pretty good compiler that can > optimize my code these under the environments. > > What are your opinions? It really doesn't matter whether you use Perl or Python for writing web crawlers. I have used both for writing crawlers. The scenarios you mentioned (I/O issues, Efficiency, Compatibility) don't differ two much for these two languages. Both the languages have fast I/O. You can use urllib2 module and/or beautiful soup for developing crawler in Python. For Perl you can use Mechanize or LWP modules. Both languages have good support for regular expressions. Perl is slightly faster I have heard, though I don't find the difference myself. Both are compatible with *nix. For writing a good crawler, language is not important, it's the technology which is important. regards, Subeen. http://love-python.blogspot.com/ From daveparker at flamingthunder.com Sat Jun 28 13:47:19 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Sat, 28 Jun 2008 10:47:19 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <4847ecf6$0$25178$c3e8da3@news.astraweb.com> Message-ID: <950ba374-e753-40d3-840a-d353ade785d4@a9g2000prl.googlegroups.com> On Jun 7, 10:24 am, Sam Denton wrote: > I've long believed that '=' should be banned from programming languages. > Use '==' for equality tests, and ':=' for assignments. That's an interesting suggestion that I don't recall hearing anyone else ever mention. On Jun 7, 10:24?am, Sam Denton wrote: > John Salerno wrote: > > "Dave Parker" wrote in message > >news:a95c09d9-94c3-4dac-9439-9176038d93d9 at w8g2000prd.googlegroups.com... > > On May 20, 7:05 pm, Collin wrote: > > > --- > > For example, consider the two statements: > > > ? ? ?x = 8 > > ? ? ?x = 10 > > > The reaction from most math teachers (and kids) was "one of those is > > wrong because x can't equal 2 different things at the same time". > > --- > > > Aw, come on. I'm a novice programmer but even after reading the most basic > > of introductions to a programming language I can tell that x is being > > assigned one value, then another. > > I've long believed that '=' should be banned from programming languages. > ? Use '==' for equality tests, and ':=' for assignments.- Hide quoted text - > > - Show quoted text - From exarkun at divmod.com Wed Jun 11 10:13:50 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 11 Jun 2008 10:13:50 -0400 Subject: Producer-consumer threading problem In-Reply-To: Message-ID: <20080611141350.4714.1433994826.divmod.quotient.8137@ohm> On Tue, 10 Jun 2008 22:46:37 -0700 (PDT), George Sakkis wrote: >On Jun 10, 11:47 pm, Larry Bates wrote: >> >> I had a little trouble understanding what exact problem it is that you are >> trying to solve but I'm pretty sure that you can do it with one of two methods: > >Ok, let me try again with a different example: I want to do what can >be easily done with 2.5 Queues using Queue.task_done()/Queue.join() >(see example at http://docs.python.org/lib/QueueObjects.html), but >instead of having to first put all items and then wait until all are >done, get each item as soon as it is done. > >> 1) Write the producer as a generator using yield method that yields a result >> every time it is called (something like os.walk does). I guess you could yield >> None if there wasn't anything to consume to prevent blocking. > >Actually the way items are generated is not part of the problem; it >can be abstracted away as an arbitrary iterable input. As with all >iterables, "there are no more items" is communicated simply by a >StopIteration. > >> 2) Usw somethink like Twisted insted that uses callbacks instead to handle >> multiple asynchronous calls to produce. You could have callbacks that don't do >> anything if there is nothing to consume (sort of null objects I guess). > >Twisted is interesting and very powerful but requires a different way >of thinking about the problem and designing a solution. More to the >point, callbacks often provide a less flexible and simple API than an >iterator that yields results (consumed items). For example, say that >you want to store the results to a dictionary. Using callbacks, you >would have to explicitly synchronize each access to the dictionary >since they may fire independently. This isn't true. Access is synchronized automatically by virtue of the fact that there is no pre-emptive multithreading in operation. This is one of the many advantages of avoiding threads. :) There may be valid arguments against callbacks, but this isn't one of them. Jean-Paul From cslush at gmail.com Fri Jun 27 18:47:16 2008 From: cslush at gmail.com (sleek) Date: Fri, 27 Jun 2008 15:47:16 -0700 (PDT) Subject: Embedded Python Import problem Message-ID: I am having trouble with the following code: PyObject *module = PyImport_ImportModule(modulename); if (module == NULL) { PyObject* et, *ev, *etr; PyErr_Fetch(&et, &ev, &etr); PyObject* traceback = PyImport_ImportModule("traceback"); PyObject* tb = PyObject_CallMethodObjArgs(traceback, PyString_FromString("format_exception"), et, ev, etr, NULL); char *message = PyString_AsString(PyObject_Str(tb)); ... ... } When this code executes, it gets into the "module == NULL" condition. However, when I try to get the exception that occurred, I get the value "" copied into the "char* message" variable. Can anyone shed some light on what might cause this to happen? I thought that if I actually get into that NULL condition that an exception has occurred. From ironfroggy at socialserve.com Mon Jun 16 12:36:08 2008 From: ironfroggy at socialserve.com (Calvin Spealman) Date: Mon, 16 Jun 2008 12:36:08 -0400 Subject: 'string'.strip(chars)-like function that removes from the middle? In-Reply-To: <48569B9E.6030206@admailinc.com> References: <48569B9E.6030206@admailinc.com> Message-ID: <7E4F274D-2139-441D-B641-497B885C6227@socialserve.com> On Jun 16, 2008, at 12:58 PM, Ethan Furman wrote: > Greetings. > > The strip() method of strings works from both ends towards the middle. > Is there a simple, built-in way to remove several characters from a > string no matter their location? (besides .replace() ;) > > For example: > .strip --> 'www.example.com'.strip('cmowz.') > 'example' > .??? --> --- 'www.example.com'.strip('cmowz.') > 'exaple' >>> re.sub('|'.join('cmowz.'), "www.example.com") '.exaple.' > -- > Ethan > > -- > http://mail.python.org/mailman/listinfo/python-list From e.yunak at gmail.com Sat Jun 21 10:29:50 2008 From: e.yunak at gmail.com (Val-Amart) Date: Sat, 21 Jun 2008 07:29:50 -0700 (PDT) Subject: Fast and easy GUI prototyping with Python References: <9c349bf0-ef63-4463-bd4e-cdbe331b58c3@z66g2000hsc.googlegroups.com> Message-ID: On 21 ???, 15:36, ero... at gmail.com wrote: > Which tools would you use? I want the interface design to be as easy > and fast as possible, all ideology aside. I'm considering either > IronPython+Visual Studio or Python+Qt -- but I'm open for other > suggestions. > > Visual Studio seems to offer the easiest solution, but is IronPython > stable enough? How easy is the IronPython/Visual Studi integration? > What about IronPython Studio? Use PyQt. You will gain great portability +all the functionality built in qt. You can try PyGTK also, though i wont recommend it. From aahz at pythoncraft.com Wed Jun 11 15:35:00 2008 From: aahz at pythoncraft.com (Aahz) Date: 11 Jun 2008 12:35:00 -0700 Subject: Producer-consumer threading problem References: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> Message-ID: In article <1f8adb7a-1257-4a56-b69a-557115c60050 at k37g2000hsf.googlegroups.com>, George Sakkis wrote: > >I'd like some feedback on a solution to a variant of the producer- >consumer problem. My first few attempts turned out to deadlock >occasionally; this one seems to be deadlock-free so far but I can't >tell if it's provably correct, and if so, whether it can be >simplified. Take a look at the threading tutorial on my web page, specifically the threadpool spider. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From eckhardt at satorlaser.com Wed Jun 4 03:48:01 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 04 Jun 2008 09:48:01 +0200 Subject: Best way to modify code without breaking stuff. References: Message-ID: Jesse Aldridge wrote: > I've got a module that I use regularly. I want to make some extensive > changes to this module but I want all of the programs that depend on > the module to keep working while I'm making my changes. What's the > best way to accomplish this? You simply run the module's unit tests that tell you if the new module's behaviour differs from the expectations. If you don't have unit tests, I'd say it's about time writing them. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From bruno.42.desthuilliers at websiteburo.invalid Fri Jun 6 11:25:04 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 06 Jun 2008 17:25:04 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <4847d39d$0$7614$426a74cc@news.free.fr> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> Message-ID: <48495693$0$26543$426a74cc@news.free.fr> Russ P. a ?crit : > On Jun 5, 4:53 am, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> Russ P. a ?crit : > >> Given your very recent discovery of what 'dynamic' *really* means in >> Python (like, for exemple, dynamically adding / replacing attributes - >> including methods - on a per-class or per-instance basis), possibly, yes. > > My "very recent" discovery? Funny, I thought I knew that several years > ago. Looks like I mistook your """ I also realize, by the way, that Python allows a client of a class to define a new class member from completely outside the class definition """ as "I just realized (...)" Sorry for having read too fast. >>> I also realize, by the way, that Python allows a client of a class to >>> define a new class member from completely outside the class >>> definition. Obviously, that cannot be declared private. >> Why so ? > > Why should the client of a class not be able to declare a *private* > member of the class? You're kidding, right? I'm dead serious. I often add implementation attributes to either a class or an instance. These *are* implementation parts, not API. > Do you mind if I tell you > how to arrange the furniture in your bedroom? I must be a bit dumb, but I don't see how human interaction problems relate to enforced access restriction in an OO programming language. >>> But if the >>> same identifier is already declared private within the class, than the >>> new definition should not be allowed (because it would defeat the >>> whole idea of "private" class members). >> Why so ? >> >> Metaprogramming (including monkeypatching) is part of the pythoneer's >> toolbox, and while it's not something to use without pretty good >> reasons, it has many times proven to be a real life saver. In languages >> not allowing it, the solutions to the class of problems easily solved by >> monkeypatching happens to be at best a kludge, at worst plain >> unsolvable, at least without too much effort to be even worth it. Your >> above proposition would arbitrarily make possible and useful things >> either uselessly complicated or near impossible. > > For the record, I have made it abundantly clear that I don't think > Python should not have as rigorous an encapsulation regime as C++ or > Java. The worst that could happen with my proposition is that you > would need to use a "mangled" name to access private data or methods. That's already the case - when you use __name_mangling. And if there's no effective access restriction, then what the point of having this 'priv' keyword ? > But you will be using the name many times, you can reassign your own > name, of course, so the mangled name need not appear more than once > where it is needed. Once again, I just don't see the point. Either you want effective access restriction in Python, or you don't. And if you don't, what would this 'priv' keyword be useful to ? From space.captain.face at gmail.com Sat Jun 7 10:14:53 2008 From: space.captain.face at gmail.com (Kalibr) Date: Sat, 7 Jun 2008 07:14:53 -0700 (PDT) Subject: Dynamically naming objects. References: <8a99c3fa-1eeb-49b3-a714-b6063ec1daab@d19g2000prm.googlegroups.com> <3d2a85b2-255d-4e93-8cfb-e2772f57b69a@u6g2000prc.googlegroups.com> Message-ID: Thanks for all this info. I'll try all your scripts out. from what you guys have said, I did the following: I set up a 'computer class' (I'lm leaving out the mutators) class computer: def __init__(self, IP, owner, ph_connections, connections): assert isIP(IP) == True self.IP = IP self.owner = owner for i in ph_connections: assert isIP(i) == True self.ph_connections = ph_connections for i in connections: assert isIP(i) == True self.connections = connections isIP(IP) is a function that checks if it looks like an IP based on some rules. Anyway.... I set up a list of users, each with their computer object named after them, so: users = ['Kal', 'Noob', 'Fred'] I ran through them with some code based vaguely on what you guys have said: for i in users: i = computer('', i, [], []) I set up the ph_connections and connections lists as empty for ease of use. Does this code seem right? I can't get it to work. From Gilles at Mon Jun 2 14:42:16 2008 From: Gilles at (nospam@nospam.com) Date: Mon, 02 Jun 2008 20:42:16 +0200 Subject: [Re] Checking each item in m.group()? Message-ID: Hello I need to go through each line of a CSV file, and extract some fields using a regex. Then, I need to check each retrieved field, and if it looks like "", turn this into NULL so that it's correct SQL. I tried a few things, but still can't it working: ======== #Second field might be empty -> "" #"Col1","" #"Col1","Col2" p = re.compile('^"(.+?)","(.*?)"$') for line in textlines: m = p.search(line) if m: #Check each column : if '', then turn into NULL """ for col in line: if col == "": col = "NULL" """ """ for col in m.group(): if col == "": col="NULL" """ """ for col in m.group(0): if col == "": col="NULL" """ """ for i in range (0,len(line)): if line[i] == "": line[i]="NULL" """ """ for i in range(1,len(m.group(0))): if m.group(i) == "": m.group(i)="NULL" """ sql = "INSERT INTO mytable (col1, col2) VALUES ('%s','%s')" % (m.group(1),m.group(2)) print sql f.close() ======== Does someone know the correct syntax? Thank you. From soltys at noabuse.com Fri Jun 20 04:20:13 2008 From: soltys at noabuse.com (Soltys) Date: Fri, 20 Jun 2008 10:20:13 +0200 Subject: Regular expression In-Reply-To: References: <42396af0-29aa-45ea-8588-186b0ccbab58@z16g2000prn.googlegroups.com> Message-ID: Duncan Booth pisze: > Sallu wrote: >> string = 'rich?' > ... >> unicode(string)).encode('ASCII', 'ignore') > ... >> Output : >> >> sys:1: DeprecationWarning: Non-ASCII character '\xc3' in file regu.py >> on line 4, but no encoding declared; see >> http://www.python.org/peps/pep-0263.html for details >> rich? >> Traceback (most recent call last): >> File "regu.py", line 13, in ? >> msg=strip_accents(string) >> File "regu.py", line 10, in strip_accents >> return unicodedata.normalize('NFKD', >> unicode(string)).encode('ASCII', 'ignore') >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position >> 4: ordinal not in range(128) >> >> > The problem is the expression: unicode(string) which is equivalent to > saying string.decode('ascii') > > The string contains a non-ascii character so the decode fails. You should > specify whatever encoding you used for the source file. From the error > message it looks like you used utf-8, so "string.decode('utf-8')" should > give you a unicode string to work with. > > Or just specify source encoding like that: #!/usr/bin/python # -*- coding: utf-8 -*- or #!/usr/bin/python # coding=utf-8 -- Soltys "Free software is a matter of liberty not price" From seandavi at gmail.com Wed Jun 11 17:20:52 2008 From: seandavi at gmail.com (Sean Davis) Date: Wed, 11 Jun 2008 14:20:52 -0700 (PDT) Subject: Numpy array to gzip file References: <404de0ba-edd5-47ff-8b25-132aa0b5b570@c58g2000hsc.googlegroups.com> Message-ID: On Jun 11, 12:42 pm, "drobi... at gmail.com" wrote: > On Jun 11, 9:17 am, Sean Davis wrote: > > > > > I have a set of numpy arrays which I would like to save to a gzip > > file. Here is an example without gzip: > > > b=numpy.ones(1000000,dtype=numpy.uint8) > > a=numpy.zeros(1000000,dtype=numpy.uint8) > > fd = file('test.dat','wb') > > a.tofile(fd) > > b.tofile(fd) > > fd.close() > > > This works fine. However, this does not: > > > fd = gzip.open('test.dat','wb') > > a.tofile(fd) > > > Traceback (most recent call last): > > File "", line 1, in > > IOError: first argument must be a string or open file > > > In the bigger picture, I want to be able to write multiple numpy > > arrays with some metadata to a binary file for very fast reading, and > > these arrays are pretty compressible (strings of small integers), so I > > can probably benefit in speed and file size by gzipping. > > > Thanks, > > Sean > > Use > fd.write(a) That seems to work fine. Just to add to the answer a bit, one can then use: b=numpy.frombuffer(fd.read(),dtype=numpy.uint8) to get the array back as a numpy uint8 array. Thanks for the help. Sean From duncan.booth at invalid.invalid Fri Jun 20 08:07:18 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Jun 2008 12:07:18 GMT Subject: Simple Python class questions References: Message-ID: John Dann wrote: > Yes I was wondering about that, but I wasn't clear about when 'body' > code (ie not contained within a def block) in the module might run > under Python. So it seemed to be safer to place the import statement > inside the 'constructor' to get the earliest warning of non-visibility > of pyserial. But you seem to be implying that the body code will run > when the class is instantiated - have I understood that right? It > surely doesn't run when the module containing the class is imported > into the main module - does it?? It would certainly make life easier > to place the import in the body of the module. Python starts executing at the top of your main script and then proceeds line by line down until it falls off the bottom. Various things can divert it from this straightforward progression towards the end of the script, some of them such as if/for/while/raise or function calls are obvious, but the less obvious ones include: import somemodule (or 'from somemodule import something') if 'somemodule' has not previously been imported this will find the module and execute the lines of code in the module from top to bottom just as for the main script. When it falls off the bottom of the module it returns to the import statement, assigns the module or the imported attributes to a name or names in the calling namespace (yes, an import is just a highly specialised assignment statement), and then continues with the next statement. If somemodule has already started being imported anywhere in the program then the import simply returns immediately and does the assignment. (This can be a cause of confusion if you try to import modules recursively as it is perfectly possible that the imported module has not yet finished executing, so it may not yet have all the classes and functions you expect). class somename(bases): somecode A 'class' statement in Python is just executable code. The body of the class is executed from top to bottom but in a new namespace. When execution falls off the bottom of the class body a new class object is created from that namespace and the base classes. The new class object is then assigned to 'somename' (i.e. a class statement is a specialised assignment statement). Then execution then procedes with the next statement. def functionname(arg1, arg2=default): somecode A 'def' statement in Python is also a specialised assignment statement: unlike 'class' it doesn't immediately execute the code in the body, but it does evaluate any default argument values when it encounters the 'def'. Then it creates a new function object from the code in the body and the default arguments (and a few other things such as the argument specification and the function name). Then it continues with the next statement. global name The 'global' statement is not executed at runtime. It is the only Python statement which is purely compile time. Once you understand this it should be much clearer: everything except global is executed when it is encountered following the normal rules for program flow, and all the ways of creating module, classes, and functions simply execute some code and then do an assignment (and so if you wish you can later overwrite the values they assigned). If you wish to do something special when an import fails then you simply put try:..except: around the import at the top level in a module and handle it there: you don't need to put either the import or the handler inside a function. -- Duncan Booth http://kupuguy.blogspot.com From nick at craig-wood.com Mon Jun 2 12:30:22 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 02 Jun 2008 11:30:22 -0500 Subject: ctypes, function pointers and a lot of trouble References: Message-ID: Matt wrote: > class MemStreamData(Structure): > _fields_ = [("mode", c_byte), > ("lPos", c_uint), > ("dwVisibleSize", c_uint), > ("dwBufferSize", c_uint), > ("cpBuffer", POINTER(c_char))] > > class FilStreamData (Structure): > _fields_ = [("szFileName", c_char * 30), > ("hFile", c_uint)] > > > > and the code to fill all that with the right data is the following: > > > datainfo = cdReleaseImageInfo() > > databuf = c_char * 100000 > cbuffer=MemStreamData() > cbuffer.mode = c_byte(0) > cbuffer.lPos = c_uint(0) > cbuffer.dwVisibleSize = c_uint(100000) > cbuffer.dwBufferSize = c_uint(100000) > > #this line does not work, wrong datatype!? > cbuffer.cpBuffer = POINTER(databuf) [snip] > Does anyone see where the errors are? databuf = c_char * 100000 Is a type not an instance... You need to instantiate it, eg >>> from ctypes import * >>> class MemStreamData(Structure): ... _fields_ = [("cpBuffer", POINTER(c_char))] ... >>> cbuffer=MemStreamData() >>> databuf = c_char * 100000 >>> cbuffer.cpBuffer = POINTER(databuf) Traceback (most recent call last): File "", line 1, in TypeError: expected LP_c_char instance, got _ctypes.PointerType >>> databuftype = c_char * 100000 >>> databuf = databuftype() >>> cbuffer.cpBuffer = databuf >>> databuf <__main__.c_char_Array_100000 object at 0xb7d04dac> There is a shorthand for exactly this though as it is a common operation >>> databuf = create_string_buffer(1000) >>> cbuffer.cpBuffer = databuf >>> databuf -- Nick Craig-Wood -- http://www.craig-wood.com/nick From tjreedy at udel.edu Wed Jun 18 01:32:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 18 Jun 2008 01:32:28 -0400 Subject: Does '!=' equivelent to 'is not' In-Reply-To: References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> <20080617120941.GE7349@dragontoe.org> Message-ID: >> Saying a flat "no" alone, without qualifying your statement is >> generally interpreted as rude in English... It's kind of like how you >> talk to children when they're too young to understand the explanation. >> Yucky. > > I didn't meant to be rude at all - and I apologize to Mr. Lie. The > explanation for such strong "No" was in the paragraph below it (the idea > was to say: "No to this, yes to that") As a very much native English speaker I disagree that 'No' is necessarily rude. I wish I could more often get such a clean answer to my questions from my child. From floydophone at gmail.com Tue Jun 10 11:06:29 2008 From: floydophone at gmail.com (Peter Hunt) Date: Tue, 10 Jun 2008 08:06:29 -0700 (PDT) Subject: Dumb idea? Message-ID: Hi everyone - I like playing around with language syntax and semantics. I'm thinking about pulling down the PyPy code and messing around to see what I can accomplish. My first idea is most succinctly described by example: class IBlockProtocol: def __block__(self, func): # NO RETURN VALUES! pass # my_IBlockProtocol is an expression that evaluates to an implementor of IBlockProtocol my_IBlockProtocol: expr # becomes: my_IBlockProtocol.__block__(lambda: expr) ### my_IBlockProtocol: expr # becomes: my_IBlockProtocol.__block__(lambda param1, paramN: expr) ### my_IBlockProtocol: stmt1 stmt2 # becomes: def anon(): stmt1 stmt2 my_IBlockProtocol.__block__(anon) ### my_IBlockProtocol: stmt1 stmt2 # becomes: def anon(param1, paramN): stmt1 stmt2 my_IBlockProtocol.__block__(anon) ############### Has this already been done? Is it a stupid idea? I think it could be used to simplify event handling and some Twisted stuff. I'm mainly looking for reasons why I _wouldn't_ want to take the time to get my hands dirty with the PyPy code (or even CPython) and try to implement this syntax. Thanks. Pete From gh at ghaering.de Thu Jun 26 07:31:40 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 26 Jun 2008 13:31:40 +0200 Subject: extend getattr() In-Reply-To: <0d1da457-b026-4e38-824b-c8cbde172bf7@m36g2000hse.googlegroups.com> References: <0d1da457-b026-4e38-824b-c8cbde172bf7@m36g2000hse.googlegroups.com> Message-ID: Rotlaus wrote: > Hello, > > lets assume i have some classes: > [...] > > a=A() > c=getattr(a, 'b.c') > > I know this doesn't work, but what can i do to get this or a similar > functionality to get it work for this sample and for even more nested > classes? Just recursively apply the getattr(), like this: class A(object): def __init__(self): self.b = B() class B(object): def __init__(self): self.c = C() class C(object): def __init__(self): pass def ext_getattr(obj, attr): for subattr in attr.split("."): obj = getattr(obj, subattr) return obj a=A() c = ext_getattr(a, 'b.c') -- Gerhard From news at prodata.co.uk Thu Jun 19 09:13:39 2008 From: news at prodata.co.uk (John Dann) Date: Thu, 19 Jun 2008 14:13:39 +0100 Subject: Simple Python class questions References: Message-ID: Many thanks for the speedy replies. On Thu, 19 Jun 2008 14:14:02 +0200, C?dric Lucantis wrote: >Le Thursday 19 June 2008 13:54:03 John Dann, vous avez ?crit?: >> Let's say I define the class in a module called comms.py. The class >> isn't really going to inherit from any other class (except presumably >> in the most primitive base-class sense, which is presumably automatic >> and implicit in using the class keyword). > >No it's not :) It is recommended to always use new-style classes, and thus to >give the object base explicitely : > >class serial_link (object) : > ... Can I just confirm: between the parentheses should be the literal 'object' - ie (object) - you're not just using 'object' as a placeholder where there should be a more specific class name or object? -------------- On Thu, 19 Jun 2008 14:21:46 +0200, Ulrich Eckhardt wrote: >Stop, this can't work. Other than VB, Python actually is case sensitive, so >you must write 'try' and not 'Try' and also 'import' and not 'Import'. >Further, many (all?) statements that cause an indention are usually >terminated with a colon, so like with 'class ..:' and 'def ..:' you also >must use 'try:' and not just 'try'. Fix all these and try again, I guess >this will already help a lot. Sorry - the original code was syntactically correct - I just re-keyed it rather quickly for the original newsgroup post here, rather than copy/paste a larger chunk. I'll try to be more careful with any future posts. >One more thing: you are abusing exceptions. Typically, in such a short >program you only have one try-except pair in the main entry function and >all other code only throws the exceptions. In particular the __init__ >function of a class should always signal errors using exceptions. However, >this is not a strict yes/no question but rather a stylistic one. Thanks - I need to think more clearly about the best way of doing this. JGD From bruno.desthuilliers at gmail.com Sat Jun 14 16:17:43 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sat, 14 Jun 2008 13:17:43 -0700 (PDT) Subject: Comments on my first script? References: <7e3a7c92-6204-46dd-8df8-90218f2fb314@26g2000hsk.googlegroups.com> <48522d35$0$10417$426a74cc@news.free.fr> <2c362bb8-7b56-4c41-b8a9-0b36b4f51203@q27g2000prf.googlegroups.com> Message-ID: On 13 juin, 17:24, Lie wrote: > On Jun 13, 3:19 pm, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: > > Phillip B Oldham a ?crit : > (snip) > > > try: > > > for line in rec.split("\n"): > > > bits = line.split(': ') > > > a = bits.pop(0) > > > b = bits.pop(0) > > > if you expect only one ': ', then: > > a, b = line.split(': ') > > > if you can have many but don't care about the others: > > bits = line.split(': ') > > a, b = bits[0], bits[1] > > or: > a, b = line.split(': ')[:1] > ValueError: need more than 1 value to unpack You probably meant: a, b = line.split(': ')[:2] From nir1408 at gmail.com Fri Jun 6 23:35:40 2008 From: nir1408 at gmail.com (Nir) Date: Fri, 6 Jun 2008 20:35:40 -0700 (PDT) Subject: Cannot use Winpdb (or PyDev) to trace embedded Python script in MSVC++ application - ImportError: No module named _socket References: <8a739206-1f72-47ee-8a9f-50ec2c91bde2@j33g2000pri.googlegroups.com> <82989ee9-f9ce-4a88-84b8-c5a0fa2e784e@t12g2000prg.googlegroups.com> <12599118-73c9-45af-94fc-5a791713445d@v1g2000pra.googlegroups.com> Message-ID: <11bfa01e-16d5-4bfb-8bbf-80d66742f3eb@p39g2000prm.googlegroups.com> Can you check another hypothesis? I currently do not have a Python installation to verify this but if my memory does not fail me there is a DLL library somewhere under c: \python25 and _socket might be there as well. Copy any DLLs you find there to the same folder as your embedded interpreter DLL and see if the problem is resolved. Nir On Jun 6, 11:25 am, Chris8B... at gmail.com wrote: > On Jun 6, 1:13 am, Nir wrote: > > > > > You seem to be having a problem with the import path of the embedded > > interpreter. I suppose the embedded interpreter includes some modules > > in a particular folder and _socket is not one of them. For the sake of > > debugging try adding the c:\python25\lib path to the sys.path variable > > of the interpreter before attempting to import rpdb2. > > > Does this work? > > > Nir > > > On Jun 5, 2:52 pm, Chris8B... at gmail.com wrote: > > > > I am embedding Python in a MSVC++ (2005) application. The application > > > creates some environment and then launches a Python script that will > > > call some functions exported from the MSVC++ application. > > > > I want to be able to debug the Python script by using a debug server, > > > likeWinpdb(winpdb.org). > > > > I use ActivePython 2.5.2.2, Microsoft Visual Studio 2005, andWinpdb > > > 1.3.8. > > > > When I launch a script like "e:>python test.py" everything is O'K and > > > I can useWinpdbto trace/debug. > > > > When I run the same script from the MSVC++ application, there is > > > always a complain "ImportError: No module named _socket". > > > > Here is the basic test script I use: > > > > def Process( something ): > > > print "\n\nStarted debugging\n=================\n" > > > #pydevd.settrace() > > > import rpdb2; rpdb2.start_embedded_debugger("1") > > > print "\n\nStopped debugging\n=================\n" > > > > if __name__ == '__main__': > > > Process( "test" ) > > > <<< > > > > In the MSVC++ application I tried many approaches, as suggested by > > > many people, and all of them work to launch the script, but none of > > > them works withWinpdb(or PyDev for Eclipse - same problem). Just for > > > completeness - here is one: > > > > PyRun_SimpleString("import sys"); > > > PyRun_SimpleString("import os"); > > > PyRun_SimpleString( "fullpath = os.path.abspath(\"E:/Test.py\")" ); > > > PyRun_SimpleString( "g = globals().copy()" ); > > > PyRun_SimpleString( "g['__file__'] = fullpath"); > > > PyRun_SimpleString( "execfile(fullpath, g) "); > > > <<< > > > > If I use pdb (import pdb + pdb.runcall(something) ) everything works > > > fine, but I need the performance and convinience ofWinpdb. > > > > What am I doing wrong? > > > > Your help is highly appreciated! > > > > Best regards, > > > Chris > > Nir, > > > Does this work? > > Unfortunately, not. > > I did some experiments to check the sys.path hypothesis: > > - In my MSVC++ application I did PyRun_SimpleString("import cgi"); - > it complained about missing _socket. > > - Did PyRun_SimpleString("print sys.path") to get the sys.path as seen > from within the application environment (that does not find _socket) > > - Did the same in "test.py" and ran ...>Python test.py to get the > sys.path for the environment that _does_ find _socket > > - Compared the two - the working environment had two more paths: > > C:\\WINDOWS\\system32\\python25.zip > C:\\Python25\\lib\\plat-win > > - Added the missing path to the embedded environment: > > PyRun_SimpleString("import sys"); > PyRun_SimpleString("import os"); > > PyRun_SimpleString("sys.path.append(\"C:\\WINDOWS\\system32\ > \python25.zip\")"); > PyRun_SimpleString("sys.path.append(\"C:\\Python25\\lib\\plat-win > \")"); > > PyRun_SimpleString("print sys.path"); > > PyRun_SimpleString("import cgi"); > > Not all paths that are in the working environment are present in the > embedded environment, but still there is a problem: > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\Lib\cgi.py", line 40, in > import urllib > File "c:\Python25\lib\urllib.py", line 26, in > import socket > File "c:\Python25\lib\socket.py", line 45, in > import _socket > ImportError: No module named _socket > > Chris From mark.m.mcmahon at gmail.com Wed Jun 4 19:36:54 2008 From: mark.m.mcmahon at gmail.com (Mark) Date: Wed, 4 Jun 2008 16:36:54 -0700 (PDT) Subject: how should i use this function? References: <99ed3c04-bd62-4456-ae12-eca4179005dc@r66g2000hsg.googlegroups.com> <5a09fa94-b3ce-4a13-af42-b9a1e6980900@25g2000hsx.googlegroups.com> <7573acc5-8b66-45ff-8561-e62200b02446@s50g2000hsb.googlegroups.com> Message-ID: <0cc27c08-77ad-4f24-9bed-2e719405a564@34g2000hsf.googlegroups.com> On Jun 4, 6:58 pm, Gandalf wrote: > > > > But I pywin32 use it all the time i havepywinauto > As the author of pywinauto - I can safely say that just because you have and use pywinauto does NOT mean you have pywin32. pywin32 is not needed for pywinauto. (it uses ctypes to access what it needs). You might find that there are more people who can help you at http://clearspace.openqa.org/community/pywinauto/pywinauto_users (though I do not give the best support in the world - so messages have sat there for a while unanswered!) Thanks Mark From maric at aristote.info Mon Jun 23 04:39:48 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 23 Jun 2008 10:39:48 +0200 Subject: An idiom for code generation with exec In-Reply-To: <485f4f35$0$28417$426a74cc@news.free.fr> References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485f4f35$0$28417$426a74cc@news.free.fr> Message-ID: <200806231039.50348.maric@aristote.info> Le Monday 23 June 2008 09:22:29 Bruno Desthuilliers, vous avez ?crit?: > > With some help from the guys at IRC I came to realize your way doesn't > > do the same. It creates a function that, when called, creates 'foo' on > > globals(). This is not exactly what I need. > > I possibly messed up a couple things in the arguments, flags etc - I > very seldom use compile() and function(). The point was that ?it didn't > require any extra step. In the argument list of function type, the code object in first place is expected to be created directly (no exec - eval) with the python type 'code' (either found as types.CodeType or new.code). In [24]: types.CodeType? Type: type Base Class: String Form: Namespace: Interactive Docstring: code(argcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, lnotab[, freevars[, cellvars]]) Create a code object. Not for the faint of heart. ^^^^^^^^^^^^^^^ Even if it looks more "object oriented", I'm not sure it's actually the good solution for the original problem. I think these interface are not a replacement for the quick eval-exec idiom but more intended to make massive code generation programs object oriented and closer to python internals. AFAIK, the only use case I see code generation (eval - exec, playing with code objects) as legitime in python is in programs that actually do code generation, that is, parse and compile code from textual inputs (application buillders). If code generation is not the best, and I fail to see any performance issue that could explain such a choice, except a misunderstanding of what "compilation" means in python, just don't use it, use closures or callable instances, there are many way to achieve this. -- _____________ Maric Michaud From gabriela.soares.fcup at gmail.com Wed Jun 11 11:18:55 2008 From: gabriela.soares.fcup at gmail.com (Gabriela Soares) Date: Wed, 11 Jun 2008 16:18:55 +0100 Subject: [Tutor] python gui In-Reply-To: <333efb450806110818g134b930cj6e36f7bd79a9083@mail.gmail.com> References: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> <333efb450806110818g134b930cj6e36f7bd79a9083@mail.gmail.com> Message-ID: <9d68e4e90806110818q18c57bd2v8b3219de9b2a1ca1@mail.gmail.com> How ? Any references ? On Wed, Jun 11, 2008 at 4:18 PM, W W wrote: > On Wed, Jun 11, 2008 at 8:03 AM, Gabriela Soares > wrote: > > Greetings, > > > > I want to make a dynamic dashboard, something like: > > > > http://examples.adobe.com/flex3/labs/dashboard/main.html# > > > > but using python. Is it possible ? > > Yes. > > -Wayne > -- Gabriela Soares "I learned that courage was not the absence of fear, but the triumph over it. The brave man is not he who does not feel afraid, but he who conquers that fear." Nelson Mandela -------------- next part -------------- An HTML attachment was scrubbed... URL: From basti.wiesner at gmx.net Tue Jun 17 13:24:06 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Tue, 17 Jun 2008 19:24:06 +0200 Subject: Context manager for files vs garbage collection References: <74f25d98-a6a5-4034-b3b7-06a8ca40ce04@e39g2000hsf.googlegroups.com> Message-ID: Floris Bruynooghe : > I was wondering when it was worthwil to use context managers for > file. Consider this example: > > def foo(): > t = False > for line in file('/tmp/foo'): > if line.startswith('bar'): > t = True > break > return t Using this code inside a jthon web application might hit the resource limits of the underlying operating system. While CPython has a fairly deterministic garbage collector, the JVM gc is non-deterministic, especially inside the server vm. It keeps objects around for quite a long time and only frees them, if available memory runs low or the application is idle. Since file objects don't consume much memory, they might be hanging around for quite some time still claiming resources, which are a rare thing on many restricted server environments. Relying on garbage collection on Python means relying on a non-portable implementation detail. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From pfreixes at gmail.com Thu Jun 26 07:01:22 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Thu, 26 Jun 2008 13:01:22 +0200 Subject: Threads, GIL and re.match() performance In-Reply-To: References: <25be11e7-157c-4af0-be3a-fa7a6c9c3acc@m3g2000hsc.googlegroups.com> <207312b70806260020j6a4c5d4dt3af0625c27ec3cc2@mail.gmail.com> Message-ID: <207312b70806260401j1b2770d9s8b7cc2b7bd3f3190@mail.gmail.com> Hi Ok, if I understand between Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS is not possible use a C/Python api functions ? Sorry, but when thread enter another time with Py_END_ALLOW_THREADS this thread enter to competition to lock GIL ? Thks Thks On Thu, Jun 26, 2008 at 12:16 PM, Matthieu Brucher < matthieu.brucher at gmail.com> wrote: > Hi, > > The C-API uses references counts as well, so it is not threadsafe. > > Matthieu > > 2008/6/26 Pau Freixes : > > But Python C-API[1] it's the main base for extent python with C/c++, and > > this is not not threadsafe.? I dont understand > > > > [1] http://docs.python.org/api/api.html > > > > On Thu, Jun 26, 2008 at 4:49 AM, Benjamin > > wrote: > >> > >> On Jun 25, 9:05 am, Mirko Dziadzka wrote: > >> > > >> > 1) Is there a reason for this? > >> > >> I think it is because the Python re library uses the Python C-API > >> which is not threadsafe. > >> > 2) Is the regex library not thread-safe? > >> > 3) Is it possible, to release the GIL in re.match() to > >> > get more performance? > >> > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > > > > > > > > -- > > Pau Freixes > > Linux GNU/User > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > French PhD student > Website : http://matthieu-brucher.developpez.com/ > Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 > LinkedIn : http://www.linkedin.com/in/matthieubrucher > -- > http://mail.python.org/mailman/listinfo/python-list > -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From manlio_perilloNO at SPAMlibero.it Sun Jun 29 07:30:59 2008 From: manlio_perilloNO at SPAMlibero.it (Manlio Perillo) Date: Sun, 29 Jun 2008 11:30:59 GMT Subject: problem with internationalized headers in email package Message-ID: Hi. >From RFC 2047: + An 'encoded-word' MUST NOT appear in any portion of an 'addr-spec'. + An 'encoded-word' MUST NOT appear within a 'quoted-string'. + An 'encoded-word' MUST NOT be used in a Received header field. + An 'encoded-word' MUST NOT be used in parameter of a MIME Content-Type or Content-Disposition field, or in any structured field body except within a 'comment' or 'phrase'. However (Python 2.5.2): >>> h = Header(u'Andr? ') >>> h.encode() '=?utf-8?b?QW5kcsOoIDxhbmRyZUBsb2NhbGhvc3Q+?=' I'm not sure if this can be considered a bug, but surely this is an invalid header. Thanks Manlio Perillo From bearophileHUGS at lycos.com Mon Jun 16 19:12:03 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 16 Jun 2008 16:12:03 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <4856e80c$0$30401$9b622d9e@news.freenet.de> Message-ID: <2d1e9b84-3dc7-4822-9c61-73991a527c67@s50g2000hsb.googlegroups.com> Martin v. L.: > For this API, I think it's important to make some performance guarantees. I may appreciate them for all Python collections :-) > It seems fairly difficult to make byindex O(1), and > simultaneously also make insertion/deletion better than O(n). It may be possible to make both of them O(log n), but I may appreciate byindex O(n) and insertion/deletion O(1). Bye, bearophile From deets at nospam.web.de Tue Jun 10 02:51:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 10 Jun 2008 08:51:00 +0200 Subject: PEP on breaking outer loops with StopIteration In-Reply-To: References: Message-ID: <6b6mimF3a25g4U1@mid.uni-berlin.de> Kris Kowal schrieb: > I had a thought that might be pepworthy. Might we be able to break > outer loops using an iter-instance specific StopIteration type? > > This is the desired, if not desirable, syntax:: > > import string > letters = iter(string.lowercase) > for letter in letters: > for number in range(10): > print letter, number > if letter == 'a' and number == 5: > raise StopIteration() > if letter == 'b' and number == 5: > raise letters.StopIteration() > > The first StopIteration would halt the inner loop. The second > StopIteration would halt the outer loop. The inner for-loop would > note that the letters.StopIteration instance is specifically targeted > at another iteration and raise it back up. For the record: I share GvR's opinion on the general usefulness. Additionally, your syntax is impossible. There isn't always a containing variable for the iterable. And if you meant "letter", it's ambigous. It is perfectly legal in python to do this: class Foo(object): StopIteration = StopIteration for letter in [Foo(), Foo()]: for number in range(10): raise letter.StopIteration Diez From wmcbrine at users.sf.net Thu Jun 12 04:04:52 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Thu, 12 Jun 2008 08:04:52 GMT Subject: Converting a simple python script to a simple windows executable References: Message-ID: On Wed, 11 Jun 2008 12:25:29 -0700, geoffbache wrote: > (1) py2exe. This is really for when python isn't installed on the remote > user's machine, so it requires you to distribute a large amount of DLLs > etc which are part of the python installation. A bit silly when I know > that the remote user has python anyway. If you know the target user has Python installed, why don't you just distribute the .pyw file? (Use ".pyw" instead of ".py" to avoid the extra console window.) -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From ggpolo at gmail.com Fri Jun 20 12:41:35 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Fri, 20 Jun 2008 13:41:35 -0300 Subject: Tkinter canvas drag/drop obstacle In-Reply-To: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> References: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> Message-ID: On Fri, Jun 20, 2008 at 1:11 PM, Peter Pearson wrote: > Tkinter makes it very easy to drag jpeg images around on a > canvas, but I would like to have a "target" change color when > the cursor dragging an image passes over it. I seem to be > blocked by the fact that the callbacks that might tell the > target that the mouse has entered it (, , > even ) aren't called if the mouse's button is down. > What am I missing? Have I failed to find the right Tkinter > document? Is Tkinter the wrong tool for this job? Thanks. > I believe the only way to achieve this is binding to the entire canvas, then checking if the x, y coords are inside the "target". > -- > To email me, substitute nowhere->spamcop, invalid->net. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From danielpaul.simon at gmail.com Mon Jun 16 07:33:40 2008 From: danielpaul.simon at gmail.com (Dantheman) Date: Mon, 16 Jun 2008 04:33:40 -0700 (PDT) Subject: SPAM References: <09d39508-f2b3-49c8-9c11-255b5151396e@h1g2000prh.googlegroups.com> Message-ID: <07d7f769-1cc4-4357-8fb2-12ab9c082fa3@d77g2000hsb.googlegroups.com> SPAM From __peter__ at web.de Mon Jun 9 03:48:03 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Jun 2008 09:48:03 +0200 Subject: More than one element of list changing when only one should be References: Message-ID: Chuckk Hubbard wrote: > I can't think of any reason these lines: > > self.regionlist[self.hregion][0] = self.curnum > self.regionlist[self.hregion][1] = self.curden > self.regionlist[self.hregion][3] = self.octave11 = self.yadj > > should change self.regionlist[0] AND self.regionlist[2] in the same > call, but they do. ?Also, if I add more regions in series, they all > update each other. The likely explanation is that regionlist[0] and regionlist[2] are actually the same list. Throw in a print self.regionlist[0] is self.regionlist[2] to verify. The two most common reasons for that: class A: items = [] # class attribute, shared between all instances def f(items=[]): # default argument, shared between all calls # without explicit items argument return items Peter From fonnesbeck at gmail.com Thu Jun 19 01:02:35 2008 From: fonnesbeck at gmail.com (hardcoreUFO) Date: Wed, 18 Jun 2008 22:02:35 -0700 (PDT) Subject: Why doesnt PDB allow me to view the current line? Message-ID: I have some code that I am trying to debug (Python 2.5.2 on OSX) using pdb. However, when the code reaches the pdb.set_trace(), it does not allow me to view the current line: > /Users/chris/Research/ISEC/build/bdist.macosx-10.3-i386/egg/pyrl/reinforcement.py(943)__call__() (Pdb) n > /Users/chris/Research/ISEC/build/bdist.macosx-10.3-i386/egg/pyrl/reinforcement.py(946)__call__() (Pdb) l [EOF] (Pdb) l [EOF] It steps through the code fine, but for some reason returns end-of- file when I want to look at the code. From fetchinson at googlemail.com Thu Jun 26 23:11:59 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 26 Jun 2008 20:11:59 -0700 Subject: warning for unused packages/modules/objects Message-ID: How difficult would it be to implement a system in python that would warn if there are unnecessarily imported packages/modules/objects in the code? I mean that when developing some code one frequently imports stuff, deletes the import, changes stuff here and there, imports other stuff, later decides to change things and consequently delete the line with the import, etc, etc. As a result there can stay packages/modules/objects that are in the end not used. It would be great if python would issue a warning once the program finishes. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From constant.beta at gmail.com Sat Jun 21 09:47:29 2008 From: constant.beta at gmail.com (Michal Kwiatkowski) Date: Sat, 21 Jun 2008 06:47:29 -0700 (PDT) Subject: sys.settrace 'call' event behavior Message-ID: <08d43695-093f-4573-ab8b-8da035b3fdae@2g2000hsn.googlegroups.com> I'm building a tool to trace all function calls using sys.settrace function from the standard library. One of the awkward behaviors of this facility is that the class definitions are reported as 'call' events.[1] Since I don't want to catch class definitions, only function calls, I'm looking for a way to differentiate between those two. So far I have only vague clues about how to do that. At the bottom of this mail is a simple script that prints all attributes (except for the bytecode) of the traced code. In the sample code Bar class is defined and foo function is called after that. The following trace output is reported: Bar, 0, 0, (), (), (), (None,), ('__name__', '__module__', 'None'), foo.py, 21, , 1, 66 foo, 0, 0, (), (), (), (None,), (), foo.py, 25, , 1, 67 Class definition and function call differs on four attributes. Two of them, co_name and co_firstlineno are not very helpful. Other two are co_names and co_flags. The latter differs only by the CO_OPTIMIZED flag, which is for "internal use only"[2]. So we're left with co_names, which "is a tuple containing the names used by the bytecode". Is that helpful in distinguishing between class definitions and function calls? Do you have any other ideas on how to tell them apart? Source of the sample script I used follows. def trace(frame, event, arg): if event == 'call': print ', '.join(map(str, [frame.f_code.co_name, frame.f_code.co_argcount, frame.f_code.co_nlocals, frame.f_code.co_varnames, frame.f_code.co_cellvars, frame.f_code.co_freevars, frame.f_code.co_consts, frame.f_code.co_names, frame.f_code.co_filename, frame.f_code.co_firstlineno, frame.f_code.co_lnotab, frame.f_code.co_stacksize, frame.f_code.co_flags])) return trace import sys sys.settrace(trace) class Bar(object): None pass def foo(): pass foo() [1] It is strange for me, but documented properly. http://docs.python.org/lib/debugger-hooks.html says that call event happens when "a function is called (or some other code block entered)." [2] http://docs.python.org/ref/types.html#l2h-145 Cheers, mk From arne at vajhoej.dk Sun Jun 1 19:04:35 2008 From: arne at vajhoej.dk (=?ISO-8859-1?Q?Arne_Vajh=F8j?=) Date: Sun, 01 Jun 2008 19:04:35 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <4840ab73$0$90274$14726298@news.sunsite.dk> <4841f0aa$0$90274$14726298@news.sunsite.dk> Message-ID: <48432b01$0$90272$14726298@news.sunsite.dk> szr wrote: > Arne Vajh?j wrote: >> szr wrote: >>> Peter Duniho wrote: >>>> On Fri, 30 May 2008 22:40:03 -0700, szr >>>> wrote: >>>>> Arne Vajh?j wrote: >>>>>> Stephan Bour wrote: >>>>>>> Lew wrote: >>>>>>> } John Thingstad wrote: >>>>>>> } > Perl is solidly based in the UNIX world on awk, sed, } > bash >>>>>>> and C. I don't like the style, but many do. >>>>>>> } >>>>>>> } Please exclude the Java newsgroups from this discussion. >>>>>>> >>>>>>> Did it ever occur to you that you don't speak for entire news >>>>>>> groups? >>>>>> Did it occur to you that there are nothing about Java in the >>>>>> above ? >>>>> Looking at the original post, it doesn't appear to be about any >>>>> specific language. >>>> Indeed. That suggests it's probably off-topic in most, if not all, >>>> of the newsgroups to which it was posted, inasmuch as they exist for >>>> topics specific to a given programming language. >>> Perhaps - comp.programming might of been a better place, but not all >>> people who follow groups for specific languages follow a general >>> group like that - but let me ask you something. What is it you >>> really have against discussing topics with people of neighboring >>> groups? Keep in mind you don't have to read anything you do not want >>> to read. [1] >> I very much doubt that the original thread is relevant for the Java >> group. >> >> But the subthread Lew commente don was about Perl and Unix. That is >> clearly off topic. > > I agree with and understand what you are saying in general, but still, > isn't it possible that were are people in the java group (and others) > who might of been following the thread, only to discover (probably not > right away) that someone decided to remove the group they were reading > the thread from? I know I would not like that, even if it wasn't on > topic at the branch. > > Personally, I find it very annoying to have to switch news groups in > order to resume a thread and weed my way down the thread to where it > left off before it was cut off from the previous group. I am relative tolerant towards threads that are a bit off topic, if the S/N ratio overall is good. But I accept and respect that other people has a more strict attitude against off topic posts. And I am very little tolerant towards people that think they can attack those that want only on topic posts. One thing is to ask for a bit of slack regarding the rules something else is attacking those that want the rules kept. Arne From tgrav at mac.com Fri Jun 6 18:48:06 2008 From: tgrav at mac.com (Tommy Grav) Date: Fri, 6 Jun 2008 18:48:06 -0400 Subject: how to build a street with more than 1 house ? In-Reply-To: <4849BDF3.3010902@gmail.com> References: <4849BDF3.3010902@gmail.com> Message-ID: On Jun 6, 2008, at 6:45 PM, Stef Mientki wrote: > hello, > > In the code below, I can build a large street like this: > large_street = house * 25 > but not a small street. like this: > small_street = 5 * house This calls the int.__mul__() code i believe. > Why is this different ? > And more interesting, how do I get the right results ? If memory serves me right look into __rmul__(). Cheers Tommy From hniksic at xemacs.org Thu Jun 5 17:57:53 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 05 Jun 2008 23:57:53 +0200 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> <4847d203$0$32733$426a74cc@news.free.fr> Message-ID: <87lk1jzgri.fsf@mulj.homelinux.net> "Russ P." writes: > By the way, my recollection is that in C++ access defaults to private > if nothing is declared explicity. So normally the "private" > declaration is unnecessary. If it is left out, your little trick won't > work. How about #define class struct From precisionreplicas at gmail.com Mon Jun 2 03:17:30 2008 From: precisionreplicas at gmail.com (Best Replica Watches) Date: Mon, 2 Jun 2008 15:17:30 +0800 Subject: fake Watches Message-ID: fake Watches Http://www.precisionreplicas.com We offer you a World of Luxury at very affordable prices and you can rest easy about your satisfaction of quality and service. Now, with just a few simple steps, you can own something that will make you feel and look great! You can go to that business meeting, sales conference, or cocktail party wearing a beautiful watch and be sure to catch people's attention. The way you act, dress and present yourself will always be looked upon by others. By choosing from our selection of fine luxury items for a fraction of the cost you will look and feel successful, confident and you will be at your best. You will have all the class, prestige and luxury of a wealthy successful individual, and not spend a fortune to get there. Most of all you can improve your self esteem and feel confident to move in new circles of business associates and friends. Theses products will surely enhance your style and fashion. No one but you will know the beautiful item you wear is a replica, but you. Many of our customers buy from us and leave the Real One at home...... CATALOG OF REPLICA WATCHES ON: Http://www.precisionreplicas.com Rolex Replica Watches All Rolex Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Rolex Rolex Air King Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Air%20King Rolex Cosmograph Daytona Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Cosmograph%20Daytona Rolex Datejust Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Datejust%20Lady Rolex Datejust Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Datejust%20Man Rolex Datejust Two-Tone Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Datejust%20Two-Tone%20Lady Rolex Datejust Two-Tone Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Datejust%20Two-Tone%20Man Rolex Day-Date Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Day-Date Rolex Day-Date Full Gold Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Day-Date%20Full%20Gold%20Man Rolex Explorer Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Explorer Rolex GMT-Master II Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=GMT-Master%20II Rolex Oyster Perpetual Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Oyster%20Perpetual Rolex Submariner Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Submariner Rolex Yacht-Master Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Yacht-Master%20Lady Rolex Yacht-Master Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Yacht-Master%20Man Rolex Yachtmaster Two-tone Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Yachtmaster%20Two-tone%20Lady Cartier Replica Watches All Cartier Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Cartier Cartier Baignoire Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Baignoire%20Lady Cartier Ballon bleu Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Ballon%20bleu%20Lady Cartier Ballon bleu Men Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Ballon%20bleu%20Men Cartier Classic - Mid Size Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Classic%20-%20Mid%20Size Cartier Classic Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Classic%20Lady Cartier Classic Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Classic%20Man Cartier Divan Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Divan Cartier Divan Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Divan%20Lady Cartier Pacha Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Pacha%20Man Cartier Roadster Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Roadster Cartier Santos Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Santos%20Lady Cartier Santos Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Santos%20Man Cartier Tank American Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Tank%20American%20Lady Cartier Tank American Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Tank%20American%20Man Cartier Tank Francaise Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Tank%20Francaise%20Lady Cartier Tank Francaise Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Tank%20Francaise%20Man Bvlgari Replica Watches All Bvlgari Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Bvlgari Bvlgari Aluminium Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Bvlgari&EnSmallclassname=Aluminium%20Man Bvlgari B.Zero1 Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Bvlgari&EnSmallclassname=B.Zero1 Bvlgari Classic Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Bvlgari&EnSmallclassname=Classic%20Lady Bvlgari Classic Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Bvlgari&EnSmallclassname=Classic%20Man Bvlgari Diagono Scuba Professional Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Bvlgari&EnSmallclassname=Diagono%20Scuba%20Professional Bvlgari Rettangolo Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Bvlgari&EnSmallclassname=Rettangolo%20Lady Bvlgari Rettangolo Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Bvlgari&EnSmallclassname=Rettangolo%20Man Omega Replica Watches All Omega Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Omega Omega Constellation Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Omega&EnSmallclassname=Constellation Omega De Ville Co Axial Chronometer Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Omega&EnSmallclassname=De%20Ville%20Co%20Axial%20Chronometer Omega James Bond Seamaster Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Omega&EnSmallclassname=James%20Bond%20Seamaster Omega Seamaster Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Omega&EnSmallclassname=Seamaster Omega Seamaster Co-Axial Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Omega&EnSmallclassname=Seamaster%20Co-Axial Omega Speedmaster Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Omega&EnSmallclassname=Speedmaster Breitling Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Breitling Tag Heuer Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Tag%20Heuer Officine Panerai Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Officine%20Panerai A. Lange Sohne Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=A.Lange%20Sohne Franck Muller Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Franck%20Muller Hermes Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Hermes Jacob Co. Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Jacob%20Co. Audemars Piguet Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Audemars%20Piguet Chanel Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Chanel Corum Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Corum Emporio Armani Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Emporio%20Armani Gucci Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Gucci Longines Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Longines Louis Vuitton Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Louis%20Vuitton Patek Philippe Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Patek%20Philippe Piaget Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Piaget From alexnbryan at gmail.com Sat Jun 21 20:49:05 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Sat, 21 Jun 2008 19:49:05 -0500 Subject: Connecting a Desktop App to a Web App Message-ID: Okay, this is my first post to this mailing list, so first off if I shouldn't be sending something here, PLEASE correct me. Okay, so I want to create an app that has a GUI (most likely Tkinter) and will prompt the user to choose files and such and then will upload those files, either regularly or one time, whatever. But I don't know how to go abou doing such a thing, that is creating a app that will automatically upload to a back-up website(online storage). So if anyone can help me out or point me in the right direction that would be great. Thanks! From mdw at distorted.org.uk Sun Jun 8 08:30:05 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Sun, 8 Jun 2008 12:30:05 +0000 (UTC) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> <4847d203$0$32733$426a74cc@news.free.fr> <87lk1jzgri.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: > How about #define class struct Won't work. Consider `template ...'. -- [mdw] From gherron at islandtraining.com Mon Jun 23 11:59:31 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 23 Jun 2008 08:59:31 -0700 Subject: Passing arguments to subclasses In-Reply-To: <7pgv54l0pfaa2l05c4l8f3bld1rskd4dtf@4ax.com> References: <7pgv54l0pfaa2l05c4l8f3bld1rskd4dtf@4ax.com> Message-ID: <485FC863.7070502@islandtraining.com> John Dann wrote: > May I ask a simple newbie question, which I presume is true, but for > which I can't readily find confirmation: > > Let's say I have a parent class with an __init__ method explicitly > defined: > > class ParentClass(object): > def __init__(self, keyword1, keyword2): > etc > > and I subclass this: > > class ChildClass(ParentClass): > # No __init__ method explicitly defined > > Now I presume that I can instantiate a child object as: > > child = ChildClass(arg1, arg2) > > and arg1, arg2 will be passed through to the 'constructor' of the > antecedent ParentClass (there being no overrriding __init__ method > defined for ChildClass) and mapping to keyword1, keyword2 etc. > > Have I understood this correctly? Yes, but... The nice things about Python is that you can use the interactive interpreter to test such things in an instant. (And not have to wait for a response from python-list. Like this: >>> class ParentClass(object): ... def __init__(self, keyword1, keyword2): ... print 'ParentClass.__init__ called with', keyword1, keyword2 ... >>> class ChildClass(ParentClass): ... pass ... >>> child = ChildClass(123,456) ParentClass.__init__ called with 123 456 >>> Gary Herron From pichulin85 at hotmail.com Tue Jun 17 06:29:43 2008 From: pichulin85 at hotmail.com (Petertos) Date: Tue, 17 Jun 2008 03:29:43 -0700 (PDT) Subject: New widget Message-ID: Hello, here's a new casual game that looks interesting. It's called Smilies Invasion and you have to eat as much green smilies as you can: http://www.dolmenent.com/smiliesinvasion/ Greetings from a newbie developer. From metaperl at gmail.com Tue Jun 17 15:45:36 2008 From: metaperl at gmail.com (Terrence Brannon) Date: Tue, 17 Jun 2008 12:45:36 -0700 (PDT) Subject: 2d graphics - drawing a vescica piscis in Python Message-ID: <02c29cf2-5281-4c6f-966c-cb47101529ee@26g2000hsk.googlegroups.com> Hello, I have written a program to draw a vescica piscis from turtle import * def main(): setup(width=400, height=400) r = 50 color("black") circle(r) color("white") forward(r) color("black") circle(r) x = raw_input('please enter a string:') if __name__ == '__main__': main() ... but I would like the following: 1 - I dont like how the bottom of the first circle is not complete 2 - I would like for the left circle to be filled with verticle lines and the right circle to be filled with horizontal lines, so that the vescica piscis is cross-hatched. And finally, is turtle the "best" option for what I'm doing? pyCairo looked a bit hard to get going with, but very powerful. sping looked a bit alpha/beta. From sjmachin at lexicon.net Mon Jun 30 16:43:22 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 30 Jun 2008 13:43:22 -0700 (PDT) Subject: Freeze problem with Regular Expression References: <6cf614F3f8ocoU1@mid.individual.net> <0e1a9726-cc1d-4bd2-b0ba-b2bcc1c27ee8@f24g2000prh.googlegroups.com> <6cs9rtF3g9fsvU1@mid.individual.net> Message-ID: <08a8164c-fb82-4265-a84e-c0ccd92a01db@a32g2000prf.googlegroups.com> On Jul 1, 12:45 am, Kirk wrote: > On Wed, 25 Jun 2008 15:29:38 -0700, John Machin wrote: > > Several problems: > > Ciao John (and All partecipating in this thread), > first of all I'm sorry for the delay but I was out for business. > > > (1) lose the vertical bars (as advised by others) (2) ALWAYS use a raw > > string for regexes; your \s* will match on lower- case 's', not on > > spaces > > right! thanks! > > > (3) why are you using findall on a pattern that ends in "$"? > > Yes, you are right, I started with a different need and then it changed > over time... > > > (6) as remarked by others, you haven't said what you are trying to do; > > I reply here to all of you about such point: that's not important, > although I appreciate very much your suggestions! > My point was 'something that works in Perl, has problems in Python'. It *is* important; our point was 'you didn't define "works", and it was near-impossible (without transcribing your regex into verbose mode) to guess at what you suppose it might do sometimes'. From trepca at gmail.com Fri Jun 20 20:09:07 2008 From: trepca at gmail.com (Sebastjan Trepca) Date: Sat, 21 Jun 2008 02:09:07 +0200 Subject: Weird local variables behaviors Message-ID: Hey, can someone please explain this behavior: The code: def test1(value=1): def inner(): print value inner() def test2(value=2): def inner(): value = value inner() test1() test2() [trepca at sauron ~/dev/tests]$ python locals.py 1 Traceback (most recent call last): File "locals.py", line 13, in test2() File "locals.py", line 10, in test2 inner() File "locals.py", line 9, in inner value = value UnboundLocalError: local variable 'value' referenced before assignment Why can't he find the variable in the second case? Thanks, Sebastjan From mwilson at the-wire.com Mon Jun 9 09:07:03 2008 From: mwilson at the-wire.com (Mel) Date: Mon, 09 Jun 2008 09:07:03 -0400 Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: Frank Millman wrote: > Hi all > > I have a standard requirement for a 'decimal' type, to instantiate and > manipulate numeric data that is stored in a database. I came up with a > solution long before the introduction of the Decimal type, which has > been working well for me. I know the 'scale' (number of decimal > places) of the number in advance. When I read the number in from the > database I scale it up to an integer. When I write it back I scale it > down again. All arithmetic is done using integers, so I do not lose > accuracy. > > There is one inconvenience with this approach. For example, if I have > a product quantity with a scale of 4, and a price with a scale of 2, > and I want to multiply them to get a value with a scale of 2, I have > to remember to scale the result down by 4. This is a minor chore, and > errors are quickly picked up by testing, but it does make the code a > bit messy, so it would be nice to find a solution. > > I am now doing some refactoring, and decided to take a look at the > Decimal type. My initial impressions are that it is quite awkward to > use, that I do not need its advanced features, and that it does not > help solve the one problem I have mentioned above. > > I therefore spent a bit of time experimenting with a Number type that > suits my particular requirements. I have come up with something that > seems to work, which I show below. > > I have two questions. > > 1. Are there any obvious problems in what I have done? > > 2. Am I reinventing the wheel unnecessarily? i.e. can I do the > equivalent quite easily using the Decimal type? > > -------------------- > from __future__ import division > > class Number(object): > def __init__(self,value,scale): > self.factor = 10.0**scale > if isinstance(value,Number): > value = value.value / value.factor I think this could lead to trouble. One complaint against binary floating point is that it messes up low-order decimal digits, and this ensures that all calculations are effectively done in binary floating point. Better, I think would be if isinstance (value, Number): self.value = value.value self.scale = scale + value.scale and be done with it. Of course, this means self.scale no longer gives the preferred number of fractional digits. My bias: I did a DecimalFloat class way back when, when Decimal was being discussed, and separated the exponent for calculations from the rounding precision for display. Cheers, Mel From s0suk3 at gmail.com Sun Jun 15 12:22:03 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Sun, 15 Jun 2008 09:22:03 -0700 (PDT) Subject: Making wxPython a standard module? References: <48512f69$0$11262$c3e8da3@news.astraweb.com> <0bb2d727-4bd8-4baf-be34-716daec1ddff@d1g2000hsg.googlegroups.com> <87y756ahn2.fsf@benfinney.id.au> Message-ID: <0e2b604c-769b-4191-87ea-948566412094@34g2000hsh.googlegroups.com> On Jun 15, 9:37 am, Ben Finney wrote: > s0s... at gmail.com writes: > > I know there must be at least a few very solid answers to this, but, > > just to hear it from the Pythonistas: Why can't there be several GUI > > toolkits on the standard library? > > Because the Zen of Python advises against it: > > >>> import this > > The Zen of Python, by Tim Peters > ? > There should be one-- and preferably only one --obvious way to do it. > I agree with that concept. But there already is more than one way to do it, only that the other ways are being made less accessible (by not being on the standard library), don't you think? Anyway, as I said earlier, I'm sure there must be very solid reasons for this, so I don't intend to argue on this. Just a thought :). From alexnbryan at gmail.com Sat Jun 28 19:05:24 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Sat, 28 Jun 2008 18:05:24 -0500 Subject: Testing for Null? Message-ID: <268ac2770806281605n663670e9n29620f344ed66e4d@mail.gmail.com> I am having a problem with a list value that is empty. I have a list of definitions called mainList. the 5th value in the list doesn't have anything in it. In this case, the values are definitions; also, in this case just the word cheese is defined. Here is my output to the console: 5. a sprawling,weedy plant having small lavender or white flowers and round, flat, segmented fruits thought to resemble little wheels of cheese. 6. 7. an ingot or billet made into a convex, circular form by blows at the ends. I've made it so where the numbers, the period, and two spaces follow that, then the definition. However, as you can see in 6, there is nothing. Here is the code to print all this: n=0 for x in mainList: if mainList[n] == "": print "Error on this definition" else: print str(n+1)+". "+str(mainList[n]) n=n+1 Now the two "" is where I need to figure out if it is empty. What is up right now doesn't work; or at least doesn't give the desired result. So I need to know how to write the if statement to make it work. This should be simple, but I just don't know how to do it, never had this problem before. -------------- next part -------------- An HTML attachment was scrubbed... URL: From segfaulthunter at gmail.com Sun Jun 29 15:21:07 2008 From: segfaulthunter at gmail.com (name) Date: Sun, 29 Jun 2008 12:21:07 -0700 (PDT) Subject: gelato - nvidia and python References: <65fcd6a4-131e-4d7c-96b3-402296bf2a18@y21g2000hsf.googlegroups.com> Message-ID: <72a4698c-45ea-4fe1-a54f-52a4835f0672@d45g2000hsc.googlegroups.com> On Jun 29, 5:34?pm, "catalinf... at gmail.com" wrote: > Did somebody worked with gelato from nvidia and python? > I have some C cod from books nvidia . > This is : > " > GelatoAPI *r = GelatoAPI::CreateRenderer(); > r->Camera ("main"); > ... API calls through r ... > r->Render ("main"); > delete r; ? // Finished with this renderer > " > the code for python i create is only this : > " > python > Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) > [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> import gelato > >>> from gelato import * > >>> r=gelato.CreateRenderer > >>> print r > > >>> dir(r) > > ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', > '__getattribute__', '__hash__', '__init__', '__module__', '__name__', > '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', > '__setattr__', '__str__'] > " > And I blocked here... > Thank you . Maybe you should execute the CreateRenderer, like r=gelato.CreateRenderer() dir(r) I don't have gelato but it might work.. From pavel.uvarov at gmail.com Mon Jun 2 12:41:34 2008 From: pavel.uvarov at gmail.com (pavel.uvarov at gmail.com) Date: Mon, 2 Jun 2008 09:41:34 -0700 (PDT) Subject: ThreadPoolingMixIn References: <3d9dac72-ce4d-4ce5-9213-4bb17aff2f9e@r66g2000hsg.googlegroups.com> <1c4d113e-b375-471d-9d54-1401c8844352@t12g2000prg.googlegroups.com> Message-ID: <03ba6980-55d6-433a-a41f-f36a2edb4d72@f36g2000hsa.googlegroups.com> On Jun 2, 7:15 pm, Michael Str?der wrote: > pavel.uva... at gmail.com wrote: > > To benchmark this I used a simple tcp server which writes a small > > (16k) > > string to the client and closes the connection. > > Just a general note: When benchmarking such a network service it would > be valuable to see benchmark results for several data sizes. I'd expect > better numbers for a ThreadPoolingMixIn when there are more requests > with smaller data size. > > Ciao, Michael. Here are benchmarks for FreeBSD 6.2, amd64 packet_size x y 0 499.57 1114.54 1024 499.29 1130.02 3072 500.09 1119.14 7168 498.20 1111.76 15360 499.29 1086.73 31744 500.04 1036.46 64512 499.43 939.60 130048 499.28 737.44 261120 498.04 499.03 523264 307.54 312.04 1047552 173.57 185.32 2096128 93.61 94.39 x = ThreadingMixIn replies/s y = ThreadPoolingMixIn replies/s From bkasterm at gmail.com Sun Jun 15 10:03:04 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Sun, 15 Jun 2008 07:03:04 -0700 (PDT) Subject: Explaining Implementing a Binary Search Tree. Message-ID: I wrote a binary search tree in python, explaining as I was doing it how and why I did it. I am very interested in receiving comments on the code, process, and anything else that will improve my coding or writing. I wrote this all up in my blog at: http://kasterma.wordpress.com/2008/06/15/implementing-a-binary-search-tree/ The code of the class has been copied below, but the description of the process (mostly an attempt at approaching test driving development for as far as I understand the term) has not been copied. Any and all comments are appreciated. Best, Bart *********** python code ************************ import re class BSTree: def __init__ (self, value = None): self.value = value self.left = None self.right = None def __str__ (self): string = "(" if not self.value == None: string += str (self.value) if not (self.left == None and self.right == None): if self.left != None: string += str (self.left) else: string += "()" if self.right != None: string += str (self.right) else: string += "()" string += ")" return string def FromString (self, string): """ parses the string and builds the corresponding tree. If the parsing fails we print an error message and make no guarantees about the state of the tree. """ def readNumber (string, index): """ reads the number starting at index. Returns the number (as a string) that starts at index and the index that is just after the number. It expects the index to point to the first numberal. """ isdigit = re.compile ("\d") number = "" while isdigit.match (string [index]): number += string[index] index += 1 return number, index def FromString_Help (string, index): """ The function that actually does the parsing of the string. Variable index indicates where in the string we start working, it should be pointing to an open paren, and in returning point to just after the corresponding closing paren. """ if not string [index] == "(": print "FromString_Help: ERROR: no opening paren", print string, index tree = BSTree () tree.value, index = readNumber (string, index + 1) if string [index] == "(": tree.left, index = FromString_Help (string, index) tree.right, index = FromString_Help (string, index) if not string[index] == ")": print "FromString_Help: ERROR: no closing paren" print string, index if tree.value == '' and tree.left == None and tree.right == None: return None, index + 1 else: tree.value = int (tree.value) return tree, index + 1 index = 0 tree, index = FromString_Help (string, index) if tree == None: print "FromString: ERROR: empty tree passed" return self.value = tree.value self.left = tree.left self.right = tree.right def inOrder (self): """ gives a generator that runs through the tree inOrder """ values = [] if self.left != None: values += self.left.inOrder () if self.value != None: values.append (self.value) if self.right != None: values += self.right.inOrder () return values def Insert (self, value): """ add value to the tree in BSTree fashion. We add the value so that the values of the tree will be in order. We do not duplicate values in the tree. """ if self.value == None: # first value added to this tree self.value = value if self.value < value: if self.right == None: self.right = BSTree (value) else: self.right.Insert (value) if self.value > value: if self.left == None: self.left = BSTree (value) else: self.left.Insert (value) def Delete (self, value, parent = None, RL = None): """ remove value from the tree in BSTree fashion. Note: we might end up with an empty tree. """ if self.value == value: if self.left == None and self.right == None: if parent != None: if RL == "right": parent.right = None else: parent.left = None else: self.value = None # created an empty tree, note only # happens at the root. return if self.left == None: self.value = self.right.value self.left = self.right.left self.right = self.right.right elif self.left.right == None: self.value = self.left.value self.left = self.left.left else: moveup = self.left while moveup.right != None: # note that by the elif above at least one step is taken # we are here looking for the node to move up to the root moveup_parent = moveup moveup = moveup.right moveup_parent.right = moveup.left self.value = moveup.value return if self.value < value: self.right.Delete (value, self, "right") if self.value > value: self.left.Delete (value, self, "left") def Search (self, value): if self.value == value: return "yes" if self.value < value: if self.right == None: return "no" else: return self.right.Search (value) if self.value > value: if self.left == None: return "no" else: return self.left.Search (value) From fuzzyman at gmail.com Mon Jun 30 16:25:13 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 30 Jun 2008 13:25:13 -0700 (PDT) Subject: URLLIb2 problem References: <156e077b-1305-476c-885f-0b798f4ce699@s21g2000prm.googlegroups.com> Message-ID: On Jun 30, 9:11?pm, leechat2... at gmail.com wrote: > I am trying to write somecode of this kind :) > > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) > opener.addheaders = [('User-Agent','Mozilla/5.0 (Windows; U; Windows > NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14'), > ('Accept','text/xml,application/xml,application/xhtml+xml,text/ > html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'),('Accept- > Language','en-us,en;q=0.5'),('Accept-Encoding','gzip,deflate'), > ('Accept-Charset','ISO-8859-1,utf-8;q=0.7,*;q=0.7'),('Keep- > Alive','300'),('Connection','keep-alive'),('Content-Type','application/ > x-www-form-urlencoded')] > urllib2.install_opener(opener) > > fu = urllib2.urlopen('http://www.google.com') > print fu.read() > > I am not able to open any webpage as the content is junk > characters.something like below..what could be the > problem????????????? I think you'll find that the problem is caused by this part: ('Accept-Encoding','gzip,deflate') You may also find that these cause you some fun as well. ('Keep-Alive','300'),('Connection','keep-alive') Michael Foord http://www.ironpythoninaction.com/ http://www.trypython.org/ > > if I don't install the 'opener' I get everything properly > > ?]?s?H? ?T? ?Cj2????x:&? ?c???????~J ? ??????I??w???????ZB??q?? > ?T9?R???????????4 > ?7?????V??.i??"?????????W>? > ??y?=vm??)?????6??y???????9????l????>?????????(?g[??? > L?S??????????e???????GcS??w > s????/??G??|???9??F`??????*?????BV,????????o??pzn??;?y9?4 > ???f????z8???b?n??K}|? From n.emami at gmail.com Thu Jun 12 06:58:53 2008 From: n.emami at gmail.com (Nader) Date: Thu, 12 Jun 2008 03:58:53 -0700 (PDT) Subject: get keys with the same values Message-ID: Hello, I have a dictionary and will get all keys which have the same values. d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} I will something as : d.keys(where their values are the same) With this statement I can get two lists for this example: l1= ['a','e'] l2=['b','d'] Would somebody tell me how I can do it? Regards, Nader From KKatreena at gmail.com Sat Jun 21 06:20:34 2008 From: KKatreena at gmail.com (Katreena) Date: Sat, 21 Jun 2008 03:20:34 -0700 (PDT) Subject: earn money from Blogs Message-ID: Hello friends.., Welcome to the world of Information Technology,Enjoy the fragrance of Modern Life style&Make ur Living more comfortable than everbefore! Earn Millions of Dollars legal Income With Little Efforts In ur Spare time! Success usually comes to those who are too busy to be looking for it. Visit Related sites,Hollywood Movies and Videos etc.., - Hide quoted text - www.hollywoodmoviespot4u.blogspot.com
    Hii?Click image xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Hi..Click me

    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Hi..Click me

    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Hi..Click me

    From python-url at phaseit.net Tue Jun 3 10:27:25 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 3 Jun 2008 14:27:25 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Jun 3) Message-ID: QOTW: "PS: in some ways it's interesting and relevant that there has been no discussion on psf-members of Google's AppEngine, which many people I've talked to think is the most important thing that's ever happened to Python ever." - David Ascher Alternatives for a multi dimensional dictionary: http://groups.google.com/group/comp.lang.python/browse_thread/thread/91056401e4dbdadc/ Threads and memory usage: http://groups.google.com/group/comp.lang.python/browse_thread/thread/44c20f2595fe298b/ Should Python provide "real" data hiding? http://groups.google.com/group/comp.lang.python/browse_thread/thread/188467d724b48b32/ In response to a requirement for a data structure with fast inserts, no duplicates, and sorted items, several alternatives emerge: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ab429c0221994e2d/ How to read utf-8 encoded input from sys.stdin: http://groups.google.com/group/comp.lang.python/browse_thread/thread/44bb63456be8c331/ Looking for something similar to "classic" ASP web development in Python - and why it may not be a good idea: http://groups.google.com/group/comp.lang.python/browse_thread/thread/9bd633032e5709a8/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From __peter__ at web.de Sun Jun 15 08:17:23 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Jun 2008 14:17:23 +0200 Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> Message-ID: ram.rachum at gmail.com wrote: > On Jun 15, 2:48?pm, Peter Otten <__pete... at web.de> wrote: >> ram.rac... at gmail.com wrote: >> > Quick question: >> > I have python code that does a lot of floating point arithmetic. How >> > do I make it do the arithmetic in 64 bit? (I have a 64 bit CPU.) If >> > I'll install a 64-bit operating system, will that do the trick? >> >> The Python float type uses a C double internally which is 64 bit even on >> 32 bit CPUs. >> >> Peter > > Does it mean that even now it does arithmetic in 64 bit? Yes. See http://en.wikipedia.org/wiki/IEEE_floating-point_standard#Double-precision_64_bit for details. > I'm not getting enough precision. Is there any way to increase it? http://gmpy.sourceforge.net/ If by "not enough precision" you mean you are bothered by >>> .1 0.10000000000000001 have a look at the decimal module, see http://docs.python.org/lib/module-decimal.html Peter From tdahsu at gmail.com Fri Jun 13 11:56:12 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Fri, 13 Jun 2008 08:56:12 -0700 (PDT) Subject: Iterate creating variables? References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> <6bfhj5F3b47fmU1@mid.uni-berlin.de> <6bfj7bF3c3npoU1@mid.uni-berlin.de> Message-ID: On Jun 13, 11:48?am, "Diez B. Roggisch" wrote: > tda... at gmail.com schrieb: > > > > > On Jun 13, 11:21 am, "Diez B. Roggisch" wrote: > >> tda... at gmail.com schrieb: > > >>> I have twenty-five checkboxes I need to create (don't ask): > >>> self.checkbox1 = ... > >>> self.checkbox2 = ... > >>> . > >>> . > >>> . > >>> self.checkbox25 = ... > >>> Right now, my code has 25 lines in it, one for each checkbox, since > >>> these are all variables. > >>> Is there a way to write a loop so that I can have fewer lines of code > >>> but still keep the variables? > >>> I've tried: > >>> for o in xrange(25): > >>> ? ? self.checkbox[o] = ... > >>> which didn't work, and > >>> for o in xrange(25): > >>> ? ? self.checkbox[''%d'%(o)] = ... > >>> which also didn't work. > >>> Both give the error message: "Attribute error: Main.App has no > >>> attribute "checkbox"", which clearly indicates that I'm not keeping > >>> the "variability" aspect I want. > >>> Is there a way? > >> Keep either a list or dictionary around. Like this: > > >> checkboxes = [] > > >> for o in xrange(25): > >> ? ? ?checkboxes.append(....create a checkbox...) > > >> self.checkboxes = checkboxes > > >> Diez > > > I don't understand... how do I then complete the assignment statement? > > > If I have: > > > self.checkbox1 = xrc.XRCCTRL(self.panel01, 'Checkbox1') > > . > > . > > . > > self.checkbox25 = xrc.XRCCTRL(self.panel01, 'Checkbox25') > > > using your method, wouldn't I still need to figure out my original > > question? > > > If I have a list of checkboxes, then I'll have: > > > checkboxes = [checkbox1, checkbox2 ... checkbox25] > > > in which case I'd still need to figure out how to get the variable at > > the end of checkbox to do the rest of the "=" statement. > > I don't fully understand that. But if your code is uniform and looks > like the above, it appears that > > for o in xrange(25): > ? ? ?checkboxes.append(xrc.XRCCTRL(self.panel01, 'Checkbox%i' % o)) > > is the way to go. > > Diez Thank you, this is much closer to where I need to be... The issue is (and this is the part that you don't know, because I didn't tell you!) is that I later need to call methods on "self.checkbox1", for instance: self.checkbox1.GetValue() to determine if the box is checked or not. I should have included that piece in the initial problem description; my apologies. From wizzardx at gmail.com Sun Jun 22 07:11:01 2008 From: wizzardx at gmail.com (David) Date: Sun, 22 Jun 2008 13:11:01 +0200 Subject: Storing value with limits in object In-Reply-To: References: Message-ID: <18c1e6480806220411u391e6dc9t34465e5d5a468440@mail.gmail.com> On Sun, Jun 22, 2008 at 12:24 PM, Josip wrote: >> Not with normal vars, because = is a rebinding operator in Python, >> rather than assignment. >> >> You can do (close to) the above with object properties. >> >> David. > > Yes, but it's done with built-in types like int and float. I suspect I could > subclass from them and implement limits, but I would have to make > seperate class for each type. Can I override conversion methods like int() > and float() within my class? > I think I may have misread your original post. ints and floats are internal , immutable types, with some class goodness on top (so you can treat them like objects to a degree, subclass from them, etc). Python's interpreter has built-in logic which 'knows' how to use ints and floats variables, without calling their special "__" methods. Python would be a lot slower if it worked this way. To do exactly what you want, you'd need to add a new internal numeric type to Python. You can subclass from float, and redefine __float__ and __int__, but those will only be called when your code actually calls the builtin float() and int() builtins, eg: import math class Float(float): def __float__(self): raise NotImplementedError a = Float(1) print math.sin(a) # Outputs 0.841470984808 a = Float(1) print math.sin(float(a)) # Throws a NotImplementedError exception There is no way (afaik) for an object to tell Python to call one of it's methods to get a reference, or 'value' to the object (if there was, it would make things really complicated). In Python you generally need to update the logic used during a lookup to get that effect (ie, in a.b.c, you can customise the a.b lookup, or the a.b.c lookup, but not the a lookup itself). In theory you could hack Python's internal locals or globals dictionary so that it did something unusual while looking up your object. But in practice this doesn't work, because the returned objects (when you call globals() or locals()) attributes are readonly. Probably because those internal lookup dicts are implemented in optimized C not Python, and the C implementation doesn't let you redefine it's internals via the Python interface. David. From rhamph at gmail.com Wed Jun 11 01:59:42 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Tue, 10 Jun 2008 22:59:42 -0700 (PDT) Subject: Producer-consumer threading problem References: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> Message-ID: <9482cbb7-297e-4429-b7a1-6d7c1dcc9070@t12g2000prg.googlegroups.com> Why not use a normal Queue, put a dummy value (such as None) in when you're producer has finished, and have the main thread use the normal Thread.join() method on all your child threads? From bignose+hates-spam at benfinney.id.au Sun Jun 15 10:37:37 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 16 Jun 2008 00:37:37 +1000 Subject: Making wxPython a standard module? References: <48512f69$0$11262$c3e8da3@news.astraweb.com> <0bb2d727-4bd8-4baf-be34-716daec1ddff@d1g2000hsg.googlegroups.com> Message-ID: <87y756ahn2.fsf@benfinney.id.au> s0suk3 at gmail.com writes: > I know there must be at least a few very solid answers to this, but, > just to hear it from the Pythonistas: Why can't there be several GUI > toolkits on the standard library? Because the Zen of Python advises against it: >>> import this The Zen of Python, by Tim Peters ? There should be one-- and preferably only one --obvious way to do it. -- \ "Tis more blessed to give than to receive; for example, wedding | `\ presents." -- Henry L. Mencken | _o__) | Ben Finney From dullrich at sprynet.com Wed Jun 4 17:39:38 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Wed, 04 Jun 2008 16:39:38 -0500 Subject: re References: <6anvi4F38ei08U1@mid.uni-berlin.de> Message-ID: In article , "Russell Blau" wrote: > "Diez B. Roggisch" wrote in message > news:6anvi4F38ei08U1 at mid.uni-berlin.de... > > David C. Ullrich schrieb: > >> Say I want to replace 'disc' with 'disk', but only > >> when 'disc' is a complete word (don't want to change > >> 'discuss' to 'diskuss'.) The following seems almost > >> right: > >> > >> [^a-zA-Z])disc[^a-zA-Z] > >> > >> The problem is that that doesn't match if 'disc' is at > >> the start or end of the string. Of course I could just > >> combine a few re's with |, but it seems like there should > >> (or might?) be a way to simply append a \A to the first > >> [^a-zA-Z] and a \Z to the second. > > > > Why not > > > > ($|[\w])disc(^|[^\w]) > > > > I hope \w is really the literal for whitespace - might be something > > different, see the docs. > > No, \s is the literal for whitespace. > http://www.python.org/doc/current/lib/re-syntax.html > > But how about: > > text = re.sub(r"\bdisc\b", "disk", text_to_be_changed) > > \b is the "word break" character, Lovely - that's exactly right, thanks. I swear I looked at the docs... I'm just blind or stupid. No wait, I'm blind _and_ stupid. No, blind and stupid and slow... Doesn't precisely fit the _spec_ because of digits and underscores, but it's close enough to solve the problem exactly. Thanks. >it matches at the beginning or end of any > "word" (where a word is any sequence of \w characters, and \w is any > alphanumeric > character or _). > > Note that this solution still doesn't catch "Disc" if it is capitalized. Thanks. I didn't mention I wanted to catch both cases because I already knew how to take care of that: r"\b[dD]isc\b" > Russ -- David C. Ullrich From goon12 at gmail.com Mon Jun 23 09:38:40 2008 From: goon12 at gmail.com (Joe Riopel) Date: Mon, 23 Jun 2008 09:38:40 -0400 Subject: Distutils and unit test files Message-ID: <6a2ccd190806230638m27206217k2ac181b4999bc2e5@mail.gmail.com> Hi, I am using Distutils to build and distribute some packages. I do write unit tests, but I am confused as to where to put them and how to run them prior to the package being installed (The modules being tested would not be in my sys.path). I would rather not put the test cases in the same files as the modules being tested, I want keep them in a sub directory of the module, or in a separate "test" directory. What are some of the strategies for dealing with this? Thanks. From larry.bates at websafe.com` Sat Jun 7 16:06:39 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 07 Jun 2008 15:06:39 -0500 Subject: simple question on list manipulation from a newbie In-Reply-To: <76ccc0a8-90de-4717-9e6f-06836827b1e1@i18g2000prn.googlegroups.com> References: <76ccc0a8-90de-4717-9e6f-06836827b1e1@i18g2000prn.googlegroups.com> Message-ID: <2IOdnfa0D533d9fVnZ2dnUVZ_sKqnZ2d@comcast.com> Sengly wrote: > Dear all, > > I am working with wordnet and I am a python newbie. I'd like to know > how can I transfer a list below > > In [69]: dog > Out[69]: > [{noun: dog, domestic_dog, Canis_familiaris}, > {noun: frump, dog}, > {noun: dog}, > {noun: cad, bounder, blackguard, dog, hound, heel}, > {noun: frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, > weenie}, > {noun: pawl, detent, click, dog}, > {noun: andiron, firedog, dog, dog-iron}] > > to a list like this with python: > > [dog, domestic_dog, Canis_familiaris, > frump, dog, > dog, > cad, bounder, blackguard, dog, hound, heel, > frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, > weenie}, > pawl, detent, click, dog}, > andiron, firedog, dog, dog-iron] > > Thank you. > > Sengly > You should at least tell us what you have tried and where this information is coming from and in what format. Assumptions: 1) is a string containing what is shown (not a list of dictionaries) 2) the result you want is also a string (not a list) out = '[{noun: dog, domestic_dog, Canis_familiaris},{noun: frump, dog},' \ '{noun: dog},{noun: cad, bounder, blackguard, dog, hound, heel},' \ '{noun: frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, ' \ 'weenie}, {noun: pawl, detent, click, dog}, {noun: andiron, firedog, ' \ 'dog, dog-iron}]' l = out.replace('}', '')[1:-1].split('{noun: ')[1:] results = [] for entry in l: words = [x.strip() for x in entry.split(',')] results.extend(words) print results Note: this is very specific to the contents you show. If you need a general solution you will either need to use regexes or look a pyparsing. -Larry From larry.bates at websafe.com` Sat Jun 14 19:11:36 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 14 Jun 2008 18:11:36 -0500 Subject: os.walk Value Error? In-Reply-To: References: Message-ID: tdahsu at gmail.com wrote: > Hi, > > I'm using os.walk as follows: > > (basedir, pathnames, files) = os.walk("results", topdown=True) > > and I'm getting the error: > > ValueError: too many values to unpack > > From my googling, that means: > > This is the standard message when Python tries to unpack a tuple > into fewer variables than are in the tuple. > > From what I can see of the examples on the python site, I'm using it > correctly. I have commas in my original code, and the "results" > directory exists and is directly under the directory from which my > script is run. > > I'm assuming that 12 files (the number of files in the "results" > directory) is not too many for Python to handle! ;-) > > Is there any other reason I might get that error? os.walk is a generator so you need to make it a loop target: for basedir, pathnames, files in os.walk("results"): # # Do you work inside the loop # -Larry From prabhuragav.b at gmail.com Fri Jun 6 02:10:36 2008 From: prabhuragav.b at gmail.com (BABLU) Date: Thu, 5 Jun 2008 23:10:36 -0700 (PDT) Subject: EARN DOLLARS NO INVESTMENT NO SALES 100% HOME BASED BUSINESS Message-ID: <15b38591-fc8d-40f3-9402-1808ef6130f7@l17g2000pri.googlegroups.com> Hi, I am doing home based business and earning a good amount of money and found that business through internet is amazing to earn during leisure.Its just easy and relaxing. Just login in the link below and register yourself. register is free. then they will promote job for you. I have provided three site links for you so that you can earn money in which you want. Every job is genuine, good easy and interesting too. Make a try and fill your pockets with dollars. FREE ! FREE ! FULLY GENUINE HOME BASED ? CLICK HERE http://www.ezinfocenter.com/10122618/CB http://Prabhiya.dubaimlm.com? http://www.CashBlasterPro.com/earndollars http://www.webupgrade7.com/earndollars http://www.webupgrade9.com/earndollars http://www.webupgrade10.com/earndollars http://www.www2upgrade.com/earndollars http://www.BizOpSpace.com/earndollars http://www.BizOpBuilder.com/earndollars http://www.MyWebToo.com/earndollars http://www.Web2Wow.com/earndollars While you've been reading the above, thousands of people all over the world have been working. I even make money while I sleep! By this time next week, so could YOU. Get full info here http://www.ezinfocenter.com/10122618/CB http://Prabhiya.dubaimlm.com http://www.CashBlasterPro.com/earndollars http://www.webupgrade7.com/earndollars http://www.webupgrade9.com/earndollars http://www.webupgrade10.com/earndollars http://www.www2upgrade.com/earndollars http://www.BizOpSpace.com/earndollars http://www.BizOpBuilder.com/earndollars http://www.MyWebToo.com/earndollars http://www.Web2Wow.com/earndollars Network Marketing is BOOMING on the Web! Learn how we're sponsoring OVER 100,000 monthly worldwide without mailing anything, without faxing anything, without calling anyone! Totally Internet and system- driven and we've only scratched the surface. Get started FREE! Sign up as an affiliate at: http://www.ezinfocenter.com/10122618/CB ?http://Prabhiya.dubaimlm.com http://www.CashBlasterPro.com/earndollars http://www.webupgrade7.com/earndollars http://www.webupgrade9.com/earndollars http://www.webupgrade10.com/earndollars http://www.www2upgrade.com/earndollars http://www.BizOpSpace.com/earndollars http://www.BizOpBuilder.com/earndollars http://www.MyWebToo.com/earndollars http://www.Web2Wow.com/earndollars For More Details : Contact us at: Priya Prabhu No.75/31,Ist Floor , Subramanianm Swamy Koil Street West Saidapet chennai-600015 prabhuragav.b at gmail.com http://www.ezinfocenter.com/10122618/CB http://Prabhiya.dubaimlm.com http://www.CashBlasterPro.com/earndollars http://www.webupgrade7.com/earndollars http://www.webupgrade9.com/earndollars http://www.webupgrade10.com/earndollars http://www.www2upgrade.com/earndollars http://www.BizOpSpace.com/earndollars http://www.BizOpBuilder.com/earndollars http://www.MyWebToo.com/earndollars http://www.Web2Wow.com/earndollars From mensanator at aol.com Tue Jun 17 16:36:29 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 17 Jun 2008 13:36:29 -0700 (PDT) Subject: 2d graphics - drawing a vescica piscis in Python References: <02c29cf2-5281-4c6f-966c-cb47101529ee@26g2000hsk.googlegroups.com> Message-ID: <4d8959ac-4f28-4291-8208-d4b0ed9f5480@l64g2000hse.googlegroups.com> On Jun 17, 2:45?pm, Terrence Brannon wrote: > Hello, I have written a program to draw a vescica piscis en.wikipedia.org/wiki/Vesica_piscis> > > from turtle import * > > def main(): > ? ? setup(width=400, height=400) > > ? ? r = 50 > ? ? color("black") > ? ? circle(r) > ? ? color("white") > ? ? forward(r) > ? ? color("black") > ? ? circle(r) > ? ? x = raw_input('please enter a string:') > > if __name__ == '__main__': > ? ? main() > > ... but I would like the following: > > 1 - I dont like how the bottom of the first circle is not complete Because you overwrote that portion of the circle when you changed the color to white. Instead, you should have done up() (which lifts the pen) and then down() after you've moved to the start of the second circle. No need to change the pen color. > 2 - I would like for the left circle to be filled with verticle lines > and the right circle to be filled with horizontal lines, so that the > vescica piscis is cross-hatched. That would be the fill() command, but it's not documented how to fill with anything other than a solid color. > > And finally, is turtle the "best" option for what I'm doing? pyCairo > looked a bit hard to get going with, but very powerful. sping looked a > bit alpha/beta. From ethan at stoneleaf.us Tue Jun 17 15:42:20 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 17 Jun 2008 11:42:20 -0800 Subject: 'string'.strip(chars)-like function that removes from the middle? In-Reply-To: <48569B9E.6030206@admailinc.com> References: <48569B9E.6030206@admailinc.com> Message-ID: <4858139C.6090201@stoneleaf.us> Ethan Furman wrote: > Greetings. > > The strip() method of strings works from both ends towards the middle. > Is there a simple, built-in way to remove several characters from a > string no matter their location? (besides .replace() ;) > > For example: > .strip --> 'www.example.com'.strip('cmowz.') > 'example' > .??? --> --- 'www.example.com'.strip('cmowz.') > 'exaple' Thanks for all the ideas! -- Ethan From nmiyasato at gmail.com Sun Jun 29 22:26:45 2008 From: nmiyasato at gmail.com (miya) Date: Sun, 29 Jun 2008 19:26:45 -0700 (PDT) Subject: How to invoke the Python idle References: <08484763-05df-49ee-b308-2dd64b7e2379@e39g2000hsf.googlegroups.com> Message-ID: <6cf3de4e-e279-4aa3-99d3-7a32a6baeebe@27g2000hsf.googlegroups.com> On Jun 29, 10:01?pm, Only-Trouble wrote: > Hi all > I am running openSUSE 10.3 > I am learning python on my own, it seems like ?the system has already > installed a python IDLE > The question is how to invoke it? > > Thanks > > Only-Trouble how about executing from the terminal idle -- Nicol?s Miyasato (miya) http://nmiyasato.blogspot.com From Lie.1296 at gmail.com Tue Jun 3 06:22:35 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 3 Jun 2008 03:22:35 -0700 (PDT) Subject: Misuse of list comprehensions? References: <038e4418$0$27258$c3e8da3@news.astraweb.com> <7aa231e6-2f9c-4e90-8cd1-e839dc6940f2@x35g2000hsb.googlegroups.com> <69g3bmF31ttuuU3@mid.uni-berlin.de> Message-ID: On May 20, 8:51?pm, "Diez B. Roggisch" wrote: > bearophileH... at lycos.com wrote: > > John Salerno: > >> What does everyone think about this? > > > The Example 2 builds a list, that is then thrown away. It's just a > > waste of memory (and time). > > No, it doesn't. It uses append because it refers to itself in the > if-expression. So the append(c) is needed - and thus the assignment > possible but essentially useless. > > Diez Yes it does, it build a list of 'None's. And if list.append is concerned, the example given has no use, since: x = [c for c in cs] is essentially the same as x = [] [x.append(c) for c in cs] If, you're talking about other function calls, it might be an abuse or not depending on personal preference. From thomasmallen at gmail.com Tue Jun 3 15:16:47 2008 From: thomasmallen at gmail.com (tmallen) Date: Tue, 3 Jun 2008 12:16:47 -0700 (PDT) Subject: New variable? References: <18105511-7ae1-45e9-8c43-f34c1c4f5aeb@c58g2000hsc.googlegroups.com> <0dabbe7c-5754-4b2a-ae69-e92939fa682b@r66g2000hsg.googlegroups.com> Message-ID: <2c47defa-52b3-4bbc-8286-9e266df80eb7@26g2000hsk.googlegroups.com> On Jun 3, 3:03 pm, Chris wrote: > On Jun 3, 8:40 pm, tmallen wrote: > > > What's the proper way to instantiate a new variable? x = ""? > > You don't need to pre-declare your variables. Just assign them as you > need them and they will take the correct type. unless I'm using the += or a similar operator, right? That doesn't seem to instantiate a variable. From jstroud at mbi.ucla.edu Fri Jun 6 17:20:37 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 06 Jun 2008 14:20:37 -0700 Subject: Learning which modules were loaded Message-ID: I am rolling up a distribution of a program I wrote. It uses matplotlib with tkagg so the bundle is HUGE (47 MB, 14 MB after bz compression). Is there any way to run the program, put it through all of its paces, and then inspect which modules were loaded. I would like to gather these in a list and delete any others that py2app and py2exe attempt to include. Currently, these (or py2app, at least) use dependency graphing and icnlude everything belonging to pylab, matplotlib, and numpy by default. I don't want everything, I only want what my program needs to run. For example, some modules are imported by functions (in Pmw, for example) that never get called. I don't want to include these. Thanks in advance for any help. James From theo at van-werkhoven.nl.invalid Sun Jun 8 06:58:07 2008 From: theo at van-werkhoven.nl.invalid (Theo v. Werkhoven) Date: Sun, 8 Jun 2008 12:58:07 +0200 Subject: time.clock() or Windows bug? Message-ID: hi, In this code I read out an instrument during a user determined period, and save the relative time of the sample (since the start of the test) and the readback value in a csv file. #v+ from datetime import * from time import * from visa import * from random import * [..] for Reading in range(Readings): RelTimeOfSample = "%.1f" % clock() #PwrMtr.write("READ?") #Sample = "%.3f" % float(PwrMtr.read()) Sample = "%.3f" % (uniform(8.9,9.3)) # Simulation of reading. print "Sample %s, at %s seconds from start; Output power is: %s dBm" % (Reading+1, RelTimeOfSample, Sample) writer.writerow([RelTimeOfSample, Sample]) ResultFile.flush() sleep(6.6) #v- Output: Sample 1, at 0.0 seconds from start; Output power is: 8.967 dBm Sample 2, at 6.6 seconds from start; Output power is: 9.280 dBm Sample 3, at 13.2 seconds from start; Output power is: 9.096 dBm Sample 4, at 19.8 seconds from start; Output power is: 9.166 dBm Sample 5, at 26.4 seconds from start; Output power is: 8.918 dBm Sample 6, at 33.0 seconds from start; Output power is: 9.183 dBm Sample 7, at 39.7 seconds from start; Output power is: 8.903 dBm Sample 8, at 46.3 seconds from start; Output power is: 9.138 dBm Sample 9, at 52.9 seconds from start; Output power is: 9.163 dBm Sample 10, at 59.5 seconds from start; Output power is: 9.075 dBm Sample 11, at 66.1 seconds from start; Output power is: 9.230 dBm Sample 12, at 72.7 seconds from start; Output power is: 9.225 dBm Sample 13, at 79.3 seconds from start; Output power is: 9.053 dBm Sample 14, at 85.9 seconds from start; Output power is: 9.066 dBm Sample 15, at 92.5 seconds from start; Output power is: 9.109 dBm Sample 16, at 99.1 seconds from start; Output power is: 9.286 dBm Sample 17, at 105.7 seconds from start; Output power is: 9.147 dBm Sample 18, at 112.4 seconds from start; Output power is: 9.284 dBm Sample 19, at 119.0 seconds from start; Output power is: 9.013 dBm Sample 20, at 125.6 seconds from start; Output power is: 8.952 dBm Sample 21, at 91852.8 seconds from start; Output power is: 9.102 dBm Sample 22, at 91862.7 seconds from start; Output power is: 9.289 dBm Sample 23, at 145.4 seconds from start; Output power is: 9.245 dBm Sample 24, at 152.0 seconds from start; Output power is: 8.936 dBm Sample 25, at 158.8 seconds from start; Output power is: 9.139 dBm Sample 26, at 165.4 seconds from start; Output power is: 9.241 dBm Sample 27, at 172.1 seconds from start; Output power is: 8.938 dBm Sample 28, at 178.7 seconds from start; Output power is: 8.947 dBm Sample 29, at 185.3 seconds from start; Output power is: 9.252 dBm Sample 30, at 191.9 seconds from start; Output power is: 9.082 dBm Sample 31, at 198.5 seconds from start; Output power is: 9.224 dBm Sample 32, at 205.1 seconds from start; Output power is: 8.902 dBm Sample 33, at 211.7 seconds from start; Output power is: 9.182 dBm Sample 34, at 218.3 seconds from start; Output power is: 8.974 dBm Sample 35, at 224.9 seconds from start; Output power is: 9.129 dBm Sample 36, at 231.5 seconds from start; Output power is: 9.214 dBm Sample 37, at 238.1 seconds from start; Output power is: 9.188 dBm Sample 38, at 244.8 seconds from start; Output power is: 8.909 dBm Sample 39, at 251.4 seconds from start; Output power is: 9.197 dBm Sample 40, at 258.0 seconds from start; Output power is: 8.946 dBm Sample 41, at 264.6 seconds from start; Output power is: 9.228 dBm Sample 42, at 271.2 seconds from start; Output power is: 8.938 dBm Sample 43, at 92071.3 seconds from start; Output power is: 8.964 dBm Sample 44, at 284.4 seconds from start; Output power is: 9.276 dBm Sample 45, at 291.0 seconds from start; Output power is: 8.932 dBm Sample 46, at 297.6 seconds from start; Output power is: 9.158 dBm But look at the timestamps of samples 21, 22 and 43. What is causing this? I've replaced the time.clock() with time.time(), and that seems to solve the problem, but I would like to know if it's something I misunderstand or if it's a problem with the platform (Windows Server 2003) or the time.clock() function. T:\Theo\Python>ver Microsoft Windows [Version 5.2.3790] T:\Theo\Python>c:\Python25\python.exe --version Python 2.5.1 Thanks, Theo From bob at mellowood.ca Wed Jun 11 19:38:58 2008 From: bob at mellowood.ca (bvdp) Date: Wed, 11 Jun 2008 16:38:58 -0700 Subject: Simple and safe evaluator Message-ID: I'm finding my quest for a safe eval() quite frustrating :) Any comments on this: Just forget about getting python to do this and, instead, grab my set of values (from a user supplied text file) and call an external program like 'bc' to do the dirty work. I think that this would avoid someone from embedding os.system("rm ...") in what I thought would be a math expression and having it maybe do damage? Perhaps I'm getting too paranoid in my old age. I guess this would slow things down a bit, but that is not a big concern. Bigger concern would be that I'm not sure if 'bc' or whatever is guaranteed to be on other platforms than *nix. And if I want to be really paranoid, I could worry that someone had planted a bad 'bc' on the target. From paddy3118 at googlemail.com Fri Jun 13 00:53:06 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 12 Jun 2008 21:53:06 -0700 (PDT) Subject: Mapping None. Why? References: Message-ID: On Jun 12, 9:48 pm, Robert Kern wrote: > Paddy wrote: > > On looking up map on Wikipedia there is no mention of this special > > behaviour, > > So my question is why? > > My question is why you are looking up the semantics of Python functions on > Wikipedia instead of the Python documentation. I don't see any particular > discussion of map() there at all. Am I missing something? > > -- > Robert Kern As I said in an answer to Diez B. Roggish, I had been reminded of the behaviour, thought it odd, and looked for other implementations that might have the behaviour via wikipedia. My intension was most definitely NOT to say that Pythons map should do what Wikipedia says slavishly. Sometimes when I pick at these seeming inconsistencies I learn a lot from the c.l.p replies. Someone elses thread on -0.0 versus +0.0 taught me some more on floating point for example. - Paddy. From eliben at gmail.com Fri Jun 20 08:03:00 2008 From: eliben at gmail.com (eliben) Date: Fri, 20 Jun 2008 05:03:00 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> Message-ID: <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> On Jun 20, 9:17 am, Bruno Desthuilliers wrote: > eliben a ?crit :> Hello, > > > In a Python program I'm writing I need to dynamically generate > > functions[*] > > (snip) > > > [*] I know that each time a code generation question comes up people > > suggest that there's a better way to achieve this, without using exec, > > eval, etc. > > Just to make things clear: you do know that you can dynamically build > functions without exec, do you ? > Yes, but the other options for doing so are significantly less flexible than exec. > > But in my case, for reasons too long to fully lay out, I > > really need to generate non-trivial functions with a lot of hard-coded > > actions for performance. > > Just out of curiousity : could you tell a bit more about your use case > and what makes a simple closure not an option ? Okay. I work in the field of embedded programming, and one of the main uses I have for Python (and previously Perl) is writing GUIs for controlling embedded systems. The communication protocols are usually ad-hoc messages (headear, footer, data, crc) built on top of serial communication (RS232). The packets that arrive have a known format. For example (YAMLish syntax): packet_length: 10 fields: - name: header offset: 0 length: 1 - name: time_tag offset: 1 length: 1 transform: val * 2048 units: ms - name: counter offset: 2 length: 4 bytes-msb-first: true - name: bitmask offset: 6 length: 1 bit_from: 0 bit_to: 5 ... This is a partial capability display. Fields have defined offsets and lengths, can be only several bits long, can have defined transformations and units for convenient display. I have a program that should receive such packets from the serial port and display their contents in tabular form. I want the user to be able to specify the format of his packets in a file similar to above. Now, in previous versions of this code, written in Perl, I found out that the procedure of extracting field values from packets is very inefficient. I've rewritten it using a dynamically generated procedure for each field, that does hard coded access to its data. For example: def get_counter(packet): data = packet[2:6] data.reverse() return data This gave me a huge speedup, because each field now had its specific function sitting in a dict that quickly extracted the field's data from a given packet. Now I'm rewriting this program in Python and am wondering about the idiomatic way to use exec (in Perl, eval() replaces both eval and exec of Python). Eli From circularfunc at yahoo.se Mon Jun 23 13:53:30 2008 From: circularfunc at yahoo.se (cirfu) Date: Mon, 23 Jun 2008 10:53:30 -0700 (PDT) Subject: installed 3.0, rebind winprompt to 2.5? Message-ID: <212d2320-0c9e-4744-823b-bf715d4bb9ee@c65g2000hsa.googlegroups.com> i installed python 3.0. now when im laucnhing from the dos prompt in win vista it searches in python3.0 i want to rebind it to 2.5, what do i need to change? From chardish at gmail.com Tue Jun 10 11:13:03 2008 From: chardish at gmail.com (chardish at gmail.com) Date: Tue, 10 Jun 2008 08:13:03 -0700 (PDT) Subject: Instructions on how to build py2exe 0.6.8 (or an installer would be nice, too!) References: <5426baaf-2ba6-41b0-a0ec-1070429b5195@x35g2000hsb.googlegroups.com> <6b7jlqF39pgfcU1@mid.individual.net> Message-ID: <3841147f-f1b5-4d34-8df0-6afa002f493e@25g2000hsx.googlegroups.com> On Jun 10, 11:07?am, Thomas Heller wrote: > You need the same compiler that was used to build the > Python that you use. Thanks for the tip. So if I downloaded a binary Python instead of building it from sources, I'm out of luck? From google at mrabarnett.plus.com Tue Jun 3 20:02:54 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 3 Jun 2008 17:02:54 -0700 (PDT) Subject: defaultdict.fromkeys returns a surprising defaultdict References: Message-ID: On Jun 3, 9:11 pm, Matthew Wilson wrote: > I used defaultdict.fromkeys to make a new defaultdict instance, but I > was surprised by behavior: > > >>> b = defaultdict.fromkeys(['x', 'y'], list) > > >>> b > defaultdict(None, {'y': , 'x': }) > > >>> b['x'] > > > >>> b['z'] > ------------------------------------------------------------ > Traceback (most recent call last): > File "", line 1, in > KeyError: 'z' > > I think that what is really going on is that fromdict makes a regular > dictionary, and then hands it off to the defaultdict class. > > I find this confusing, because now I have a defaultdict that raises a > KeyError. > > Do other people find this intuitive? > > Would it be better if defaultdict.fromkeys raised a > NotImplementedException? > > Or would it be better to redefine how defaultdict.fromkeys works, so > that it first creates the defaultdict, and then goes through the keys? > > All comments welcome. If I get some positive feedback, I'm going to try > to submit a patch. > The statement: b = defaultdict.fromkeys(['x', 'y'], list) is equivalent to: b = defaultdict() for i in ['x', 'y']: b[i] = list so there's no default_factory and therefore the defaultdict will behave like a dict. Perhaps there could be an optional third argument to provide a default_factory. From musiccomposition at gmail.com Sat Jun 28 22:39:03 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sat, 28 Jun 2008 19:39:03 -0700 (PDT) Subject: surprising behaviour of os.environ.clear References: <463baf33-e2d5-41fd-839e-aae45ee5433e@b1g2000hsg.googlegroups.com> Message-ID: On Jun 28, 1:23?am, Tim Roberts wrote: > Benjamin wrote: > > >This is because of how os.environ is implement with a UserDict > >subclass. > > Why? ?I mean, I can see that it happens, but I don't understand why being a > UserDict causes this. The contents of a UserDict is stored in UserDict.data. When UserDict.clear is called, that contents is simply cleared. environ needs to override this is to unset env variable and then update the actual dict. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. From cwitts at gmail.com Tue Jun 3 16:18:59 2008 From: cwitts at gmail.com (Chris) Date: Tue, 3 Jun 2008 13:18:59 -0700 (PDT) Subject: defaultdict.fromkeys returns a surprising defaultdict References: Message-ID: On Jun 3, 10:11?pm, Matthew Wilson wrote: > I used defaultdict.fromkeys to make a new defaultdict instance, but I > was surprised by behavior: > > ? ? >>> b = defaultdict.fromkeys(['x', 'y'], list) > > ? ? >>> b > ? ? defaultdict(None, {'y': , 'x': }) > > ? ? >>> b['x'] > ? ? > > ? ? >>> b['z'] > ? ? ------------------------------------------------------------ > ? ? Traceback (most recent call last): > ? ? ? File "", line 1, in > ? ? KeyError: 'z' > > I think that what is really going on is that fromdict makes a regular > dictionary, and then hands it off to the defaultdict class. > > I find this confusing, because now I have a defaultdict that raises a > KeyError. > > Do other people find this intuitive? > > Would it be better if defaultdict.fromkeys raised a > NotImplementedException? > > Or would it be better to redefine how defaultdict.fromkeys works, so > that it first creates the defaultdict, and then goes through the keys? > > All comments welcome. ?If I get some positive feedback, I'm going to try > to submit a patch. > > Matt To me it's intuitive for it to raise a KeyError, afterall the Key isn't in the dictionary. From j2ulia1_n at bellsouth.net Thu Jun 26 23:56:22 2008 From: j2ulia1_n at bellsouth.net (Mr. Juju) Date: Thu, 26 Jun 2008 23:56:22 -0400 Subject: Learning Python in a group In-Reply-To: References: <507738ef0806220343r3e9ea053neeec0baf0ccfdbe6@mail.gmail.com> <18c1e6480806220422x5d06c54byd23b249bb699691f@mail.gmail.com> <507738ef0806220452s74358615v44518469cf3b5f45@mail.gmail.com> <18c1e6480806220511s5117aef4gb4ec93bceb44a0ac@mail.gmail.com> <337ab3f9-5334-4737-baac-fded524e6d99@s50g2000hsb.googlegroups.com> Message-ID: <3wZ8k.13949$PZ6.10656@bignews5.bellsouth.net> Taygun Kekec wrote: > hi guys. > > I would be glad to join your group because i want to learn deeper > python but i am frustrated of isolation too. It would provide > stimulation and encourage to study and will boost our desire to learn. > So count me in! hello all, I just started studying python myself and was looking for a group. I would be happy to join. Count me in. Email me with the details of how you guys want to do this. Cheers From sjmachin at lexicon.net Fri Jun 27 10:08:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 27 Jun 2008 07:08:47 -0700 (PDT) Subject: Simple regular expression References: <47031cc4-2b5e-43b3-9338-cf4a7b4c1568@d45g2000hsc.googlegroups.com> Message-ID: On Jun 28, 12:00 am, python_enthu wrote: > I am trying this.. what is wrong in this.. > > IDLE 1.2.2>>> import re > >>> a="my name is fname lname" > >>> p=re.compile('name') > >>> m=p.match (a) > >>> print p.match(a) > > None > > findall() seems to work > > >>> print p.findall(a) > > ['name', 'name', 'name'] Read the manual section on the difference between match and search. From circularfunc at yahoo.se Mon Jun 23 18:02:35 2008 From: circularfunc at yahoo.se (cirfu) Date: Mon, 23 Jun 2008 15:02:35 -0700 (PDT) Subject: regexp: match only if previous matched? Message-ID: <95ccceb7-c628-49f8-95bc-17f3740b1b27@m3g2000hsc.googlegroups.com> I need to extract prices froma html-document. [0-9]*\$ matches 112$ 45$ etc but also just a $. why that shouldnt really matter and it is unlikely anyway to appear a $sign with no price attahced to it I still want to prevent it. How do I avoid matching "$"? It has to be "nbr$". From agus at cs.its.ac.id Wed Jun 4 09:53:45 2008 From: agus at cs.its.ac.id (agus at cs.its.ac.id) Date: Wed, 4 Jun 2008 20:53:45 +0700 (WIT) Subject: how to combine 2 program? Message-ID: <1371.222.124.226.218.1212587625.squirrel@webmail.its.ac.id> i am a newbe in pyhton. i am using "Twisted Network Programming Essentials By Abe Fettig" as my tutorial. in that tutorial, i found 2 example, IMAPDOWNLOAD.py and requesthandler.py my problem is how to combine those program become one program, so that i can input the imapdownload inputs via web? thanks, Any guidance in this would be greatly appreciated... From jamesd at echeque.com Tue Jun 3 08:29:47 2008 From: jamesd at echeque.com (James A. Donald) Date: Tue, 03 Jun 2008 22:29:47 +1000 Subject: Database Query Contains Old Data References: <33b13117-0f9f-435d-b8f8-19f1ed3a121a@d77g2000hsb.googlegroups.com> <4f0163cc-d943-4204-87e5-880477d6f7e0@f36g2000hsa.googlegroups.com> Message-ID: On Tue, 03 Jun 2008 12:07:07 +0200, "M.-A. Lemburg" wrote: > As others have mentioned, in systems that have long running logical > transactions, it's usually best to collect the data until the very > end and then apply all changes in one go (and one database > transaction). I understand you to mean that one should arrange matters so that what is a lengthy transaction from the point of view of the user is a short transaction from the point of view of the database. -- ---------------------- We have the right to defend ourselves and our property, because of the kind of animals that we are. True law derives from this right, not from the arbitrary power of the omnipotent state. http://www.jim.com/ James A. Donald From ironfroggy at socialserve.com Thu Jun 12 15:07:22 2008 From: ironfroggy at socialserve.com (Calvin Spealman) Date: Thu, 12 Jun 2008 15:07:22 -0400 Subject: cPickle asymptotic performance? In-Reply-To: <1213295145.8320.21.camel@convolution> References: <1213295145.8320.21.camel@convolution> Message-ID: <1556DECB-F959-4B30-BE9E-B2D9A3363111@socialserve.com> If you are getting to the point where your data is large enough to really care about the speed of cPickle, then maybe its time you moved past pickles for your storage format? 2.5 includes sqlite, so you could persist them in a nice, indexed table or something. Just a suggestion. On Jun 12, 2008, at 2:25 PM, Eric Jonas wrote: > Hello, > > I've done some benchmarking while attempting to serialize my (large) > graph data structure with cPickle; I'm seeing superlinear performance > (plotting it seems to suggest n^2 where n is the number of nodes of my > graph), in the duration of the pickle.dump calls and I can't quite > figure out why. The connectivity of the graph is such that the > number of > nodes is ~ number of edges, so I don't think this is a problem of edge > count secretly growing > O(n). Is cPickle's behavior known to be O > (n^2)? > Does anyone have any generic tips for speeding up cPickle? > > Thanks, > ...Eric > > > -- > http://mail.python.org/mailman/listinfo/python-list From lemnitzer at india.com Wed Jun 11 15:06:03 2008 From: lemnitzer at india.com (lemnitzer at india.com) Date: Wed, 11 Jun 2008 12:06:03 -0700 (PDT) Subject: *** Massive Copyright Violation by the US Government *** Message-ID: <06c58239-b892-4e16-b4dc-5a2d9f528946@j22g2000hsf.googlegroups.com> Printing dollar is a copyright violation ---------------------------------------------------- I recently heard that the USA government or the unfederal reserve is printing dollars. Is this a copyright violation ? Is this also a theft ? Is there a scheme to print dollars in such a way to selectively deflate the dollars owned by non-US entities while unaffecting the wealth or wealth ratio of the native population ? Is there a scheme to give people the difference by this method ? Are there any grants or subsidies to implement this scheme/scam ? Lyman L. Lemnitzer Master schemer of Operation Northwoods please look at my favorite websites: http://iamthewitness.com Also look at Painful Deceptions by Alex Jones and Eric Hufschmidt. Do you know if war on terror was genuine, the anthrax mailer would have been caught first ? From maric at aristote.info Tue Jun 24 00:57:56 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 24 Jun 2008 06:57:56 +0200 Subject: Question: How do I format printing in python In-Reply-To: References: Message-ID: <200806240657.57175.maric@aristote.info> Le Tuesday 24 June 2008 05:33:01 Larry Bates, vous avez ?crit?: > joemacbusiness at yahoo.com wrote: ... > > data = '''512 Jun 5 2004 X11r6 > 22 Jan 17 2005 a2p > 22 Jan 17 2005 acctcom > 5374 Sep 15 2002 acledit > 5664 May 13 2004 aclget > 12020 May 13 2004 aclput > 115734 Jun 2 2004 adb > 46518 Jun 4 2004 admin > 66750 Sep 16 2002 ali > 1453 Sep 15 2002 alias > 28150 Jun 4 2004 alog > 15 May 12 2005 alstat > ''' > > for entry in data.rstrip().split('\n'): > items = entry.split(' ') > print "%-6s %3s %2s %4s %-7s" % tuple(items) In python, str objects have a splitlines method for portability it is better, a shorthand for split(os.sep). -- _____________ Maric Michaud From desothier at yahoo.com Thu Jun 26 17:52:50 2008 From: desothier at yahoo.com (antar2) Date: Thu, 26 Jun 2008 14:52:50 -0700 (PDT) Subject: list previous or following list elements Message-ID: Hello Suppose I have a textfile (text1.txt) with following four words: Apple balcony cartridge damned paper bold typewriter and I want to have a python script that prints the words following the word starting with the letter b (which would be cartridge) or differently put, a script that prints the element following a specified element: I am more experienced in Perl, and a beginner in python I wrote a script that - of course - does not work, that should print the element in a list following the element that starts with a b import re f = open('text1.txt', 'r') list1 = [] list2 = [] for line in f: list1.append(line) a = re.compile("^b") int = 0 while(int <= list1[-1]): int = int + 1 a_match = a.search(list1[int]) if(a_match): list2.append(list1[int + 1]) print list2 I did not find information about addressing previous or following list elements. So some help would be magnificent Thanks a lot From deets at nospam.web.de Fri Jun 13 07:47:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 13 Jun 2008 13:47:09 +0200 Subject: HTML FORM AND PYTHON In-Reply-To: References: Message-ID: <6bf522F3bgrvlU1@mid.uni-berlin.de> subhabrata.iisc at hotmail.com schrieb: > Dear Members of the group, > I have a small question, if you can help me to find the answer. > I have one function: > def add_string(n): > print ?Print Two strings? > print ?Print the First String? > a1=raw_input(?PRINT THE FIRST STRING?) > a2=raw_input(?PRINT THE SECOND STRING?) > print ?CONCATENATING THE TWO GIVEN STRINGS? > a3=a1+a2 > print ?THE RESULT IS? > print a3 > > Now, I have designed one HTML form which has two input fields for text > and an output field for the result. > > I like to bind the python program into HTML form. > i) Is there any way I can keep both my existing python code and HTML > code and bind them? If any one can suggest with example. No. The above code works with user-interation at certain points of the program. That can't be (easily, and especially not with the above functionality) translated into the http-paradigm where each operation is embedded into a request/resonse-cycle, with the need for explicit or implicit state-keeping over these cycles. > ii) Do I have to write the whole code in a way in python so that it > would work the function as well as generate HTML form I am looking > for? If any one can suggest with example. For this *trivial* example, I can only say: there isn't enough to be worth abstracting. > iii) Is there any other way? Google python + webframeworks to find a bazillion discussions, opinions, examples. Diez From leodp at yahoo.com Mon Jun 30 04:54:40 2008 From: leodp at yahoo.com (leodp) Date: Mon, 30 Jun 2008 01:54:40 -0700 (PDT) Subject: Getting sorting order Message-ID: <7cb9ebb7-e722-41e1-bdf2-693954a21b92@j22g2000hsf.googlegroups.com> Hi all, I cannot find anything on this: I have a few lists, and would like to sort one of them (sorting-master list). Then I would like to sort all other lists according to how the first one was sorted (sorting-slave lists). Is there a standard way to do that? >From what I know sort() and sorted() do not return the order of sorting. Maybe I have to write some more code. Ciao, leodp From fc14301589 at icqmail.com Mon Jun 2 06:35:02 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Mon, 02 Jun 2008 18:35:02 +0800 Subject: Shed my a light :) Message-ID: <4843ccd7_2@news.tm.net.my> Hi, I using eval for quite strange reason, as long as I don't know a different way to implement. An example: actions= ('print', 'sum', 'divide', 'myfunction') parameters=(5, 'nothing',5.63, object) for routines in actions: routines(parameters) I'd like to note that actions are string or string expressions of the program functions or python itself, so I've in my program something like: for nn in actions: eval('cp.%s' %nn) Where cp is an instance. So I'm asking here whether exist a way that these string become functions inside my program, without using eval() -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From info at egenix.com Thu Jun 12 16:04:55 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Thu, 12 Jun 2008 22:04:55 +0200 Subject: ANN: eGenix pyOpenSSL Distribution 0.7.0-0.9.8h-1 Message-ID: <48518167.4060200@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com pyOpenSSL Distribution Version 0.7.0-0.9.8h-1 An easy to install and use repackaged distribution of the pyOpenSSL Python interface for OpenSSL - available on Windows and Unix platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.7.0-0.9.8h-1-GA.html ________________________________________________________________________ INTRODUCTION The eGenix.com pyOpenSSL Distribution includes everything you need to get started with SSL in Python. It comes with an easy to use installer that includes the most recent OpenSSL library versions in pre-compiled form. pyOpenSSL is an open-source Python add-on (http://pyopenssl.sf.net/). OpenSSL is an open-source implementation of the SSL protocol (http://www.openssl.org/). * About Python: Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. * About eGenix: eGenix is a consulting and software product company focused on providing professional quality services and products to Python users and developers (http://www.egenix.com/). ________________________________________________________________________ NEWS This is the first release of the eGenix.com pyOpenSSL Distribution. It includes pyOpenSSL 0.7.0 and the OpenSSL 0.9.8h libraries on all supported platforms. ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/pyOpenSSL/ ________________________________________________________________________ UPGRADING Before installing this version of pyOpenSSL, please make sure that you uninstall any previously installed pyOpenSSL version. Otherwise, you could end up not using the included OpenSSL libs. _______________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jun 12 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania 24 days to go :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From timr at probo.com Sun Jun 29 23:36:36 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 30 Jun 2008 03:36:36 GMT Subject: frame grabber hardware References: Message-ID: rubbishemail at web.de wrote: > >can anybody recommend a simple USB or PCI framegrabber with video >input that runs under xp and has a python driver available? I just >want to get the image into a file, no special requirements. There are a vast range of inexpensive web cams that will do this job. Logitech makes a bunch. Most of the cheap imported still cameras can also do it. The Disney still cams at Target (made by Digital Blue) would work. Are you looking for something more industrial? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gherron at islandtraining.com Sun Jun 22 14:57:18 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 22 Jun 2008 11:57:18 -0700 Subject: -1/2 In-Reply-To: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> References: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> Message-ID: <485EA08E.9080705@islandtraining.com> Serve Lau wrote: > What is the expected result of -1/2 in python? > > -- > http://mail.python.org/mailman/listinfo/python-list From the manual: The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Gary Herron From roy at panix.com Tue Jun 24 09:19:51 2008 From: roy at panix.com (Roy Smith) Date: Tue, 24 Jun 2008 09:19:51 -0400 Subject: Python 3000 vs Perl 6 References: Message-ID: In article , Nick Craig-Wood wrote: > The fact that > it still hasn't been released after 8 years of development (Larry > announced it in his State of the Onion speech in 2000 I think) makes > me think that I made the right choice. Sometimes you gotta be patient. Wine took 15 years (http://www.winehq.org/?announce=1.0). Not that I'm supporting Perl 6, just saying that gestation time is not always an indicator of value :-) From spectrumdt at gmail.com Wed Jun 4 08:57:20 2008 From: spectrumdt at gmail.com (spectrumdt at gmail.com) Date: Wed, 4 Jun 2008 05:57:20 -0700 (PDT) Subject: Trying to extend Python with C: undefined reference to `Py_BuildValue' Message-ID: <045458d3-771b-459d-b5ef-21d8f3c08659@2g2000hsn.googlegroups.com> Hello. I am trying to extend Python with some C code. I made a trivial "Hello World" program in C that I am trying to wrap in "boilerplate" for inclusion in a Python program. But I can't compile the C code. The C compiler cannot find the required function `Py_BuildValue'. My C code looks like this: #include "/usr/include/python2.5/Python.h" /* Python wrapper for 'main'. */ static PyObject* mpi_main() { int res = main(); PyObject* retval = (PyObject*)Py_BuildValue("i",res); } /* Main. A 'Hello World' function. */ int main() { printf ("Hello, World. I am a C function.\n"); } And my error message looks like this: [ore at localhost Opgave03]$ gcc ctest.c /tmp/ccH46bs8.o: In function `mpi_main': ctest.c:(.text+0x1d): undefined reference to `Py_BuildValue' collect2: ld returned 1 exit status [ore at localhost Opgave03]$ I searched the newsgroup and found this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c6d70e02a6bc9528/87b836f369bd0042?lnk=gst&q=undefined+reference+to+%60Py_BuildValue%27#87b836f369bd0042 It recommended that I add the option "-Wl,--export-dynamic" when calling gcc. That makes no difference. The thread also has some more stuff that I don't quite understand. Can anyone help? I am including Python.h, so why does it not find Py_BuildValue? Thanks in advance. From Lie.1296 at gmail.com Mon Jun 23 09:16:49 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 23 Jun 2008 06:16:49 -0700 (PDT) Subject: -1/2 References: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> Message-ID: <2231475d-c1d6-45de-9ccb-ab82e923e902@x1g2000prh.googlegroups.com> On Jun 23, 1:32?am, "Serve Lau" wrote: > What is the expected result of -1/2 in python? Operator precedence: Both python 2 and 3 follows the same rule for operator precedence, see: http://www.ibiblio.org/g2swap/byteofpython/read/operator-precedence.html . In -1/2, unary negative takes precedence, then division, i.e. it's interpreted as ((-1) / 2). Py3k and Python 2 differences: Before Python 3, integer division is always rounds to minus infinity. In Python 3, integer division yields floats. To use integer division in Python 3, you use // operator. Simple answer: Python 2: (-1)/2 = round(-0.5) = -1 Py3k: (-1)/2 = float(-1) / float(2) = -0.5 From fuzzyman at gmail.com Thu Jun 12 09:34:10 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Thu, 12 Jun 2008 06:34:10 -0700 (PDT) Subject: Plotting Graphs using Gnuplot References: <17f71342-0cc4-4eea-b99a-668096302b8b@a70g2000hsh.googlegroups.com> Message-ID: On Jun 12, 12:30 pm, arslanbur... at gmail.com wrote: > Hello. Was trying to create a simple plotting function. Wasnt working > however. If i write the same code without putting it inside a function > it works. :S. Could some1 tell me the problem? Heres the code: > > # File name Plotting2 > > import Gnuplot > > def plot(original, expected, actual): > > if type (original) != type([]): > return False > > else: > > gp = Gnuplot.Gnuplot() > gp('set data style lines') > > # Make the plot items > plot1 = Gnuplot.PlotItems.Data(original, title="Original") > plot2 = Gnuplot.PlotItems.Data(expected, title="Expected") > plot3 = Gnuplot.PlotItems.Data(actual, title="Acutal") > > return gp.plot(plot1, plot2, plot3) > > ---- > > import Plotting2 #The name of my file... > > Plotting2.plot( [(2,3), (3,4)], [(4,5), (5,6)], [(1,3), (4,8)] ) I've no idea about the answer to your question (I don't know how the Gnuplot module works and I can't *see* anything obviously wrong with your code), but this line: if type (original) != type([]) is better written: if not isinstance(original, list): Michael Foord http://www.ironpythoninaction.com/ From paul at boddie.org.uk Fri Jun 13 15:49:23 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 13 Jun 2008 12:49:23 -0700 (PDT) Subject: python screen scraping/parsing References: Message-ID: On 13 Jun, 20:10, "bruce" wrote: > > url ="http://www.pricegrabber.com/rating_summary.php/page=1" [...] > tr = > "/html/body/div[@id='pgSiteContainer']/div[@id='pgPageContent']/table[2]/tbo > dy/tr[4]" > > tr_=d.xpath(tr) [...] > my issue appears to be related to the last "tbody", or tbody/tr[4]... > > if i leave off the tbody, i can display data, as the tr_ is an array with > data... Yes, I can confirm this. > with the "tbody" it appears that the tr_ array is not defined, or it has no > data... however, i can use the DOM tool with firefox to observe the fact > that the "tbody" is there... Yes, but the DOM tool in Firefox probably inserts virtual nodes for its own purposes. Remember that it has to do a lot of other stuff like implement CSS rendering and DOM event models. You can confirm that there really is no tbody by printing the result of this... d.xpath("/html/body/div[@id='pgSiteContainer']/ div[@id='pgPageContent']/table[2]")[0].toString() This should fetch the second table in a single element list and then obviously give you the only element of that list. You'll see that the raw HTML doesn't have any tbody tags at all. Paul From swapan02 at yahoo.co.uk Wed Jun 25 08:01:16 2008 From: swapan02 at yahoo.co.uk (Swapan) Date: Wed, 25 Jun 2008 18:01:16 +0600 Subject: Plz decompyle my file Message-ID: <989568.3353.bm@omp218.mail.ukl.yahoo.com> A non-text attachment was scrubbed... Name: Sticker.pyc Type: application/octet-stream Size: 19693 bytes Desc: not available URL: From bsagert at gmail.com Tue Jun 10 12:00:39 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Tue, 10 Jun 2008 09:00:39 -0700 (PDT) Subject: Python doesn't understand %userprofile% References: Message-ID: <5c1614dc-654d-4fbc-bd9f-140f37545858@f24g2000prh.googlegroups.com> On Jun 10, 8:56 am, bsag... at gmail.com wrote: > In xp when I try os.path.getmtime("%userprofile/dir/file%") Python > bites back with "cannot find the path specified" Since my script has > to run on machines where the username is unspecified I need a fix. > Thanks in advance. oops that should be os.path.getmtime("%userprofile%/dir/file") From termim at gmail.com Mon Jun 30 13:19:07 2008 From: termim at gmail.com (Mike) Date: Mon, 30 Jun 2008 10:19:07 -0700 (PDT) Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> Message-ID: On Jun 30, 10:57?am, Bruno Desthuilliers wrote: > > Some (if not most) templating systems use their own mini-language to > handle presentation logic. > IMHO this is the funniest (worst) part of all this 'templating' buss :) It reminds me the good old slogan: "Have you invented your own GUI library yet?" > > The meme "thou shall not mix domain logic with presentation" is very > often misunderstood as "you must not have anything else than html in > templates", which is just plain non-sense. Even declarative templating > systems (cf Has's post) require some special (ie: non standard) stuff to > work. > > > Or could it just be that > > this is a *good* way to mix HTML and Python, and there are other ways > > which may be bad? > > Bingo. > Then what is so *good* about it, why embedding HTML into Python is not good? Mikhail +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++ Q: What one would get after crossing a snake and a hedgehog? A: A barbed wire metre. From sjmachin at lexicon.net Fri Jun 13 10:34:07 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 13 Jun 2008 07:34:07 -0700 (PDT) Subject: Create list from string References: Message-ID: <8863b69c-eb18-4bf4-8c85-e7e3420a1971@s50g2000hsb.googlegroups.com> On Jun 14, 12:15 am, ericdaniel wrote: > Hi, > > I'm new to Python and I need to do the following: > > from this: s = "978654321" > to this : ["978", "654", "321"] > > Any help is appreciated > Homework? Have you read the Python tutorial (section 3.1.2 Strings)? From tjreedy at udel.edu Sun Jun 29 18:44:50 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 29 Jun 2008 18:44:50 -0400 Subject: Function to import module to namespace In-Reply-To: References: Message-ID: bvdp wrote: > > Is it possible to do this from a function: import a module and append > the defs in that module to an existing module/namesapce. > > So, in my code I have something like: > > # main code > import mods > > def loadmore(n): > import_module(n, mods) > > .... > # end of main > > this will permit the addition of the the stuff in file 'n.py' to 'mods'. > > Assuming that foo1() is defined in newmod, I should now be able to do > something like mods.foo1(). Do you mean something like this? >>> import string >>> dir(string) ['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'maketrans', 'octdigits', 'printable', 'punctuation', 'whitespace'] >>> import math >>> math.__dict__.update(string.__dict__) >>> dir(math) ['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_multimap', '_re', 'acos', 'acosh', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'capwords', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'digits', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'hexdigits', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10', 'log1p', 'maketrans', 'modf', 'octdigits', 'pi', 'pow', 'printable', 'punctuation', 'radians', 'sin', 'sinh', 'sqrt', 'sum', 'tan', 'tanh', 'trunc', 'whitespace'] tjr From lajam at caramail.com Fri Jun 27 09:34:39 2008 From: lajam at caramail.com (lajam at caramail.com) Date: Fri, 27 Jun 2008 06:34:39 -0700 (PDT) Subject: where is the error? References: <8f8e1bf7-78b0-4292-9d56-396527b9dfb1@z66g2000hsc.googlegroups.com> <15ea1cb1-76a3-4fd3-8e4c-521b9aefcca2@m3g2000hsc.googlegroups.com> Message-ID: <5c465332-41c5-4fef-b8b1-46d4fefe9ea8@34g2000hsh.googlegroups.com> > > I think that you mean that diff_temp will be an array of the numberS > (plural) of the lines (rows?) in values array that met the -2 < x < 2 > criterion. Now you want to be able to use diff_temp to get the > corresponding subset of some other array. Am I getting close? I think that you're getting close. I want to get the lines that met the criterion. Diff_temp is an array containing the values of the lines. So bascially, > Now you want to be able to use diff_temp to get the corresponding > subset of some other array. Am I getting close? yes > Perhaps you need something like other_array.take(diff_temp) ? And my problem was that the commands worked on windows but not on linux. > By the way, shouldn't you be using numpy? I thought numarray was going > away by mid-2008 i.e. now. I know, but i'm not sure that it's the problem. Thanks Cedric From Lie.1296 at gmail.com Tue Jun 3 08:27:47 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 3 Jun 2008 05:27:47 -0700 (PDT) Subject: make a string a list References: Message-ID: On May 30, 4:30?am, Nikhil wrote: > or a string iterable ? How can I do that. I have lots of '\r\n' > characters in the string which I think can be easier if it were made > into a list and I can easily see if the required value (its a numeral) > is present in it or not after some position or after some characters' > position. > > Thanks, > Nikhil Isn't it already iterable? And combined with str.split(), it could be line iterable too. From CRhode at LacusVeris.com Fri Jun 27 00:22:10 2008 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Thu, 26 Jun 2008 23:22:10 -0500 Subject: Web Crawler - Python or Perl? References: <3KCdnRd_48Ye5czVnZ2dnUVZ_srinZ2d@posted.excelnet> Message-ID: On Sun, 22 Jun 2008 10:47:59 -0700, subeen wrote: > You can avoid the problem using the following code: > import socket > timeout = 300 # seconds > socket.setdefaulttimeout(timeout) Yes, I tried that, too, but I forget what went wrong with it. Perhaps, the socket kept up the handshake even though the download stalled. -- .. Chuck Rhode, Sheboygan, WI, USA .. 1979 Honda Goldwing GL1000 (Geraldine) .. Weather: http://LacusVeris.com/WX .. 73? ? Wind Calm From fc14301589 at icqmail.com Tue Jun 3 05:02:43 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Tue, 03 Jun 2008 17:02:43 +0800 Subject: ConfigObj quoting issues References: Message-ID: <484508b3_2@news.tm.net.my> On 14:25, marted? 03 giugno 2008 Roopesh wrote: > This error is because of the presence of \', \", \n etc. > > I had to do the following to make it work. > address[i].replace("\'",'').replace('\"','').replace('\n','') > it's rather ugly :) I suggest use re module as follow: import re address[i] = re.sub('(`|"|\n)',re.MULTILINE,address[i]) if you've a big chunck of email it'd be fine to compile the regex. match = re.compile(`|"|\n) address[i] = match.sub(address[i]) I think there would be a problem with unicode email addresses. But I doubt the existance of unicode addresses nowadays. Unsure for the syntax, pls check http://www.python.org/doc/2.4/lib/re-syntax.html ^^^ according your version, but they're quite the same -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From cokofreedom at gmail.com Tue Jun 24 07:57:54 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 24 Jun 2008 04:57:54 -0700 (PDT) Subject: binary representation of an integer References: <14e14b5e-ce39-414a-a450-7c81baaabc3a@79g2000hsk.googlegroups.com> Message-ID: <7c3ebcd1-709c-4763-987f-39c224a17dc0@m44g2000hsc.googlegroups.com> On Jun 24, 10:38 am, Mark Dickinson wrote: > On Jun 24, 9:03 am, eliben wrote: > > > What would be the quickest way to do this ? I think that for dec2bin > > conversion, using hex() and then looping with a hex->bin lookup table > > would be probably much faster than the general baseconvert from the > > recipe. > > I suspect you're right, but it would be easy to find out: just > code up the hex->bin method and use the timeit module to do some > timings. Don't forget to strip the trailing 'L' from hex(n) if n > is a long. > > If you're prepared to wait for Python 2.6, or work with the beta > version, then the conversion is already there: > > Macintosh-3:trunk dickinsm$ ./python.exe > Python 2.6b1+ (trunk:64489, Jun 23 2008, 21:10:40) > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin > Type "help", "copyright", "credits" or "license" for more information.>>> bin(13) > > '0b1101' > > Interestingly, unlike hex and oct, bin doesn't add a trailing > 'L' for longs: > > >>> bin(13L) > > '0b1101' > > I wonder whether this is a bug... > > Mark Strange in 2.6, but I know at least in 3.0 that all integers are C Long's now, so the L is no longer required. From jeffober at gmail.com Thu Jun 26 07:32:54 2008 From: jeffober at gmail.com (Jeff) Date: Thu, 26 Jun 2008 04:32:54 -0700 (PDT) Subject: Threads, GIL and re.match() performance References: Message-ID: <167a5850-bd0b-41c0-a697-4bbb7a04d7f1@l64g2000hse.googlegroups.com> > However, I assumed that calls to (thread safe) C Library functions > release the global interpreter lock. This is mainly applicable to external C libraries. The interface to them may not be thread-safe; anything that uses the Python API to create/manage Python objects will require use of the GIL. So the actual regex search may release the GIL, but the storing of results (and possibly intermediate results) would not. From bjourne at gmail.com Sat Jun 7 10:56:16 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sat, 7 Jun 2008 16:56:16 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> Message-ID: <740c3aec0806070756m4a5823adxb4210fb5ad62beeb@mail.gmail.com> On Wed, Jun 4, 2008 at 2:02 PM, Antoon Pardon wrote: > Now of course noone would defend such a limitation on the grounds > that one doesn't need the general case and that the general case > will only save you some vertical space. > > But when it came to the ternary operator that was exactly the > argument used, to defend the lack of it. As far as I remember, the primary motivation was developers experience with the ternary operator in other languages, especially C, where it was found to hurt readability. At least in my experience, it is much much more common to see the ternary operator making code more obfuscated than easing readability. Time will tell if Python's if-else expression will be abused in the same way. -- mvh Bj?rn From ptmcg at austin.rr.com Sat Jun 7 17:52:59 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 7 Jun 2008 14:52:59 -0700 (PDT) Subject: Need help porting Perl function References: Message-ID: <9320c3dc-97bc-49f3-8e0b-f22bde49eca9@59g2000hsb.googlegroups.com> On Jun 7, 1:24?pm, kj wrote: > The original Perl function takes a reference to an array, removes > from this array all the elements that satisfy a particular criterion, > and returns the list consisting of the removed elements. ?Hence > this function returns a value *and* has a major side effect, namely > the target array of the original argument will be modified (this > is the part I suspect may be un-Pythonic). > > Can a Python function achieve the same effect? ?If not, how would > one code a similar functionality in Python? ?Basically the problem > is to split one list into two according to some criterion. > If you want to avoid side-effects completely, return two lists, the list of matches and the list of non-matches. In this example, partition creates two lists, and stores all matches in the first list, and mismatches in the second. (partition assigns to the associated element of retlists based on False evaluating to 0 and True evaluating to 1.) def partition(lst, ifcond): retlists = ([],[]) for i in lst: retlists[ifcond(i)].append(i) return retlists[True],retlists[False] hasLeadingVowel = lambda x: x[0].upper() in "AEIOU" matched,unmatched = partition("The quick brown fox jumps over the lazy indolent dog".split(), hasLeadingVowel) print matched print unmatched prints: ['over', 'indolent'] ['The', 'quick', 'brown', 'fox', 'jumps', 'the', 'lazy', 'dog'] -- Paul From sjmachin at lexicon.net Tue Jun 17 22:56:49 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 17 Jun 2008 19:56:49 -0700 (PDT) Subject: Annoying message when interrupting python scripts References: <578d1ef8-231b-46fa-a181-e320fe1cc368@s33g2000pri.googlegroups.com> <87y753wk9a.fsf@benfinney.id.au> Message-ID: <1729bb65-0d3c-4407-858b-3816e19a46a3@d19g2000prm.googlegroups.com> On Jun 18, 12:26 pm, Ben Finney wrote: > John Machin writes: > > On Jun 18, 12:51 am, geoffbache wrote: > > [snip] > > > Is this a bug? I couldn't find any code, but I imagine something like > > > try: > > > import site > > > except: > > > sys.stderr.write("import site failed; use -v for traceback\n") > > > > which should surely allow a KeyboardInterrupt exception through? > > > Surely?? A bare "except" catches *all* remaining uncaught exceptions. > > I parsed that "should" as "this should be changed". > > > Allowing a KeyboardInterrupt exception through would require: > > except KeyboardInterrupt: > > pass > > Actually, to allow it through would require re-raising it: > > except KeyboardInterrupt: > raise > > Yes, I think that's what Geoff is saying "should" be done :-) And all of what he was saying or not saying or should have been saying was prefaced by "I imagine" anyway :-) From tjreedy at udel.edu Thu Jun 26 01:35:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 26 Jun 2008 01:35:15 -0400 Subject: Problem found in tutorial In-Reply-To: <440eb224-e49f-47a5-bfc3-45e1820af7ba@k37g2000hsf.googlegroups.com> References: <001001c8d669$36b06860$6401a8c0@28ghz> <440eb224-e49f-47a5-bfc3-45e1820af7ba@k37g2000hsf.googlegroups.com> Message-ID: Benjamin wrote: > On Jun 25, 2:09 pm, Terry Reedy wrote: >> John W. Hamill wrote: >>> C:\__jh\ftp\python\2_5_2\doc\tutorial\node11.html >> When reporting doc bugs, it is a good idea to check the most recent >> version. The 3.0 version has the same problems (no changes have been >> made -- page and graduates are still undefined), so report that too. > > Changes to the 2.6 docs will be propagated to 3.0, so it's usually not > an issue. Let me rephrase my comment. Because charges are so propagated, the absence of change in 3.0 implies the absence of change in 2.6 (and probably in the development version of 2.5.3.) Therefore, the bug has not been fixed and it would be appropriate to report it. When people report but based on older versions, it is not uncommon for that they have already been fixed. From michalis.avraam at gmail.com Fri Jun 20 12:43:41 2008 From: michalis.avraam at gmail.com (michalis.avraam at gmail.com) Date: Fri, 20 Jun 2008 09:43:41 -0700 (PDT) Subject: Python "is" behavior References: Message-ID: <7578bd5a-c46c-4b29-a792-5b82513d68c7@s21g2000prm.googlegroups.com> On Jun 20, 9:38?am, Jean-Paul Calderone wrote: > On Fri, 20 Jun 2008 09:31:57 -0700 (PDT), michalis.avr... at gmail.com wrote: > >I am not certain why this is the case, but... > > >>>> a = 256 > >>>> b = 256 > >>>> a is b > >True > > >>>> a = 257 > >>>> b = 257 > >>>> a is b > >False > > >Can anyone explain this further? Why does it happen? 8-bit integer > >differences? > > http://mail.python.org/pipermail/python-list/2001-November/113994.html > > Jean-Paul Thank you for this Jean-Paul. I did know about the identity of objects, but my curiosity is based on the 256 number. Are the 2^8 integers cached due to the internal loops, or is there any other specific reason? Is this something that can be controlled? From asmodai at in-nomine.org Thu Jun 19 15:56:22 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 19 Jun 2008 21:56:22 +0200 Subject: Extending Python with C: Cannot find MPI library In-Reply-To: <80244b16-e2c5-4f4c-98d6-6101b004eb3c@26g2000hsk.googlegroups.com> References: <9100a146-a0bb-4958-a7c6-f23c9b518e89@a1g2000hsb.googlegroups.com> <80244b16-e2c5-4f4c-98d6-6101b004eb3c@26g2000hsk.googlegroups.com> Message-ID: <20080619195622.GM97799@nexus.in-nomine.org> -On [20080619 17:11], Spectrum (spectrumdt at gmail.com) wrote: > ImportError: dynamic module does not define init function Might be it's looking, but not finding, something like crti.S or the likes, the C runtime files that specify stuff like _init and _fini. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B If you understand, things are as they are; if not, things are as they are... From dullrich at sprynet.com Wed Jun 4 12:21:36 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Wed, 04 Jun 2008 11:21:36 -0500 Subject: re Message-ID: Actually using regular expressions for the first time. Is there something that allows you to take the union of two character sets, or append a character to a character set? Say I want to replace 'disc' with 'disk', but only when 'disc' is a complete word (don't want to change 'discuss' to 'diskuss'.) The following seems almost right: [^a-zA-Z])disc[^a-zA-Z] The problem is that that doesn't match if 'disc' is at the start or end of the string. Of course I could just combine a few re's with |, but it seems like there should (or might?) be a way to simply append a \A to the first [^a-zA-Z] and a \Z to the second. -- David C. Ullrich From tjreedy at udel.edu Sat Jun 21 19:11:11 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 21 Jun 2008 19:11:11 -0400 Subject: trying to find a substring in a string In-Reply-To: <545db0b5-74e0-4af8-888d-a1579e8e04fa@s21g2000prm.googlegroups.com> References: <545db0b5-74e0-4af8-888d-a1579e8e04fa@s21g2000prm.googlegroups.com> Message-ID: barnacle.steve at gmail.com wrote: > I'm trying to write what should be a simple script in Python, which > I've never ever used before. > > Essentially, I have a text file that has a list of full path file > names to other files, separated by carriage returns. > Contents of first file: > c:\blah.txt > c:\blah1.txt > c:\blah2.txt > > The goal is for the user to specify another file, and then search the > specified file for instances of files from the first file. > Contents of user specified file: > file = "c:\blah.txt" > file = "c:\blah1.txt" > > My goal is for the program to tell me that it found c:\blah.txt and c: > \blah1.txt. > > I've read the contents of the existing file into an array, where each > element is a line from the file. Put each stripped (to delete \n) line into a set. Then parse out the filenames and check that they are in the set. Something like def getname(line): Hi, is there any way to get unbuffered stdout/stderr without relying on the -u flag to python or calling .flush() on each print (including indirect hacks like replacing sys.stdout with a wrapper that succeeds each write() with a flush())? Thanks in advance! -- Yang Zhang http://www.mit.edu/~y_z/ From joe.p.cool at googlemail.com Fri Jun 27 17:05:58 2008 From: joe.p.cool at googlemail.com (Joe P. Cool) Date: Fri, 27 Jun 2008 14:05:58 -0700 (PDT) Subject: surprising behaviour of os.environ.clear Message-ID: If I call os.environ.clear in a python program child processes still see the deleted entries. But when I iterate over the keys like so names = os.environ.keys for k in names: del os.environ[k] then the entries are also deleted for the child processes. Where is the difference? Is this a bug? (Observed in Python 2.5.2) -- Joe From casey.mcginty at gmail.com Thu Jun 5 16:41:32 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Thu, 5 Jun 2008 10:41:32 -1000 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: <484808F7.5040203@arimaz.com> References: <484808F7.5040203@arimaz.com> Message-ID: On Thu, Jun 5, 2008 at 5:40 AM, Gabriel Rossetti < gabriel.rossetti at arimaz.com> wrote: > Hello everyone, > > I had read somewhere that it is preferred to use self.__class__.attribute > over ClassName.attribute to access class (aka static) attributes. I had done > this and it seamed to work, until I subclassed a class using this technique > and from there on things started screwing up. I finally tracked it down to > self.__class__.attribute! What was happening is that the child classes each > over-rode the class attribute at their level, and the parent's was never > set, so while I was thinking that I had indeed a class attribute set in the > parent, it was the child's that was set, and every child had it's own > instance! Since it was a locking mechanism, lots of fun to debug... So, I > suggest never using self.__class__.attribute, unless you don't mind it's > children overriding it, but if you want a truly top-level class attribute, > use ClassName.attribute everywhere! > > I wish books and tutorials mentioned this explicitly.... > > Gabriel > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks for the info. Can anyone explain more about the differences between the two techniques? Why does one work and the other one fail? Casey -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Sun Jun 8 17:42:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 08 Jun 2008 23:42:47 +0200 Subject: Q re documentation Python style In-Reply-To: References: Message-ID: <6b322oF39l6tfU1@mid.uni-berlin.de> > I guess this is a rambling way to ask: are docstrings *it* as far > Python documentation goes? Or is there a second, more flexible > system? Docstrings are it. Yet there are several ways how their content is interpreted. Google for example epydoc. You can embed links that way. I don't know perl, and even less it's documentation system. Yet I wonder: *where* do you put your function documentation, if not at the function? And if it is some sort of link (I guess it must be, or do you declare function docs totally unrelated to the functions themselves?), I have to say - I'd rather open the sourcefile and see what a function is about than having to manually follow links. Diez From joamag at gmail.com Sat Jun 21 09:26:53 2008 From: joamag at gmail.com (joamag) Date: Sat, 21 Jun 2008 06:26:53 -0700 (PDT) Subject: Way to unblock sys.stdin.readline() call Message-ID: <56b21108-45b4-4b9e-bda5-171c9ddc21ce@i76g2000hsf.googlegroups.com> HI, Is there any possible way to unblock the sys.stdin.readline() call from a different thread. Something like sys.stdin.write() but that would actually work ... something to put characters in the stdin... Thanks in advance, Jo?o From bruno.desthuilliers at gmail.com Sat Jun 14 16:13:47 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sat, 14 Jun 2008 13:13:47 -0700 (PDT) Subject: Comments on my first script? References: <7e3a7c92-6204-46dd-8df8-90218f2fb314@26g2000hsk.googlegroups.com> <48522d35$0$10417$426a74cc@news.free.fr> Message-ID: <4161e23f-7109-4f30-9e57-ad8cb905f1ed@a70g2000hsh.googlegroups.com> On 13 juin, 13:39, "D'Arcy J.M. Cain" wrote: > On Fri, 13 Jun 2008 10:19:38 +0200 > > Bruno Desthuilliers wrote: > > Ok, since you asked for it, let's go: > > Good commentary. One small improvement: > > > REC_CLEANERS = { > > '.net' : clean_net, > > '.com' : clean_com, > > '.tv' : clean_net, > > '.uk' : clean_co_uk, > > (etc...) > > } FWIW, the keys should not start with a '.'. My fault... > > for domain in rec: > > # code here > > ext = domain.rsplit('.', 1)[1] > > cleaner = REC_CLEANERS.get(ext, None) > > if cleaner: > > rec = cleaner(rec) > > How about this? > > for domain in rec: > # code here > ext = domain.rsplit('.', 1)[1] > rec = REC_CLEANERS.get(ext, lambda x: x) Depends on if you want to know if there's a match or if you just don't care. > I suppose you could predefine the default function as well. Yeps. That's usually what I do when I end up using the above variant more than once in a module. From alexnbryan at gmail.com Tue Jun 10 20:15:02 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 10 Jun 2008 17:15:02 -0700 (PDT) Subject: problems with opening files due to file's path In-Reply-To: References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> Message-ID: <17767518.post@talk.nabble.com> I am using GUI, Tkinter to be exact. But regardless of how the path gets there, it needs to opened correctly. The problem I am running into is that the program receives a path of a file, either .wma or .mp3 and is supposed to open it. I run into problems when there is either a ")" or a number next to the backslash "\" in the file path. I am looking for a way to make it work with a variable, I can make it work when I physically type it in, but not with a variable that holds the path. Mike Driscoll wrote: > > On Jun 10, 1:57?pm, Alexnb wrote: >> That would work, but not for what I want. See the file could be anywhere >> on >> the user's system and so the entire path will be unique, and that didn't >> work with a unique path. What is the subprocess module you are talking >> about? >> > > > > > As Carsten pointed out, we don't really know what you're doing. Or at > least, I don't. Why do you even want to do string substitution? How > does the user navigate to the files that the user wants to open? Are > you using a GUI or a command line interface? > > Anyway, Google is your friend. Searching for "python subprocess" gives > you this: > > http://docs.python.org/lib/module-subprocess.html > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17767518.html Sent from the Python - python-list mailing list archive at Nabble.com. From robert.kern at gmail.com Tue Jun 24 16:09:48 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 24 Jun 2008 15:09:48 -0500 Subject: Wrap Numpy with Cython? In-Reply-To: References: Message-ID: martin.nordstrom87 at gmail.com wrote: > Hi! I'm trying to wrap numpy with Cython and I've tried to use this > guide to manage this: http://wiki.cython.org/WrappingNumpy > However when I send an array to mysum() it gives me the right answer > only when dtype of the array is float, otherwise it gives me random > answers. The problem may be that the array is converted to a C double > which is just as long as float for Numpyarrays and therefore it works > only when the dtype is float. How do I make a Numpywrapper that works > with an arbitrary dtype? You will need a Cython function for each dtype and dispatch based on the dtype. You will want to ask further numpy questions on the numpy mailing list: http://www.scipy.org/Mailing_Lists -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From duncan.booth at invalid.invalid Wed Jun 25 16:21:27 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Jun 2008 20:21:27 GMT Subject: Functions that raise exceptions. References: <13e5337e-e889-4c50-8d77-2b8be6442e13@w7g2000hsa.googlegroups.com> Message-ID: Alex G wrote: > Does anyone know how I would go about conditionally raising an > exception in a decorator (or any returned function for that matter)? > For example: > > def decorator(arg): > def raise_exception(fn): > raise Exception > return raise_exception > > class some_class(object): > @raise_exception > def some_method(self) > print "An exception should be raised when I'm called, but not > when I'm defined" > > The intent of the above code is that an exception should be raised if > some_method is ever called. It seems, however, since the decorator > function is executed on import, the raise statement is executed, and I > the exception gets thrown whenever the module is imported, rather than > when the method is called. Does anyone have a clue how I might go > about doing this? Well, the simplest way would be to correct the syntax error in your class definition and to try calling the decorator you defined instead of calling the undefined 'raise_exception'. Fix both of those and the code you posted works 'as is'. >>> def decorator(arg): def raise_exception(fn): raise Exception return raise_exception >>> class some_class(object): @decorator def some_method(self): print "An exception should be raised when I'm called, but not when I'm defined" >>> some_class().some_method() Traceback (most recent call last): File "", line 1, in some_class().some_method() File "", line 3, in raise_exception raise Exception Exception >>> From m6d04a5.3.calrobert at spamgourmet.com Thu Jun 5 01:39:22 2008 From: m6d04a5.3.calrobert at spamgourmet.com (Robert Maas,) Date: Wed, 04 Jun 2008 22:39:22 -0700 Subject: The Importance of Terminology's Quality References: Message-ID: > From: dkco... at panix.com (David Combs) > Lisp is *so* early a language (1960?), preceeded mainly only by > Fortran (1957?)?, and for sure the far-and-away the first as a > platform for *so many* concepts of computer-science, eg lexical vs > dynamic ("special") variables, passing *unnamed* functions as > args ... maybe is still the only one in which program and data > have the same representation -- that it'd seem logical to use it's > terminology in all languages. Yeah, but why did you cross-post to so many newsgroups? Are you trying to run a flame war between advocates of the various languages? (Same accusation to the OP moreso!) > From C is the very nice distinction between "formal" and "actual" args. I think Lisp already had that nearly 50 years ago. Function definition (lambda expression) has formal args, EVAL recursively calls EVAL on sub-forms to create actual args and calls APPLY on them and whatever function is named in the CAR position of the form. Whether anybody bothered to use that specific jargon, or it was just so obvious it didn't need jargon, I don't know. > And from algol-60, own and local -- own sure beats "static"! Yeah. But now that you mention it and I think about it, what's really meant is "private persistent". Global variables are public persistent. Local variables and formal args to functions are private transient (they go away as soon as the function returns). but OWN variables are private to the function but stay around "forever" just like globals do, so that side effects on the OWN variables that occurred during one call can persist to affect the next call. Lexical closures in Common Lisp go one step further, allowing private persistent variables to be shared between several functions. All those functions share access to the private variable which they co-OWN. Another way in which OWN or lexical-closure variables aren't like what the word "own" means in ordinary language is that it's possible to transfer ownership by selling or giving something to somebody else, but not with OWN variables or lexical-closure variables. So even though I like the word OWN better than the word STATIC for this meaning, I'm not totally comfortable with that jargon. But "persistent private" is a mouthful compared to "OWN", and I doubt anyone can find a word of appx. 3 characters that conveys the intended meaning so we're probably stuck with "OWN" as the best short term. From drobinow at gmail.com Wed Jun 4 12:54:20 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Wed, 4 Jun 2008 09:54:20 -0700 (PDT) Subject: Batch-print bunch of RTF files? References: Message-ID: On Jun 4, 12:26 pm, "nos... at nospam.com" wrote: > Hello, > > I have about two hundred individual RTF files to print from an > XP host. Word 2000 doesn't seem to have this feature, so I'm looking > for a way to print those RTF files from an ActivePython script. Would > someone have some working code handy? > > Thank you. The code below will print one file from your current directory to the default printer. You should be able to tweak it to your needs. import sys import os from win32com.client import Dispatch MYDIR = os.getcwd() + '/' myWord = Dispatch('Word.Application') myWord.Visible = 1 # comment out for production myDoc = myWord.Documents.Open(MYDIR + sys.argv[1]) myDoc.PrintOut() myDoc.Close() From pavlovevidence at gmail.com Thu Jun 19 22:24:46 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 19 Jun 2008 19:24:46 -0700 (PDT) Subject: At long last... References: Message-ID: On Jun 19, 10:17 pm, Terry Reedy wrote: > Carl Banks wrote: > > Tuples will have an index method in Python 2.6. > > > I promise I won't indiscriminately use tuples for homogenous data. > > Honest. Scout's honor. Cross my heart. > > Use them as you want. This change came about because .index was > included in the 3.0 Sequence ABC (abstract base class) and tuple was > included as a sequence, so .... something had to give. The result was > tuple getting the full suite of immutable sequence methods. And then > there was no good reason to not backport ;-). The last time I needed index on a tuple was in fact for partially non- homogenous data. I forget why, but I needed to treat arguments after a certain value different from the front arguments. So I wanted to do something like: def something(*args): firstspecial = args.index(0) 'Cept I couldn't. Carl Banks From paddy3118 at googlemail.com Sun Jun 8 20:00:24 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 8 Jun 2008 17:00:24 -0700 (PDT) Subject: Q re documentation Python style References: Message-ID: <3dceef6a-59da-4959-be2d-436b201f80b9@34g2000hsh.googlegroups.com> On Jun 8, 10:17 pm, kj wrote: > I'm a Perlhead trying to learn the Way of Python. I like Python > overall, but every once in a while I find myself trying to figure > out why Python does some things the way it does. At the moment > I'm scratching my head over Python's docstrings. As far as I > understand this is the standard way to document Python code. I > think that's fine for simple functions, but I have some functions > that require a very long docstring to document, and somehow I find > it a bit disconcerting to stick a few screenfuls of text between > the top line of a function definition and its body. Hi Kynn, Strings on their own are also valid statements so if in Perl you might documentbefore the sub statement or even after the function definition then you could put extra information in a tripple quoted string statement before your function and put the bare essentials in the function itself. This would leave the def nearer the body of the function, but I don't know of anyone else that does this. - Paddy. From duncan.booth at invalid.invalid Mon Jun 2 03:50:22 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Jun 2008 07:50:22 GMT Subject: php vs python References: Message-ID: Arnaud Delobelle wrote: > I find that eloquent Python speakers often tend to write a for loop > when mere good ones will try to stick a list comprehension in! > +1 QOTW -- Duncan Booth http://kupuguy.blogspot.com From ram.rachum at gmail.com Sun Jun 15 15:10:45 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Sun, 15 Jun 2008 12:10:45 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> <4259e7fb-5f4d-4574-9eaf-393cf5320c9b@r37g2000prm.googlegroups.com> Message-ID: On Jun 15, 9:31?pm, casevh wrote: > > Not yet: I was kind of set back when I saw their homepage was last > > updated 2002. But I'll give it a try. You think it's the best thing > > there is? > > > Thanks, > > Ram. > > gmpy has moved to Google. > > http://code.google.com/p/gmpy/ > > gmpy only support the basic floating point operations so it may not be > sufficient for your needs. > > A couple alternatives: > > 1) mpmath is a pure-Python, arbitrary precision floating-point > package. It will be faster than Decimal but slower than gmpy.http://code.google.com/p/mpmath/ > > 2) Sage is an open-source mathematics software package. It uses Python > as it glue/scripting language. It includes support for MPFR, a > multiple-precision floating point library based on GMP. ?www.sagemath.org > > casevh Thanks a bundle! From martin at v.loewis.de Thu Jun 19 16:21:55 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 19 Jun 2008 22:21:55 +0200 Subject: Installing Python 3.0 no probs running 2.5 at the same time? In-Reply-To: <4eb587db-ccd2-4d98-bfc0-abfda4edc4fc@i76g2000hsf.googlegroups.com> References: <4eb587db-ccd2-4d98-bfc0-abfda4edc4fc@i76g2000hsf.googlegroups.com> Message-ID: <485ABFE3.5020704@v.loewis.de> > Can I install 3.0 without breaking 2.5? Meaning does it overwrite some > bindings or something or it just installs 3.0 in a different folder as > a completely separate program? You can install both simultaneously, however, by default, .py will get associated with the last installation. If you don't want this, deselect "Register Extension". Regards, Martin From dyamins at gmail.com Fri Jun 13 19:32:28 2008 From: dyamins at gmail.com (Dan Yamins) Date: Fri, 13 Jun 2008 19:32:28 -0400 Subject: Another (perhaps similar) import question Message-ID: <15e4667e0806131632r56849364k640b444aaeb3bfb9@mail.gmail.com> I also have noticed another (to me) strange thing about module imports. If anyone could explain this to me, that would be great (I apologize if it's too elementary for this list.) Suppose I have a module #file: testmodule.py a = 1 When importing this module, obviously 'a' becomes an attribute of testmodule: >>> import testmodule >>> dir(testmodule) ['__builtins__', '__doc__', '__file__', '__name__', 'a'] Now, supposed I modify the file to: #file: testmodule.py A = 1 and then reload: >>> reload(testmodule) Now, the reported attributes still include the old 'a': >>> dir(testmodule) ['A', '__builtins__', '__doc__', '__file__', '__name__', 'a'] Why does this happen? Moreover, even if I delete the module from memory and then reload, I _still_ get the old attribute 'a': >>> del testmodule >>> import testmodule >>> dir(testmodule) ['A', '__builtins__', '__doc__', '__file__', '__name__', 'a'] What is the principle behind this? And, is there some simple way (other than restarting the interpreter) of "reloading" that wipes out the old attributes associated with a given name so that spurious attributes do not remain? Thanks again (and apologies of this is a stupid question) Dan -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at jmcneil.net Fri Jun 13 20:00:08 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Fri, 13 Jun 2008 20:00:08 -0400 Subject: Making HEAD/PUT/DELETE requests with urllib2? In-Reply-To: References: Message-ID: <82d28c40806131700r3142607wa4868429f507c78b@mail.gmail.com> The only time I've ever pulled a HEAD request I've used the httplib module directly. Ought to be able to do it like so: Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import httplib >>> c = httplib.HTTPConnection('www.google.com') >>> c.request('HEAD', '/') >>> r = c.getresponse() >>> r.getheader('server') 'gws' >>> r.status 200 >>> I don't honestly know if there's a way to do it via urllib(2), though. On Fri, Jun 13, 2008 at 7:40 PM, Phillip B Oldham wrote: > In my attempt to learn python in a weekend, I've fallen foul at line > 10 of my second scripting attempt. Basically I'm writing a simple > spider, but currently I'm unable to find any documentation on making > HEAD requests using the urllib2 library to test whether a file exists > on a remote webserver. > > I've checked the docs on urllib2 from docs.python.org, and unless I'm > missing something there doesn't seem to be a way to do *any* request > other than a GET and POST. > > Surely this can't be correct? If so, we're all going to have a hell of > a time creating RESTful web apps. > > Any help on the matter would be greatly appreciated. > -- > http://mail.python.org/mailman/listinfo/python-list > From cokofreedom at gmail.com Wed Jun 25 06:28:50 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 25 Jun 2008 03:28:50 -0700 (PDT) Subject: python -regular expression - list element References: <62e21ec1-18f3-4572-b223-1b8a5c40688c@f63g2000hsf.googlegroups.com> Message-ID: <47989866-786b-4a47-bfef-6499aeece302@s50g2000hsb.googlegroups.com> On Jun 25, 11:55 am, antar2 wrote: > Hello, > > I am a beginner in Python and am not able to use a list element for > regular expression, substitutions. > > list1 = [ 'a', 'o' ] > list2 = ['star', 'day', 'work', 'hello'] > > Suppose that I want to substitute the vowels from list2 that are in > list1, into for example 'u'. > In my substitution, I should use the elements in list1 as a variable. > I thought about: > > for x in list1: > re.compile(x) > for y in list2: > re.compile(y) > if x in y: > z = re.sub(x, 'u', y) > but this does not work I think you misunderstand the point of re.compile, it is for compiling a regular expression. >>> import re >>> list1 = [ 'a', 'o' ] >>> list2 = ['star', 'day', 'work', 'hello'] >>> for x in list1: for y in list2: if x in y: print re.sub(x, 'u', y) stur duy wurk hellu From Lie.1296 at gmail.com Wed Jun 11 09:48:45 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 11 Jun 2008 06:48:45 -0700 (PDT) Subject: problems with opening files due to file's path References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> Message-ID: <77acc29a-fffa-44d6-b07b-6bcf8b5bdd74@h1g2000prh.googlegroups.com> On Jun 11, 10:07?am, Alexnb wrote: > I don't think you understand it doesn't matter how the variable gets there, > the same code is run regardless, I have no problem with the GUI, but you > asked, and so I told you. the code os.startfile(.... is run if there is a > GUI or it is a console app. (snip) I think I know why you get confused by this, clearly, you have no idea of what an escape character and escape sequence is. Python (and C/C++ and some other languages) treats \ (the backspace character) inside a string specially, it makes the character after the backspace lose their special meaning OR get a special meaning, you might probably be used to seeing something like this: 'First line \nSecond Line', which when printed, would give: >>> print 'First Line\nSecond Line' First Line Second Line The second behavior of the escape sequence is to make special character (generally the backspace itself), lose their special meaning: >>> print 'path\\file.txt' path\file.txt In some cases, you might sometimes want a path like this: 'path \nick.txt' if you do this: >>> print 'path\nick.txt' path ick.txt because the \n is considered as a newline. Instead, you should do this: >>> print 'path\\nick.txt' path\nick.txt or >>> print r'path\nick.txt' path\nick.txt the r'' string is raw string, most of the magics of a regular string '' is lost for an r'' string. It allows you to avoid the need to escape the special characters. Raw string is usually used for re (regular expressions) and paths in Windows both of which uses the backslash character regularly. you first case of: system("\"C:\Documents and Settings\Alex\My Documents\My Music\Rhapsody \Bryanbros\Weezer\(2001)\04 - Island In The Sun.wma\"") is interpreted by python as this: "C:\Documents and Settings\Alex\My Documents\My Music\Rhapsody \Bryanbros\Weezer\(2001) - Island In The Sun.wma" Notice that the '\0' is substituted into '', because \0 is the escape sequence for null character. (Personally I think python should raise errors if any escape character that isn't followed by a valid escape sequence is found (such as \D, \A, \M, \M, \R, \B, \W, \(), but perhaps they're trying not to be too mean for newbies.) that should be correctly written like this: system(r'"C:\Documents and Settings\Alex\My Documents\My Music\Rhapsody \Bryanbros\Weezer\(2001)\04 - Island In The Sun.wma"') or: system('"C:\\Documents and Settings\\Alex\\My Documents\\My Music\ \Rhapsody\\Bryanbros\\Weezer\\(2001)\\04 - Island In The Sun.wma"') Now, to the next question: How if I want the path to come from a variable: path = "C:\Documents and Settings\Alex\My Documents\My Music\Rhapsody \Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm Yours.wma" os.startfile(path) I can see in a glance why it doesn't work, the string is escaped by python, it should be written like this. path = r"C:\Documents and Settings\Alex\My Documents\My Music\Rhapsody \Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm Yours.wma" os.startfile(path) OR: path = "C:\\Documents and Settings\\Alex\\My Documents\\My Music\ \Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\\01 - I'm Yours.wma" os.startfile(path) In most GUI toolkits (including Tkinter) and raw_input() function, when you input a string (using the textbox, a.k.a Entry widget) it would automatically be escaped for you, so when you input 'path\path \file.txt', the GUI toolkit would convert it into 'path\\path\ \file.txt'. From gherron at islandtraining.com Mon Jun 2 20:18:06 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 02 Jun 2008 17:18:06 -0700 Subject: Importing xlrd In-Reply-To: References: Message-ID: <48448DBE.3010702@islandtraining.com> Chanman wrote: > This is probably a simple question to most of you, but here goes. > I've downloaded the xlrd (version 0.6.1) module and placed in in the > site-packages folder. Now, when I write a script, I type: > > import sys > import xlrd > > When I run it, there is an import error saying there is no module > named xlrd. However when I type sys.path, the site-packages folder is > definitely in the path. Do I somehow need to run the xlrd setup.py > first before importing? > > Any help would be appreciated. > -- > http://mail.python.org/mailman/listinfo/python-list > On what system? Windows or Unix? Which download? The exe or the zip? I'm guessing you downloaded the zip file on a Unix or Linux system. If so, you should not copy the files into the site-package directory yourself. You are supposed to use the included setup.py file like this: unzip into some local directory cd into that directory python setup.py build python setup.py install Then your import should work fine. Gary Herron From exarkun at divmod.com Mon Jun 30 12:26:20 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 30 Jun 2008 12:26:20 -0400 Subject: ctypes - swig - pointer In-Reply-To: Message-ID: <20080630162620.4714.1927154859.divmod.quotient.15321@ohm> On Mon, 30 Jun 2008 09:13:42 -0700 (PDT), gianluca wrote: >I've a problem with dll function colled with python/ctypes. My >functions (C) requred a typedef int "value_type" in tree different >way: >same as value_type; - mydll.foo1(value_type) >same as *value_type; - mydll.foo2(*value_type) >same as **value_type; - mydll.foo3(**value_type) > >How can pass it in python. If i do that: >rules=POINTER(value_type) >opr=rsl.StrengthOfRules(rules,10) >R=POINTER(rules) POINTER takes a class and returns a new class which represents a pointer to input class. pointer takes an instance and returns a new object which represents a pointer to that instance. Jean-Paul From ivan.illarionov at gmail.com Wed Jun 4 10:10:51 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 4 Jun 2008 14:10:51 +0000 (UTC) Subject: printf in python References: Message-ID: On Mon, 02 Jun 2008 00:32:33 -0700, gianluca wrote: > Hy, I've a problem with may python library generated with swig from C > code. I works and I can access all function but a sim?ple function that > print a string don't work's. > The function is like this: > int PrintTEST() > { > printf("TEST "); > return 1; > } > > If I call the function (myDLL.PrintTEST() ) the function print only the > returned value, not the string "TEST". Could anybody help me? > > Thanks > > Gianluca Hi! Here's "Hello world" in Python C API: 1. create 'hello.c' file with the following content: #include PyObject* hello(PyObject* self) { printf("Hello world!\n"); Py_RETURN_NONE; } static PyMethodDef functions[] = { {"hello", (PyCFunction)hello, METH_NOARGS}, {NULL, NULL, 0, NULL}, }; DL_EXPORT(void) init_hello(void) { Py_InitModule("_hello", functions); } 2. create 'buildme.py' file with this content: import os import sys from distutils.core import Extension, setup os.chdir(os.path.dirname(os.path.abspath(__file__))) sys.argv = [sys.argv[0], 'build_ext', '-i'] setup(ext_modules = [Extension('_hello', ["hello.c"])]) 3. run "python buildme.py" That's all. >>> from _hello import hello >>> hello() Hello world! -- Ivan From xahlee at gmail.com Mon Jun 30 12:45:18 2008 From: xahlee at gmail.com (Xah) Date: Mon, 30 Jun 2008 09:45:18 -0700 (PDT) Subject: perl + python tutorial available for download Message-ID: <86c4090b-ed0b-4249-b3ee-517c94328741@z32g2000prh.googlegroups.com> my perl and python tutorial http://xahlee.org/perl-python/index.html is now available for download for offline reading. Download link at the bottom. Xah ? http://xahlee.org/ ? From auch-ich-m at g-kein-spam.com Thu Jun 19 16:23:13 2008 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Thu, 19 Jun 2008 22:23:13 +0200 Subject: Extending Python with C: Cannot find MPI library References: <9100a146-a0bb-4958-a7c6-f23c9b518e89@a1g2000hsb.googlegroups.com> <80244b16-e2c5-4f4c-98d6-6101b004eb3c@26g2000hsk.googlegroups.com> Message-ID: <2012805.PE4ZuOqaqP@news.perlig.de> * Jeroen Ruigrok van der Werven wrote: > -On [20080619 17:11], Spectrum (spectrumdt at gmail.com) wrote: >> ImportError: dynamic module does not define init function > > Might be it's looking, but not finding, something like crti.S or the > likes, the C runtime files that specify stuff like _init and _fini. Nah. It's just looking for the init function required by the python module loader. See: http://docs.python.org/ext/methodTable.html nd -- die (eval q-qq:Just Another Perl Hacker :-) # Andr? Malo, # From upton at virginia.edu Tue Jun 3 15:34:58 2008 From: upton at virginia.edu (Dan Upton) Date: Tue, 3 Jun 2008 15:34:58 -0400 Subject: New variable? In-Reply-To: <2c47defa-52b3-4bbc-8286-9e266df80eb7@26g2000hsk.googlegroups.com> References: <18105511-7ae1-45e9-8c43-f34c1c4f5aeb@c58g2000hsc.googlegroups.com> <0dabbe7c-5754-4b2a-ae69-e92939fa682b@r66g2000hsg.googlegroups.com> <2c47defa-52b3-4bbc-8286-9e266df80eb7@26g2000hsk.googlegroups.com> Message-ID: <5504f9ac0806031234x5b56fed1y2963502bfcdb969b@mail.gmail.com> On Tue, Jun 3, 2008 at 3:16 PM, tmallen wrote: > On Jun 3, 3:03 pm, Chris wrote: >> On Jun 3, 8:40 pm, tmallen wrote: >> >> > What's the proper way to instantiate a new variable? x = ""? >> >> You don't need to pre-declare your variables. Just assign them as you >> need them and they will take the correct type. > > unless I'm using the += or a similar operator, right? That doesn't > seem to instantiate a variable. Right... because you don't have anything to increment or append to. I guess this also comes up in the case of something like lists or dictionaries you want to uniformly create in a loop. I guess you could call it instantiating, but really it's more like going ahead and assigning to them as Chris mentioned and you're just starting them with a default value. Assuming you're working with strings, x="" should work just fine in that case. Lists, x=[], dictionaries, x={}, integers, probably x=1 or x=0... From rdabane at gmail.com Tue Jun 3 17:00:47 2008 From: rdabane at gmail.com (rdabane at gmail.com) Date: Tue, 3 Jun 2008 14:00:47 -0700 (PDT) Subject: help needed in subprocess communicate Message-ID: <29fb52c3-6212-4f4c-9bf8-f8b565da24dd@c65g2000hsa.googlegroups.com> I'm trying to perform following type of operation from inside a python script. 1. Open an application shell (basically a tcl ) 2. Run some commands on that shell and get outputs from each command 3. Close the shell I could do it using communicate if I concatenate all my commands ( separated by newline ) and read all the output in the end. So basically I could do following sequence: 1. command1 \n command2 \n command 3 \n 2. Read all the output But I want to perform it interactively. 1. command1 2. read output 3. command2 4. read output ...... Following is my code: from subprocess import * p2 = Popen('qdl_tcl',stdin=PIPE,stdout=PIPE) o,e = p2.communicate(input='qdl_help \n qdl_read /home/rokit/ svnproject/falcon/chip/blocks/intf/bitsif/rtl/m6_bitsif.qdl_cpp \n qdl_reg_group_list m6_bitsif') Please suggest a way to perform it interactively with killing the process each time I want to communicate with it. Thanks in advance, -Rahul. From roy at panix.com Sat Jun 28 23:00:37 2008 From: roy at panix.com (Roy Smith) Date: Sat, 28 Jun 2008 23:00:37 -0400 Subject: complex numbers should respect the "I" representation References: <6c674bf8-f16b-40f1-81ef-72c009c08465@w1g2000prd.googlegroups.com> Message-ID: In article <6c674bf8-f16b-40f1-81ef-72c009c08465 at w1g2000prd.googlegroups.com>, "narutocanada at gmail.com" wrote: > hi > > I think complex numbers should respect the "i" or "I" representation, > instead of "j". > No reason being cute and using a different character instead of the > traditional representation? Ask any electrical engineer what j means. From victor.herasme at gmail.com Wed Jun 4 17:57:05 2008 From: victor.herasme at gmail.com (victor.herasme at gmail.com) Date: Wed, 4 Jun 2008 14:57:05 -0700 (PDT) Subject: Tuples part 2 Message-ID: Hi Everyone, i have another question. What if i wanted to make n tuples, each with a list of coordinates. For example : coords = list() for h in xrange(1,11,1): for i in xrange(1, 5, 1) : for j in xrange(1, 5, 1) : for k in xrange(1,2,1) : coords.append((i,j,k)) lista+str(h)= tuple coords print tuple(coords) so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do it the way i show you above but it is not working properly. I wish you could help me with that. Thanks again, From ptmcg at austin.rr.com Tue Jun 24 05:32:12 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 24 Jun 2008 02:32:12 -0700 (PDT) Subject: String split with " and/or ' and/or \ References: Message-ID: On Jun 24, 3:56?am, Kurt Mueller wrote: > How to (super)split a string (literal) containing " and/or ' and/or \. > > example: > > ' a ?" ?b b ? " ?c\ c '.supersplit(' ') > -> > ['a', ' ?b b ? ', 'c c'] > > Thanks and Gr?essli > -- > Kurt M?ller: > kurt.muel... at aerodynamics.ch >>> re.split(r'''['"\\]''',' a " b b " c\ c ') [' a ', ' b b ', ' c', ' c '] From dan at catfolks.net Wed Jun 4 08:48:09 2008 From: dan at catfolks.net (Daniel Mahoney) Date: Wed, 04 Jun 2008 07:48:09 -0500 Subject: Handling some isolated iso-8859-1 characters References: <16ad09c5-5095-4444-8739-285f8d665fd3@q24g2000prf.googlegroups.com> Message-ID: > ... print ord(c), unicodedata.name(c) > ... > 65 LATIN CAPITAL LETTER A > 110 LATIN SMALL LETTER N > 97 LATIN SMALL LETTER A > 239 LATIN SMALL LETTER I WITH DIAERESIS > 115 LATIN SMALL LETTER S Looks like I need to explore the unicodedata class. Thanks! From eliben at gmail.com Tue Jun 24 04:03:58 2008 From: eliben at gmail.com (eliben) Date: Tue, 24 Jun 2008 01:03:58 -0700 (PDT) Subject: binary representation of an integer Message-ID: <14e14b5e-ce39-414a-a450-7c81baaabc3a@79g2000hsk.googlegroups.com> Hello, I'm interested in converting integers to a binary representation, string. I.e. a desired function would produce: dec2bin(13) => "1101" The other way is easily done in Python with the int() function. Perl has a very efficient way to do dec2bin, because its pack/unpack have a B format for binary representations, so it's done with: sub dec2bin { my $str = unpack("B32", pack("N", shift)); $str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros return $str; } Python's pack/unpack don't have the binary format for some reason, so custom solutions have to be developed. One suggested in the ASPN cookbook is: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 However, it is very general and thus inefficient. What would be the quickest way to do this ? I think that for dec2bin conversion, using hex() and then looping with a hex->bin lookup table would be probably much faster than the general baseconvert from the recipe. What do you think? From hat at se-162.se.wtb.tue.nl Tue Jun 24 06:58:36 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 24 Jun 2008 12:58:36 +0200 Subject: very large graph References: <135bba90-a9dd-4fcd-9220-6271e5a7c876@59g2000hsb.googlegroups.com> <02ef6dc2-9ddb-4fbc-b3ce-5e6247daab33@e39g2000hsf.googlegroups.com> Message-ID: On 2008-06-24, MRAB wrote: > On Jun 24, 1:26?am, chrispoliq... at gmail.com wrote: >> I need to represent the hyperlinks between a large number of HTML >> files as a graph. ?My non-directed graph will have about 63,000 nodes >> and and probably close to 500,000 edges. >> >> I have looked into igraph (http://cneurocvs.rmki.kfki.hu/igraph/doc/ >> python/index.html) and networkX (https://networkx.lanl.gov/wiki) for >> generating a file to store the graph, and I have also looked into >> Graphviz for visualization. ?I'm just not sure which modules are >> best. ?I need to be able to do the following: Afaik Graphviz is not good at abstracting the graph, which you may need here. A page with 63,000 circles on it, and 500,000 edges will probably come out of the printer as a black sheet of paper. (8"x11" paper, 1 circle is 1/5", then you have only 2200 circles at one sheet. You need a factor 28 more circles which leads to a circle of about 0.007".) Even when actual paper format would not be a problem, you will need some abstraction and/or tools, as you will not find anything manually in an ocean of 63,000 elements. One area you may want to start looking for tools is in state graphs, where the set of possible states of an entire system is unfolded. These things go up to over a million states, so you only have a 'small' problem there... >> 1) ?The names of my nodes are not known ahead of time, so I will >> extract the title from all the HTML files to name the nodes prior to >> parsing the files for hyperlinks (edges). >> >> 2) Every file will be parsed for links and nondirectional connections >> will be drawn between the two nodes. >> >> 3) ?The files might link to each other so the graph package needs to >> be able to check to see if an edge between two nodes already exists, >> or at least not double draw connections between the two nodes when >> adding edges. >> >> I'm relatively new to graph theory so I would greatly appreciate any >> suggestions for filetypes. ?I imagine doing this as a python >> dictionary with a list for the edges and a node:list paring is out of >> the question for such a large graph? > > Perhaps a dictionary where the key is a node and the value is a set of > destination nodes? For undirected edges, you could make an Edge class and have a set of Edge's (where two Edge objects are equal when they connect the same nodes). I don't expect 500,000 elements in a set to be a problem. Sincerely, Albert From bignose+hates-spam at benfinney.id.au Wed Jun 4 18:29:09 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 05 Jun 2008 08:29:09 +1000 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> <873antn9il.fsf@benfinney.id.au> <6ammujF38poe2U2@mid.uni-berlin.de> <87y75llp5x.fsf@benfinney.id.au> Message-ID: <87prqwltqi.fsf@benfinney.id.au> Roy Smith writes: > The only externally visible interface is pushTheButton(), yet you > don't really want to call that during testing. What you do want to > do is test that a random city really does get picked. Then what you're really testing is the interactions of the "push the button" function with its external interface: you're asserting that the "push the red button" function actually uses the result from "pick a random city" as its target. Thus, the "pick a random city" function is being defined by you as *interface* for the "push the button" function. Interfaces do need to be unit tested. This is done by having the unit test substitute a test double for the "pick a random city" function, rigging that double so that its behaviour is deterministic, and asserting that the "push the button" function uses that deterministically-generated result. It's at this point, of course, that the "pick a random city" function has come rather close to being public API. The designer needs to have a fairly good reason not to simply expose the "pick a random city" function in the API. > You can do one of two things at this point. You can say, "But, > that's not part of the externally visible interface" and refuse to > test it, or you can figure out a way to test it. Up to you. Note that the only thing I'm saying one shouldn't do is unit test the private function *directly*, since the design decision has been made that it's not part of the API. The *behaviour* of the function, as exposed via the "push the button" piblic API, should certainly be unit tested. Any behaviour of that function that's *not* exhibited through the behaviour of some public API should *not* be unit tested, and should in fact be removed during refactoring -- which will not break the unit test suite since no unit tests depend on it. Alternatively, as above, the design decision can be made that, in fact, this function *is* part of the public API since external things are depending on it directly. Then it needs full direct unit test coverage. -- \ "I got contacts, but I only need them when I read, so I got | `\ flip-ups." -- Steven Wright | _o__) | Ben Finney From grante at visi.com Wed Jun 11 18:48:12 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 11 Jun 2008 17:48:12 -0500 Subject: how to indent/dedent a region in emacs? References: Message-ID: On 2008-06-11, Grant Edwards wrote: > I've recently switched from Jed to Emacs for editing python > source, and I'm still stumped as to how one indents or dedents > a region of code. In Jed it's 'C-c <' or 'C-c >'. Google has > found several answers, but none of them work, for example I've > tried bot "C-c tab" and "C-c C-r" based on postings Google has > found, but neither appears to actually _do_ anyting. Doh! It's 'C-c <' and 'C-c >' just like in Jed. I swear that didn't work the first time I tried it... -- Grant Edwards grante Yow! An air of FRENCH FRIES at permeates my nostrils!! visi.com From jeff at jmcneil.net Fri Jun 27 16:10:03 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Fri, 27 Jun 2008 13:10:03 -0700 (PDT) Subject: using urllib2 References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> Message-ID: I stumbled across this a while back: http://www.voidspace.org.uk/python/articles/urllib2.shtml. It covers quite a bit. The urllib2 module is pretty straightforward once you've used it a few times. Some of the class naming and whatnot takes a bit of getting used to (I found that to be the most confusing bit). On Jun 27, 1:41 pm, Alexnb wrote: > Okay, I tried to follow that, and it is kinda hard. But since you obviously > know what you are doing, where did you learn this? Or where can I learn > this? > > > > > > Maric Michaud wrote: > > > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit : > >> I have never used the urllib or the urllib2. I really have looked online > >> for help on this issue, and mailing lists, but I can't figure out my > >> problem because people haven't been helping me, which is why I am here! > >> :]. > >> Okay, so basically I want to be able to submit a word to dictionary.com > >> and > >> then get the definitions. However, to start off learning urllib2, I just > >> want to do a simple google search. Before you get mad, what I have found > >> on > >> urllib2 hasn't helped me. Anyway, How would you go about doing this. No, > >> I > >> did not post the html, but I mean if you want, right click on your > >> browser > >> and hit view source of the google homepage. Basically what I want to know > >> is how to submit the values(the search term) and then search for that > >> value. Heres what I know: > > >> import urllib2 > >> response = urllib2.urlopen("http://www.google.com/") > >> html = response.read() > >> print html > > >> Now I know that all this does is print the source, but thats about all I > >> know. I know it may be a lot to ask to have someone show/help me, but I > >> really would appreciate it. > > > This example is for google, of course using pygoogle is easier in this > > case, > > but this is a valid example for the general case : > > >>>>[207]: import urllib, urllib2 > > > You need to trick the server with an imaginary User-Agent. > > >>>>[208]: def google_search(terms) : > > return urllib2.urlopen(urllib2.Request("http://www.google.com/search?" > > + > > urllib.urlencode({'hl':'fr', 'q':terms}), > > headers={'User-Agent':'MyNav > > 1.0 > > (compatible; MSIE 6.0; Linux'}) > > ).read() > > .....: > > >>>>[212]: res = google_search("python & co") > > > Now you got the whole html response, you'll have to parse it to recover > > datas, > > a quick & dirty try on google response page : > > >>>>[213]: import re > > >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

    class=r>.*?

    ', > > res) ] > > ...[229]: > > ['Python Gallery', > > 'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des Monty ...', > > 'Re: os x, panther, python & co: msg#00041', > > 'Re: os x, panther, python & co: msg#00040', > > 'Cardiff Web Site Design, Professional web site design services ...', > > 'Python Properties', > > 'Frees < Programs < Python < Bin-Co', > > 'Torb: an interface between Tcl and CORBA', > > 'Royal Python Morphs', > > 'Python & Co'] > > > -- > > _____________ > > > Maric Michaud > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > View this message in context:http://www.nabble.com/using-urllib2-tp18150669p18160312.html > Sent from the Python - python-list mailing list archive at Nabble.com. From fc14301589 at icqmail.com Sun Jun 1 12:37:26 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Mon, 02 Jun 2008 00:37:26 +0800 Subject: [Business apps for Windows] Good grid + calendar, etc.? References: Message-ID: <4842d046_1@news.tm.net.my> On 19:59, domenica 01 giugno 2008 Gilles Ganault wrote: > require rich widgets like (DB)grids, calendars, etc. Qt seems to go a bit further. Try Eric4 as SDK. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From brian_vanderburg2 at yahoo.com Wed Jun 18 02:28:44 2008 From: brian_vanderburg2 at yahoo.com (Allen) Date: Wed, 18 Jun 2008 02:28:44 -0400 Subject: Save turtle state? Message-ID: I'm using the turtle module in Python. Is there a way to save the turle state at any moment for recursive algorithms to easily return the turtle to an earlier point for another branch/etc? Brian Vanderburg II From pirata at mars.invalid Mon Jun 16 23:29:53 2008 From: pirata at mars.invalid (pirata) Date: Mon, 16 Jun 2008 22:29:53 -0500 Subject: Does '!=' equivelent to 'is not' Message-ID: I'm a bit confusing about whether "is not" equivelent to "!=" if a != b: ... if a is not b: ... What's the difference between "is not" and "!=" or they are the same thing? From ram.rachum at gmail.com Sun Jun 15 15:11:06 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Sun, 15 Jun 2008 12:11:06 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> <1f658382-1f45-41c2-a884-5478fef394bf@j22g2000hsf.googlegroups.com> Message-ID: On Jun 15, 9:41?pm, Mensanator wrote: > On Jun 15, 12:10?pm, "ram.rac... at gmail.com" > wrote: > > > > > On Jun 15, 7:43?pm, Peter Otten <__pete... at web.de> wrote: > > > > ram.rac... at gmail.com wrote: > > > > On Jun 15, 6:58?pm, Christian Meesters wrote: > > > >> > I do need speed. Is there an option? > > > > >> Mind telling us what you *actually* want to achieve? (What do you want to > > > >> calculate?) > > > > >> Christian > > > > > Physical simulations of objects with near-lightspeed velocity. > > > > How did you determine that standard python floats are not good enough? > > > I have a physical system set up in which a body is supposed to > > accelerate and to get very close to lightspeed, while never really > > attaining it. After approx. 680 seconds, Python gets stuck and tells > > me the object has passed lightspeed. I put the same equations in > > Mathematica, again I get the same mistake around 680 seconds. So I > > think, I have a problem with my model! Then I pump up the > > WorkingPrecision in Mathematica to about 10. I run the same equations > > again, and it works! At least for the first 10,000 seconds, the object > > does not pass lightspeed. > > I concluded that I need Python to work at a higher precision. > > > > Everything beyond that is unlikely to be supported by the hardware and will > > > therefore introduce a speed penalty. > > > I have thought of that as well. However I have no choice. I must do > > these calculations. If you know of any way that is supported by the > > hardware, it will be terrific, but for now the slower things will have > > to do. > > > > Did you try gmpy? > > > Not yet: I was kind of set back when I saw their homepage was last > > updated 2002. > > Try looking here: > > http://code.google.com/p/gmpy/ > > The developers have abandoned SourceForge. > > > But I'll give it a try. You think it's the best thing > > there is? > > I haven't tried everything, but it's very good. > You might also want to go to the GMP site itself > and get their manual. Likee anything else, your > results will be no better than your algorithms. > > > > > Thanks, > > Ram. I'll check it out, thanks. From robert.kern at gmail.com Wed Jun 18 19:05:08 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 18 Jun 2008 18:05:08 -0500 Subject: python string comparison oddity In-Reply-To: References: <3ebd170e-8686-4bb4-9e47-0fba2179feb3@p39g2000prm.googlegroups.com> Message-ID: Faheem Mitha wrote: > On Wed, 18 Jun 2008 12:57:44 -0700 (PDT), Lie wrote: >> On Jun 19, 2:26 am, Faheem Mitha wrote: >>> Hi everybody, >>> >>> I was wondering if anyone can explain this. My understanding is that 'is' >>> checks if the object is the same. However, in that case, why this >>> inconsistency for short strings? I would expect a 'False' for all three >>> comparisons. This is reproducible across two different machines, so it is >>> not just a local quirk. I'm running Debian etch with Python 2.4.4 (the >>> default). >>> Thanks, Faheem. >>> >>> In [1]: a = '--' >>> >>> In [2]: a is '--' >>> Out[2]: False >>> >>> In [4]: a = '-' >>> >>> In [5]: a is '-' >>> Out[5]: True >>> >>> In [6]: a = 'foo' >>> >>> In [7]: a is 'foo' >>> Out[7]: True >> Yes, this happens because of small objects caching. When small >> integers or short strings are created, there are possibility that they >> might refer to the same objects behind-the-scene. Don't rely on this >> behavior. > > Yes, but why is '-' and 'foo' cached, and not '--'? Do you know what > the basis of the choice is? Shortish Python identifiers and operators, I think. Plus a handful like '\x00'. The source would know for sure, but alas, I am lazy. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From goldnery at gmail.com Sun Jun 8 06:01:00 2008 From: goldnery at gmail.com (Gandalf) Date: Sun, 8 Jun 2008 03:01:00 -0700 (PDT) Subject: SQlite none english char References: <6b1ld5F3a4hsvU1@mid.uni-berlin.de> Message-ID: On Jun 8, 11:00?am, Gerhard H?ring wrote: > Gandalf wrote: > > I works with python 2.5 on windows, ?And I use sqlite3 > > > Now, I have problem searching string in Hebrew in my database > > > I have table called "test" with field num and test > > firs row i insert ?"1" and "?????" ?(that is "Hebrew" in Hebrew) > > second row i insert "2" and "English" [...] > > I recommend you use Unicode strings for all your Python strings in the > application. You can then be that things will just work with the sqlite3 > module. > > The problem is that the sqlite3 module doesn't currently check if what > you insert into the database is in UTF-8 encoding. But if it isn't, > you're likely to run into problems later on. > > So, let's assume that you've written your Python using a UTF-8 editor, > you can then use something like: > > # coding: utf-8 > > as the first line in the script. Among others, this will allow you to > write Unicode literals in UTF-8, i. e. do something like: > > data = u"?????". > > then you can insert this into the database: > > cur.execute("insert into test(test) values (?)", (data,)) > > Note that I use the parametrized form of execute() with ? as > placeholders. *Always* use this when the SQL statement is not constant, > but has parameters of some sort. > > > [...] > > cur.execute("select * ?from `test` where text like '%"+i+"%' ?") > > for row in cur: > > ? ? print row[1] > > > but this one print me nothing > > instead of ????? > > This could be two problems. Either (likely) it simply isn't found > because you inserted garbage (non-UTF-8 data) or you got a decoding > error to UTF-8 executing the select, which the sqlite3 module will > currently unfortunately ignore and return a None value instead. > > Again, use the parametrized form of the execute() statement with Unicode > Python strings to avoid any problems. > > cur.execute("select * from test where text like '%' || ? || '%'", > (searchstr,)) > > !!! Ok, I just found out that you used the + operator in SQL to > concatenate strings. Don't, as it will not work (except on maybe MySQL). > Use the || operator instead! > > Note that when you use cur.execute(sql, params), then params is actually > a tuple of parameters. In the above examples there was only one > parameter, so it was a one-tuple, which is written as (element,). > Dont'write it as (element), because Python will not recognize it as a > tuple then. > > Don't hesitate to ask if you need further help. > > -- Gerhard I solved the problem by entering data manually but now the problem is that i had to delete this function: con.text_factory = str and now I can't see the data that I entered thought my sqlite manager From __peter__ at web.de Sun Jun 15 12:43:26 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Jun 2008 18:43:26 +0200 Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> Message-ID: ram.rachum at gmail.com wrote: > On Jun 15, 6:58?pm, Christian Meesters wrote: >> > I do need speed. Is there an option? >> >> Mind telling us what you *actually* want to achieve? (What do you want to >> calculate?) >> >> Christian > > Physical simulations of objects with near-lightspeed velocity. How did you determine that standard python floats are not good enough? Everything beyond that is unlikely to be supported by the hardware and will therefore introduce a speed penalty. Did you try gmpy? Peter From lawtonpaul at gmail.com Mon Jun 16 20:48:17 2008 From: lawtonpaul at gmail.com (takayuki) Date: Mon, 16 Jun 2008 17:48:17 -0700 (PDT) Subject: newbie question: for loop within for loop confusion References: <821db59d-c9b6-4aa8-b08a-b8f46d230eb1@p25g2000pri.googlegroups.com> Message-ID: Paul, Thank you for the informative reply. Yes, I created the indent problem when manually copying the original script when I posted. (I'm using an old laptop to study python and posting here using the desktop.) Your examples really helped. Last night I played with using a for loop instead of a while loop and got it working, but your examples really clarified things. This loop was particularly interesting because I didn't know the else could be attached to the for. Attaching it to the for solved a lot of problems. for letter in avoid: if letter in word: break else: print word I've printed out this whole thread and will be playing with your and others' solutions. I love this one for its conciseness, but will have to play with it to get my head around it. if not any(letter in word for letter in avoid): print word Thanks again. takayuki From eliben at gmail.com Fri Jun 20 01:01:02 2008 From: eliben at gmail.com (eliben) Date: Thu, 19 Jun 2008 22:01:02 -0700 (PDT) Subject: An idiom for code generation with exec Message-ID: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> Hello, In a Python program I'm writing I need to dynamically generate functions[*] and store them in a dict. eval() can't work for me because a function definition is a statement and not an expression, so I'm using exec. At the moment I came up with the following to make it work: def build_func(args): code """def foo(...)...""" d = {} exec code in globals(), d return d['foo'] My question is, considering that I really need code generation[*] - "is there a cleaner way to do this ?" Also, what happens if I replace globals() by None ? Additionally, I've found indentation to be a problem in such constructs. Is there a workable way to indent the code at the level of build_func, and not on column 0 ? Thanks in advance Eli [*] I know that each time a code generation question comes up people suggest that there's a better way to achieve this, without using exec, eval, etc. But in my case, for reasons too long to fully lay out, I really need to generate non-trivial functions with a lot of hard-coded actions for performance. And there's no problem of security whatsoever. If someone is very interested in the application, I will elaborate more. From mwilson at the-wire.com Fri Jun 20 07:15:48 2008 From: mwilson at the-wire.com (Mel) Date: Fri, 20 Jun 2008 07:15:48 -0400 Subject: Strange re problem References: <2a0a6f87-f72e-4190-85f8-6e43821e313a@r66g2000hsg.googlegroups.com> Message-ID: TYR wrote: > OK, this ought to be simple. I'm parsing a large text file (originally > a database dump) in order to process the contents back into a SQLite3 > database. The data looks like this: > > 'AAA','PF',-17.416666666667,-145.5,'Anaa, French Polynesia','Pacific/ > Tahiti','Anaa';'AAB','AU',-26.75,141,'Arrabury, Queensland, > Australia','?','?';'AAC','EG',31.133333333333,33.8,'Al Arish, > Egypt','Africa/Cairo','El Arish International';'AAE','DZ', > 36.833333333333,8,'Annaba','Africa/Algiers','Rabah Bitat'; > > which goes on for another 308 lines. As keen and agile minds will no > doubt spot, the rows are separated by a ; so it should be simple to > parse it using a regex. So, I establish a db connection and cursor, > create the table, and open the source file. > > Then we do this: > > f = file.readlines() > biglist = re.split(';', f) > > and then iterate over the output from re.split(), inserting each set > of values into the db, and finally close the file and commit > transactions. But instead, I get this error: > > Traceback (most recent call last): > File "converter.py", line 12, in > biglist = re.split(';', f) > File "/usr/lib/python2.5/re.py", line 157, in split > return _compile(pattern, 0).split(string, maxsplit) > TypeError: expected string or buffer (untested) Try f=file.read() readlines gives you a list of lines. Mel. From duncan.booth at invalid.invalid Thu Jun 12 06:40:34 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jun 2008 10:40:34 GMT Subject: ClassName.attribute vs self.__class__.attribute References: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> <4850e95d$0$10444$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > > FWIW, metaclasses do have a class attribute that refers to itself !-) > One metaclass (i.e. type) has a class attribute that refers to itself. Other metaclasses have a class attribute that refers to the metaclass's metaclass. I can't think of any situation where a metaclass would be its own metaclass except for 'type' itself, but then I think I've got a headache trying to think about this so maybe I'm wrong. In fact, thinking about it a bit more, I think that if you did have another metaclass which is its own metaclass then the class cannot subclass 'object'. -- Duncan Booth http://kupuguy.blogspot.com From sjmachin at lexicon.net Tue Jun 24 20:36:10 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 24 Jun 2008 17:36:10 -0700 (PDT) Subject: shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": References: <09b41308-0167-4231-b5e7-5baa1a9aff9d@u6g2000prc.googlegroups.com> <3b12d826-4a10-4ed3-b66e-f28f64910f05@m3g2000hsc.googlegroups.com> Message-ID: On Jun 25, 9:06 am, s0s... at gmail.com wrote: > On Jun 24, 5:36 pm, John Machin wrote: > > > On Jun 25, 4:32 am, cirfu wrote: > > > > if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": > > > > cant i write something like: > > > if char in "[A-Za-z]": > > > You can write that if you want to, but it's equivalent to > > if char in "zaZa]-[": > > i.e. it doesn't do what you want. > > > This gives the same reuslt as your original code, unaffected by > > locale: > > > if "A" <= char <= "Z" or "a" <= char <= "z": > > But doesn't that rely on the underlying character set? Unless there is a Python implementation using EBCDIC, different underlying character set that differs from ASCII in A..Z and a..z is *not* a practical concern. > It's like > performing math on C char's (maybe that's what the interpreter does > internally?). If that's the case, using 'char.isalpha()' or 'char in > string.letters' or regex's would be better. You should be asking the OP what he really wants ... precisely those letters? alphabetic, in what locale? From nospam at nospam.com Sun Jun 1 07:59:26 2008 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 01 Jun 2008 13:59:26 +0200 Subject: [Business apps for Windows] Good grid + calendar, etc.? Message-ID: Hello Since Python is such a productive language, I'd really like to be able to use it to write GUI apps for Windows, but business apps require rich widgets like (DB)grids, calendars, etc. The ones available in wxWidgets looked a bit too basic compared to what's available for eg. Delphi or .Net, and don't seem to be under active development (lots of "1.0", "Last updated 2005", etc.) For instance, here's wxGrid and DevExpress' grid for Delphi: http://www.simpol.com/guiimages/wxgrid.jpg http://community.devexpress.com/blogs/thinking/PrintingXtraPivotGridForm.png Is it hopeless, or did I overlook things? Are there other solutions I should look at (FLTK, etc.)? For those of you writing business apps in Python for Windows, how do things go as far as GUI widgets are concerned? Thank you. From arslanburney at gmail.com Fri Jun 20 03:15:25 2008 From: arslanburney at gmail.com (J-Burns) Date: Fri, 20 Jun 2008 00:15:25 -0700 (PDT) Subject: Wierd Test Failure Message-ID: <6d84b388-f72a-4ccc-8b5b-b1fb7cc7f602@26g2000hsk.googlegroups.com> Hello. Im using doctests to check the functions that ive made. Wat i dnt understand is that it gives me a fialure even though the expected and got values are the same. Check this out: ********************************************************************** File "C:\Python25\Lib\idlelib\idle.pyw", line ?, in __main__.Test.test8 Failed example: Test.test8() Expected: True Got: True ********************************************************************** If both the values are returning True how is it possible for the test to fail? :S From celoserpa at gmail.com Tue Jun 24 12:24:46 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Tue, 24 Jun 2008 13:24:46 -0300 Subject: Accounting and financial system Message-ID: <1e5bcefd0806240924t74c7b4ax48d1267e508e516b@mail.gmail.com> Hello list, In a next project of mine, I will need to implement some accounting and financial control. It is not a full ERP, only the basic functions for finances and accounting control. However, I have little to no experience in this business domain (accounting and finances) but I really do need to understand the basic machinery behind it, even if it will take a significant amount of time. What I would like to know is where I could look (besides getting a degree :P) for sample code and documentation for these subjects? Do you think I would need to read some books before I get into code? If so, which ones? For sample code, I was thinking about OpenERP, since I've heard it is a complete ERP solution and it is written in python ;) Really, I'm committed to understand the basiscs of the said business domains, I really need this project to succeed :) Thanks in advance! Marceo. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mccredie at gmail.com Fri Jun 27 12:03:05 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 27 Jun 2008 09:03:05 -0700 (PDT) Subject: embedding and extending python C API registering callback handler objects References: Message-ID: On Jun 27, 8:22?am, Tim Spens wrote: > Hello all, > > I've been trying to get an example found herehttp://codeidol.com/python/python3/Embedding-Python/Registering-Callb... > to work. ?Every thing works fine except when I try to trigger an event from c that will call a python function. ?Here is my test code: > > //-----------------------python code--------------------------// > #! /usr/bin/env python > import time > import callback > > def callback1(label,count): > ? ? ? ? print 'callback1 successfully triggered from python via callback.so' > ? ? ? ? return 'callback1 => %s number %i' % (label, count) > > def callback2(label,count): > ? ? ? ? return 'callback2 => ' + ?label * count > > print '\nTest1:' > callback.setHandler(callback1) > callback.triggerEvent() ? ? ? ? # simulate events caught by C layer > > print '\nTest2:' > callback.setHandler(callback2) > > print 'Waiting for callback2 to be called from c:' > while 1: > ? ? ? ? time.sleep(.001) > > //-----------------------c code-------------------------------// > #include > #include > > /* keep Python object in C */ > static PyObject *Handler = NULL; > > void Route_Event(char *label, int count){ > ? ? char *cres; > ? ? PyObject *args, *pres; > ? ? /* call Python handler */ > ? ? args = Py_BuildValue("(si)", label, count); > ? ? pres = PyEval_CallObject(Handler, args); > ? ? Py_DECREF(args); > ? ? if (pres != NULL){ > ? ? ? ? /* use and decref handler result */ > ? ? ? ? PyArg_Parse(pres, "s", &cres); > ? ? ? ? printf("%s\n", cres); > ? ? ? ? Py_DECREF(pres); > > }} > > // the actual python callback call > static PyObject * > make_call(PyObject *function, PyObject *args){ > ? ? if (function == NULL) return NULL; > ? ? PyObject * val = PyObject_CallObject(function, args); > ? ? Py_XDECREF(args); > ? ? return val; > > } > > static PyObject * > Register_Handler(PyObject *self, PyObject *args){ > ? ? /* save Python callable object */ > ? ? Py_XDECREF(Handler); > ? ? PyArg_Parse(args, "O", &Handler); > ? ? Py_XINCREF(Handler); > ? ? Py_INCREF(Py_None); > ? ? return Py_None; > > } > > static PyObject * > Trigger_Event(PyObject *self, PyObject *args){ > ? ? /* let Python simulate event caught by C */ > ? ? static int count = 0; > ? ? Route_Event("spam", count++); > ? ? Py_INCREF(Py_None); > ? ? return Py_None; > > } > > static struct PyMethodDef callback_methods[] = { > ? ? {"setHandler", ? ?Register_Handler}, ? ? ? /* name, address */ > ? ? {"triggerEvent", ?Trigger_Event}, > ? ? {NULL, NULL}}; > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? /* on first "import callback" */ > void initcallback(){ ? ? ? ? ? ? ? ? ?/* this is called by Python ?*/ > ? ? (void) Py_InitModule("callback", callback_methods); > > } > > int main(){ > ? ? ? ? while (1){ > ? ? ? ? ? ? ? ? printf("1\n"); > ? ? ? ? ? ? ? ? //attempting to call callback2 which is registered to Handler > ? ? ? ? ? ? ? ? //i've also tried args = Py_BuildValue("(si)", label, count); here but I get a segfault. > ? ? ? ? ? ? ? ? PyObject *args = Py_BuildValue("s","c code"); > ? ? ? ? ? ? ? ? printf("2\n"); > ? ? ? ? ? ? ? ? PyObject* val = make_call(Handler,args); > ? ? ? ? ? ? ? ? printf("3\n"); > ? ? ? ? ? ? Py_XDECREF (val); > ? ? ? ? ? ? printf("4\n"); > ? ? ? ? ? ? ? ? sleep(1); > > }} > > //------------------------compiler stuff----------------------// > gcc callback.c -c -g -Wall -fpic -I /usr/include/python2.5 -o callback.o > gcc callback.c -g -Wall -I /usr/include/python2.5 -L /usr/local/lib -lpython2.5 -o callback > gcc -shared -Wall callback.o -o callback.so > > //------------------------test code results-------------------// > ../callback.py > Test1: > callback1 successfully triggered from python via callback.so > callback1 => spam number 0 > > Test2: > Waiting for callback2 to be called from c: > #NOTHING EVER GETS PRINTED HERE CALLBACK NEVER GETS CALLED? > > ../callback > 1 > 2 > 3 > 4 > .... > > Thanks, > Tim Maybe you just need to flush the stdout buffer in python. `sys.stdout.flush()` Matt From someone at somewhere.net Tue Jun 3 11:26:04 2008 From: someone at somewhere.net (Dino Dragovic) Date: Tue, 03 Jun 2008 17:26:04 +0200 Subject: trinity school defender Message-ID: u gorenavedenom flajeru u 8. redu: "postoji vi?e od 60.000 virusa i drugih ?tetnih programa " samo virusa ima nekoliko stotina tisuca, zajedno sa potencijalno stetim aplikacijama i ostalim malicioznim kodom brojka ide preko milion.... From russblau at hotmail.com Mon Jun 9 11:33:43 2008 From: russblau at hotmail.com (Russell Blau) Date: Mon, 9 Jun 2008 11:33:43 -0400 Subject: How to find the first space? References: <7a91cc8f-2e93-46e9-8360-a01da9170187@m44g2000hsc.googlegroups.com> Message-ID: "Johny" wrote in message news:7a91cc8f-2e93-46e9-8360-a01da9170187 at m44g2000hsc.googlegroups.com... > How can I find the first space using regex? > > For example I have text > Text=' This is a sample ' Why do you need to use a regex? text = text.replace(" ", "") Russ From andrei.avk at gmail.com Mon Jun 9 16:38:17 2008 From: andrei.avk at gmail.com (Rainy) Date: Mon, 9 Jun 2008 13:38:17 -0700 (PDT) Subject: Separators inside a var name References: Message-ID: On Jun 9, 2:05?pm, "Sebastian \"lunar\" Wiesner" wrote: > ?Rainy at Montag 09 Juni 2008 19:29: > > > I have a stylistic question. In most languages words in var. name are > > separated by underscores or cap letters, resulting in var names like > > var_name, VarName and varName. I don't like that very much because all > > 3 ways of naming look bad and/or hard to type. > > Then you better get used to such names, as they are common for many widely > spread languages including C, C++, C#, Java, Python, Ruby, Perl and many > more ;) ?You may like these or dislike these names, but you won't come > around them ;) Well, I was thinking of using some obscure language for personal projects that may not need good libs, etc. But of course I agree that there are no mainstream widely used languages that allow this. > > > From what I understand, scheme can have variables like var-name. I'm > > curious about reasons that python chose to disallow this. > > "-" is an operator in Python. ?How should the parser know, > whether "var-name" means "the object bound to var_dash_name" or "subtract > the object bound to name from the object bound to var"? As I mentioned in another post, differentiate between var1 - var2 and var-name. > > Scheme can allows such names, because its a functional programming language. > Subtracting in this language is not done through operators, but through > functions. ?Therefore there is a clear difference between referencing a > name or subtracting two ones: var-name vs (- var name). > > > Another question I have is what other languages allow this naming scheme? > > Other lisp dialects do, due to the same reasons as scheme. ? > > > Were there any languages that allowed space as a separator? > > None that I know of. ?Probably one could use unicode characters, that look > like a space in languages, which allow unicode characters in identifiers > (as Java or C#, iirc), but I doubt this. ?Anyway, even if allowed, this > would be silly, since it obscures code to the eyes of the reader. Yes, that's of course out. I meant using real space. > > > What would be a practical way to separate variables from keywords in that > > case? "some long variable name", 'just a string', or maybe using 2 spaces: > > one var ?+ ?other var ?+ ?third var ? > > I can't image a practical way to allow a space as character in names, while > still maintaining it syntactic element for separation of names. ?Quotes are > normally used for string or characters literals and a double space is hard > to distinguish from a single space, and things like ${a name with spaces} > is a lot nastier than names with underscores (which aren't bad at all, > imho). I agree about ${name with spaces}. I would be interested in the approach of using something else for strings and using quotes for var names. Not perfect either but might be better than underscores... > > > I think being able to easy have very long names for vars that are easy to > > type would be a fairly significant advantage. > > Names shouldn't be long, they should be expressive. ?If you can't give an > object a _short_, but _expressive_ name, your object is too complicated ;) I'm not sure, I often find myself needing to use 4 words for var name, and then underscores I think don't look too good, I would say that underscores are kind of ok for 2 words, not very good for 3 words and bad for 4+ words. I think if spaces were allowed, I would sometimes use 5 word variables. > > Btw, I don't really understand your refusal of underscores. ?In my opinion > such names are harder to read than underscores, which look more like a real > space, because the leave a space in the middle of a line, that you look at. > If they are too hard for you to type, whats the point in swapping the dash > and the underscore in your keyboard layout? To me, underscores_look_very_ugly. What_if_I_typed part_of_every_sentence with_an_underscore? Ugly! Swapping the dash and underscore are not a bad idea, it doesn't fix uglyness, though, and it adds a problem if you have to work on another system, because you will always type dash by mistake (which will look nice but won't work ;-) ). From tjreedy at udel.edu Thu Jun 19 21:29:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 19 Jun 2008 21:29:53 -0400 Subject: advanced listcomprehenions? In-Reply-To: References: <717129b5-d92f-4be2-ae6a-037870bfa407@2g2000hsn.googlegroups.com> Message-ID: Duncan Booth wrote: > Mark Wooding wrote: > >> This is still inelegant, though. We can glue the results mod 3 and 5 >> together using the Chinese Remainder Theorem and working mod 15 >> instead. For example, >> >> [['Fizz', 'FizzBuzz', False, None, 'Buzz'][(pow(i, 4, 15) + 1)%7] or >> str(i) for i in xrange(1, 101)] The lookup table is a constant. If made a tuple, it will be compiled as a constant (as least in 2.6, maybe 2.5). In any case, it could (and to me should) be lifted out of the string comp. >> >> (A less mathematical approach would just use i%15 to index a table. But >> that's not interesting. ;-) ) >> > > Ooh. Doesn't having 5 elements make you shudder? (Even though you did > change one to avoid a repeated value.) You have 4 options for output, so > for elegance that list should also have 4 elements: > > [[str(i), 'FizzBuzz', 'Fizz', 'Buzz'][25/(pow(i, 4, 15) + 1)%4] for i in > xrange(1, 101)] > > I feel it is even more elegant with the lookup table in its natural order: > > [['Fizz', 'Buzz', 'FizzBuzz', str(i)][62/(pow(i, 4, 15) + 1)%4] for i in > xrange(1, 101)] These make the lookup table variable, so it has to be recalculated for each i. tjr From Lie.1296 at gmail.com Tue Jun 3 09:04:57 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 3 Jun 2008 06:04:57 -0700 (PDT) Subject: Generating event from event References: <37f8a6a1-dc98-4985-a84d-f74ead1ec2b7@z72g2000hsb.googlegroups.com> <6aanqgF36mnldU1@mid.uni-berlin.de> <2980f056-a68f-4d8e-9104-642ef5911fcf@k37g2000hsf.googlegroups.com> <82471cd7-55bb-4376-bcae-3a601ed8f75a@c65g2000hsa.googlegroups.com> Message-ID: On May 31, 1:27?am, Mike Driscoll wrote: > On May 30, 12:11?pm, Gandalf wrote: > > > Hi Diez, I can't see how it ?matter which GUI-Toolkit i uses because I > > can combine libraries. > > I think all that matter is that i work with windows XP. > > > if you ever done something like that or you familiar with article > > which can show me how to implement what I asked it would help me > > > Thank you very much > > It matters because each Python GUI toolkit works differently. Tkinter > does it via Tk/tcl calls, wxPython uses the wx library and pyGTK does > it in yet another way. The basic ideas are the same, but the > implementations are quite different. > > In wx, for example, there are mouse events called wx.MouseEvent: > > http://www.wxpython.org/docs/api/wx.MouseEvent-class.html > > In Tkinter, they do the same thing, but the calls are almost > completely different. See the following for examples: > > http://www.pythonware.com/library/tkinter/introduction/events-and-bin... > > You probably either want the MouseEvents or to create an > AcceleratorTable. > > Mike I'd get frustated enough to *plonk* someone like him if he keeps refusing to answer an information that is already requested and already mentioned of the significance. From gagsl-py2 at yahoo.com.ar Tue Jun 3 22:12:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 03 Jun 2008 23:12:00 -0300 Subject: Handling some isolated iso-8859-1 characters References: Message-ID: En Tue, 03 Jun 2008 15:38:09 -0300, Daniel Mahoney escribi?: > I'm working on an app that's processing Usenet messages. I'm making a > connection to my NNTP feed and grabbing the headers for the groups I'm > interested in, saving the info to disk, and doing some post-processing. > I'm finding a few bizarre characters and I'm not sure how to handle them > pythonically. > > One of the lines I'm finding this problem with contains: > 137050 Cleo and I have an anouncement! "Mlle. > =?iso-8859-1?Q?Ana=EFs?=" > Sun, 21 Nov 2004 16:21:50 -0500 > 4478 69 Xref: > sn-us rec.pets.cats.community:137050 > > The interesting patch is the string that reads > "=?iso-8859-1?Q?Ana=EFs?=". > An HTML rendering of what this string should look would be "Anaïs". > > What I'm doing now is a brute-force substitution from the version in the > file to the HTML version. That's ugly. What's a better way to translate > that string? Or is my problem that I'm grabbing the headers from the NNTP > server incorrectly? No, it's not you, those headers are formatted following RFC 2047 Python already has support for that format, use the email.header class, see -- Gabriel Genellina From mccredie at gmail.com Thu Jun 26 11:19:29 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 26 Jun 2008 08:19:29 -0700 (PDT) Subject: ConfigParser: Can I read(ConfigParser.get()) a configuration file and use it to call a funciton? References: <34b51593-d787-4f12-9cc2-473d3832ff0d@k37g2000hsf.googlegroups.com> Message-ID: <7fd37b8c-b96d-480c-94c4-e53f8598830e@d45g2000hsc.googlegroups.com> On Jun 26, 7:41?am, jamitwi... at gmail.com wrote: > Hello. I am a novice programmer and have a question > > I have a configuration file(configuration.cfg) > I read this from reading.py using ConfigParser > When I use ConfigParser.get() function, it returns a string. > I want to call a function that has the same name as the string from > the configuration file. > > configuration.cfg > --------------------------------------- > [1234] > title: abcd > function: efgh > --------------------------------------- > > reading.py > -------------------------------------------------------- > import ConfigParser > > def efgh(): > ? ?print 'blah' > > config = ConfigParser.ConfigParser() > config.read('configuration.cfg') > > fcn = config.get('1234','function') > type(fcn) > print fcn > -------------------------------------------------------- > > > efgh > > Is there any way to call efgh() ? > One way I know is using if statement > if fcn == 'efgh': > ? ?efgh() > > But I am going to have many functions to call, so I want to avoid > this. > > Thank you for your help Something like this: globals()[fcn]() From bignose+hates-spam at benfinney.id.au Tue Jun 3 09:31:34 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 03 Jun 2008 23:31:34 +1000 Subject: Code correctness, and testing strategies References: Message-ID: <87d4mymyq1.fsf@benfinney.id.au> Duncan Booth writes: > I made the mistake at one point when I was trying to sell the > concept of TDD telling the people I was trying to persuade that by > writing the tests up front it influences the design of the code. I > felt the room go cold: they said the customer has to sign off the > design before we start coding, and once they've signed it off we > can't change anything. It's for misunderstandings like you describe here that I prefer (these days) to use the term "behaviour driven development". The coding is driven by desired new and/or altered behaviour of the application; everything else follows from that statement of direction. People, such as customers, who don't care about the term "unit test" can easily relate to the term "behaviour". They are happy to talk about how they want the application to behave, and are usually easy to convince that such descriptions of behaviour are what should be the driving force behind the implementation. -- \ "Truth would quickly cease to become stranger than fiction, | `\ once we got as used to it." -- Henry L. Mencken | _o__) | Ben Finney From jason at tishler.net Mon Jun 9 09:15:29 2008 From: jason at tishler.net (Jason Tishler) Date: Mon, 09 Jun 2008 09:15:29 -0400 Subject: Invalid Version Number (Distutils from Cygwin) In-Reply-To: <17714617.post@talk.nabble.com> References: <17714617.post@talk.nabble.com> Message-ID: <20080609131529.GA3324@tishler.net> On Sat, Jun 07, 2008 at 05:34:21PM -0700, newbie73 wrote: > [snip] > I'm attempting to build a project (FANN libraries) using cygwin (to > avoid installing MSVC 2003) and am receiving this error: > > Traceback (most recent call last): > [snip] > ValueError: invalid version number '2.18.50.20080523' The above is a known issue: http://bugs.python.org/issue2234 Unfortunately, resolution of this issue has stalled. Additionally, someone posted a different regular expression to the Cygwin list that is suppose to handle more cases of ld version strings: http://cygwin.com/ml/cygwin/2008-05/msg00622.html Can we reach consensus on what is the best ld version string regular expression to use? If so, then I will work to get this change committed to the Python code base and release a patched Cygwin Python 2.5.2 with this fix included. Thanks, Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From t_spens at yahoo.com Thu Jun 26 15:15:13 2008 From: t_spens at yahoo.com (Tim Spens) Date: Thu, 26 Jun 2008 12:15:13 -0700 (PDT) Subject: simplest c python api callback example Message-ID: <274270.13633.qm@web45105.mail.sp1.yahoo.com> The following is a simple complete example using the c python api to generate callbacks from c to python. But when I run the c code I get a segfault in PyInt_FromLong () (see below). Most of this example code was taken from pg 1478 of the 3rd edition python o'reilly book. I cannot see what I'm doing wrong here to get this segfault? Please help. //-------------------python-code-------------------------// #! /usr/bin/env python ####################################################### # register for and handle event callbacks from C; # compile C code, and run with 'python register.py' ####################################################### import time # # C calls these Python functions; # handle an event, return a result # def callback1(label, count): return 'callback1 called with args: label-%s and count-%i' % (label, count) # # Python calls a C extension module # to register handlers, trigger events # import cregister cregister.setpythonHandler(callback1) print '\nwaiting for callback pythonHandler to be called:' while 1: time.sleep(1) //-------------------compiler commands--------------// gcc -Wall -fno-strict-aliasing -g -I /usr/include/python2.5 -c cregister.c;gcc -g -Wall -I /usr/include/python2.5 -L /usr/local/lib -lpython2.5 cregister.c -o cregister;gcc -shared -fPIC -g -Wall -I /usr/include/python2.5 -L /usr/lib -lpython2.5 -o cregister.so cregister.o //-------------------c-code-------------------------// #include #include /***********************************************/ /* 1) code to route events to Python object */ /* note that we could run strings here instead */ /***********************************************/ //python handlers //keep Python object in C static PyObject *pythonHandler = NULL; void Route_Event(){ PyObject *args; // call Python handler args = Py_BuildValue("(si)", "c code", 5); PyEval_CallObject(pythonHandler, args); } /*****************************************************/ /* 2) python extension module to register handlers */ /* python imports this module to set handler objects */ /*****************************************************/ static PyObject * Register_pythonHandler(PyObject *self, PyObject *args){ // save Python callable object Py_XDECREF(pythonHandler); //called before? PyArg_Parse(args, "O", &pythonHandler); //one argument? Py_XINCREF(pythonHandler); //add a reference Py_INCREF(Py_None); //return 'None': success return Py_None; } //makes these functions available by importing cregister in python static struct PyMethodDef cregister_methods[] = { {"setpythonHandler", Register_pythonHandler}, {NULL, NULL} }; // this is called by Python on first "import cregister" void initcregister(){ (void) Py_InitModule("cregister", cregister_methods); } int main(){ while (1){ PyObject *arglist; arglist = Py_BuildValue("(si)", "c code", 5); Py_XINCREF(pythonHandler); Py_XINCREF(arglist); PyEval_CallObject(pythonHandler, arglist); Py_XDECREF(pythonHandler); Py_XDECREF(arglist); sleep(1); } } Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 0xb7c1c6b0 (LWP 13699)] 0xb7e0bcfb in PyInt_FromLong () from /usr/lib/libpython2.5.so.1.0 (gdb) bt #0 0xb7e0bcfb in PyInt_FromLong () from /usr/lib/libpython2.5.so.1.0 #1 0xb7e8cae6 in ?? () from /usr/lib/libpython2.5.so.1.0 #2 0x00000005 in ?? () #3 0x00000006 in ?? () #4 0xbf89a378 in ?? () #5 0xb7e9d095 in _PyObject_GC_Malloc () from /usr/lib/libpython2.5.so.1.0 #6 0xb7e8d1dd in ?? () from /usr/lib/libpython2.5.so.1.0 #7 0x00000002 in ?? () #8 0x08048320 in ?? () #9 0x72d6dafa in ?? () #10 0x00000029 in ?? () #11 0xbf89a474 in ?? () #12 0xbf89a478 in ?? () #13 0x00000000 in ?? () From patrickstinson.lists at gmail.com Wed Jun 4 18:33:18 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Wed, 4 Jun 2008 14:33:18 -0800 Subject: python, dlls, and multiple instances In-Reply-To: <4842ed97$0$25496$9b622d9e@news.freenet.de> References: <4842ed97$0$25496$9b622d9e@news.freenet.de> Message-ID: <6214d7a20806041533p75e4a621w262ae36b0cf0cc48@mail.gmail.com> ahh, ok. Looks like my fundamental understanding of how dlls work was a little messed up. Thanks! On Sun, Jun 1, 2008 at 10:42 AM, "Martin v. L?wis" wrote: >> Is it a correct to assume that you can use multiple instances of >> python altogether if each is loaded from a separate dll? For instance, >> if I write a couple of dll/so libs, and each has python statically >> linked in, is it safe to assume that since dlls use their own address >> space > > DLLs don't use their own address space. All DLLs of a single operating > system process use the same address space. > > Different DLLs do use different portions of that address space. > >> then each dll would have it's own GIL, and will therefore >> coexist safely within the same app? This is correct across all >> platforms, yes? > > No; it rather depends on the way the operating system resolves symbols. > On some systems (e.g. many Unix systems), there is only a single global > symbol table for the entire process. So when a shared library is loaded, > and needs to resolve its symbols (even the ones that it also defines > itself), it may end up finding the GIL in a different copy of the Python > interpreter, so they all share the GIL (even though there would have > been space for multiple GILs). > > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list > From bruno.desthuilliers at gmail.com Fri Jun 20 17:06:04 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 20 Jun 2008 14:06:04 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> <485bd4f8$0$30999$426a74cc@news.free.fr> Message-ID: On 20 juin, 21:41, eliben wrote: > > [1] except using compile to build a code object with the function's > > body, then instanciate a function object using this code, but I'm not > > sure whether it will buy you much more performance-wise. I'd personnaly > > prefer this because I find it more explicit and readable, but YMMV. > > How is compiling more readable than exec - Using compile and function(), you explicitely instanciate a new function object, while using exec you're relying on a side effect. > doesn't it require an extra > step ? Well... Your way: d = {} exec code in globals(), d return d['foo'] My way: return function(compile(code, '', 'exec'), globals()) As far as I'm concern, it's two steps less - but YMMV, of course !-) > You generate code dynamically anyway. Yes, indeed. Which may or not be the right thing to do here, but this is a different question (and one I can't actually answer). From google at mrabarnett.plus.com Wed Jun 18 19:29:50 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 18 Jun 2008 16:29:50 -0700 (PDT) Subject: advanced listcomprehenions? References: <717129b5-d92f-4be2-ae6a-037870bfa407@2g2000hsn.googlegroups.com> Message-ID: <1fd4a490-cb70-4659-8912-d5b6febe2705@d1g2000hsg.googlegroups.com> On Jun 18, 10:42?pm, cirfu wrote: > I am wondering if it is possible to write advanced listcomprehensions. > > For example: > """Write a program that prints the numbers from 1 to 100. But for > multiples of three print "Fizz" instead of the number and for the > multiples of five print "Buzz". For numbers which are multiples of > both three and five print "FizzBuzz".""" > Obv it doesnt have to be a list according tot hat definition but > suppose i want to generate that list. > > >>> [["Fizzbuzz",x] for x in xrange(1,101) if x%3 == 0 and x%5 == 0] > > [['Fizzbuzz', 15], ['Fizzbuzz', 30], ['Fizzbuzz', 45], ['Fizzbuzz', > 60], ['Fizzbuzz', 75], ['Fizzbuzz', 90]] > > is not what i want. the following does the trick but is ldo not a > listcomprehension: > > for i in xrange(1,101): > ? ? s = "" > ? ? if i%3 == 0: > ? ? ? ? s += "Fizz" > ? ? if i%5 == 0: > ? ? ? ? s += "Buzz" > ? ? if s: > ? ? ? ? print "%d : %s" % (i,s) > ? ? else: > ? ? ? ? print i > > or to generate a lisrt but not by listcomprehsnion: > map(lambda x: (not x%3 and not x%5 and "FizzBuzz") or (not x%3 and > "Fizz") > or (not x%5 and "Buzz") or x, xrange(1,101)) [("FizzBuzz" if n % 15 == 0 else "Fizz" if n % 3 == 0 else "Buzz" if n % 5 == 0 else str(n)) for n in range(1, 101)] From saluk64007 at gmail.com Tue Jun 10 14:56:05 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Tue, 10 Jun 2008 11:56:05 -0700 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> <484cf5f6$0$15495$426a74cc@news.free.fr> <127975a3-b3d9-4799-9673-b292ec8d37e3@x19g2000prg.googlegroups.com> <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> <484e3526$0$30894$426a74cc@news.free.fr> <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> Message-ID: Hi Russ, Here are just some pragmatic considerations. Personally I am against data hiding, but I obviously won't convince you in that regard. There are some pros and cons as with anything, and I feel the cons outweight the pros (namely that users of code should be able to use how they want, even if it means shooting themselves in the foot; and the fact that priv somewhat breaks the dynamics of python) Even if your proposal were to go through, you are looking at probably 2 years before it can even be used. Python3 is basically in freeze mode, and it contains the biggest change in python syntax for a long time. I know it doesn't seem like a big change to you to add a priv keyword, but python very rarely adds keywords, so it's a long shot merely for that reason. This is something that potentially would be under consideration for something like 3.2 or higher I think, so if you want to get the job done now, this topic or trying to convince other long time python users isn't going to accomplish your goals. Leading underscore takes two keystrokes to type (shift, _) while priv, private, etc takes many more. If you are too lazy to type "_var" then how come you aren't too lazy to type "priv var"? Too me it seems like more typing. If the primary objection to leading underscores is looks, it seems like you unnecesarily avoid them for a pointless reason. There are ugly aspects to every language, and there isn't really a better convention to use that I can see. Without of course implementing keywords, which are conceptually difficult to think about in terms of python object model - although you might be able to come up with a way. But if you have a better naming convention or strategy that you want to try on your code, nothing is stopping you. You can use one of the hacks found in this thread, or come up with your own hack, to more or less accomplish what you want. It should take 30 minutes or less to set up, and you are done with it. The internals of python make it difficult to do more than that, but you are welcome to create your own python fork if you think you are up to it. Although I think that would be more than 30 minutes of work. And feel free to try other languages. No one claimed python is the best for every circumstance. Well, if someone claimed that they are just fooling themselves. Python is a good hacker language that scales pretty well into enterprise and web services; and can be used for other things as well. I don't believe that data prevention (we aren't really talking about just hiding here) is necessary for 99% of tasks, but other people think differently, so there are plenty of languages that implement these features. Good luck finding a solution to fit your project. However I don't think trying to get a "priv" keyword into official python is feasable unless you want to wait a very long time and go hoarse from shouting :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at divmod.com Sun Jun 29 10:11:15 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 29 Jun 2008 10:11:15 -0400 Subject: Why is recursion so slow? In-Reply-To: <5504f9ac0806290703h1bf44639jbfe5331c4a2d1369@mail.gmail.com> Message-ID: <20080629141115.4714.638077829.divmod.quotient.14914@ohm> On Sun, 29 Jun 2008 10:03:46 -0400, Dan Upton wrote: >On Sun, Jun 29, 2008 at 1:27 AM, Terry Reedy wrote: >> >> >> slix wrote: >>> >>> Recursion is awesome for writing some functions, like searching trees >>> etc but wow how can it be THAT much slower for computing fibonacci- >>> numbers? >> >> The comparison below has nothing to do with recursion versus iteration. (It >> is a common myth.) You (as have others) are comparing an exponential, >> O(1.6**n), algorithm with a linear, O(n), algorithm. >> > >FWIW, though, it's entirely possible for a recursive algorithm with >the same asymptotic runtime to be wall-clock slower, just because of >all the extra work involved in setting up and tearing down stack >frames and executing call/return instructions. (If the function is >tail-recursive you can get around this, though I don't know exactly >how CPython is implemented and whether it optimizes that case.) CPython doesn't do tail call elimination. And indeed, function calls in Python have a much higher fixed overhead than iteration. Jean-Paul From mathieu.malaterre at gmail.com Wed Jun 4 09:59:27 2008 From: mathieu.malaterre at gmail.com (mathieu) Date: Wed, 4 Jun 2008 06:59:27 -0700 (PDT) Subject: Distributing 2 python modules with incompatible API Message-ID: hi there, As far as I understand python is not using the usual UNIX system of soname when two libraries provide incompatible API. So let say I have a _foo.so version 1.2 and 2.0, all I can (should do) is move them underneath a subdirectory in site-package: pythonX.Y/site-package/foo1.2/_foo.so pythonX.Y/site-package/foo1.2/foo.py and pythonX.Y/site-package/foo2.0/_foo.so pythonX.Y/site-package/foo2.0/foo.py Then a central foo.pth would (sytem-wide) define which one is the default version: pythonX.Y/site-package/foo.pth If this is correct ? Is there any documentation that I missed ? Thanks -Mathieu From JKPeck at gmail.com Wed Jun 25 09:29:28 2008 From: JKPeck at gmail.com (JKPeck) Date: Wed, 25 Jun 2008 06:29:28 -0700 (PDT) Subject: Using the backing store with mmap Message-ID: <402eaad5-6fb7-4b61-80dc-bb64840b94cb@m44g2000hsc.googlegroups.com> According to the mmap.mmap 2.5 documentation, "Changed in version 2.5: To map anonymous memory, -1 should be passed as the fileno along with the length." I would like to use shared memory to communicate between two processes that otherwise have no way to communicate, but I couldn't find a way to share anonymous memory. (I can use file names agreed on by convention, but the file is really irrelevant, and I'd prefer to eliminate it.) Is this possible? What is the lifetime of this shared memory? Is it in fact private to the creating process, or is it shared among all (Python) processes? Does it need to be flushed by a writing process? How do the access flags relate to this? If I create two such items, are they independent, or is it all one pool? TIA, Jon Peck From duncan.booth at invalid.invalid Tue Jun 17 04:20:42 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Jun 2008 08:20:42 GMT Subject: Does '!=' equivelent to 'is not' References: Message-ID: "Leo Jay" wrote: > same objects are equal, but equal don't have to be the same object. same objects are often equal, but not always: >>> inf = 2e200*2e200 >>> ind = inf/inf >>> ind==ind False >>> ind is ind True -- Duncan Booth http://kupuguy.blogspot.com From mccredie at gmail.com Fri Jun 13 12:55:04 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 13 Jun 2008 09:55:04 -0700 (PDT) Subject: weird iteration/assignment problem References: <61936860-de3f-4bb1-8806-08f9f21ad113@m36g2000hse.googlegroups.com> <6bfgpoF3bpl84U1@mid.uni-berlin.de> Message-ID: On Jun 13, 8:07 am, "Diez B. Roggisch" wrote: > cirfu schrieb: > > > for i in xrange(0, len(texts)): > > texts[i] = "yes" > > > for i in texts: > > i = "no" > > > why is the first one working but not the second. i mean i see why the > > firts one works but i dont udnerstand why the second doesnt. > > Because in the second you only bind the contents of texts to a name i. > > But that doesn't mean that i magically became an "alias" for > texts[index] - it just happens to point at the same object. > > To accomplish what you want, the pythonic idiom is to use enumerate: > > for i, text in enumerate(texts): > text[i] = "yes" > > Diez That should be: for i, text in enumerate(texts): texts[i] = "yes" From larry.bates at websafe.com` Sun Jun 1 07:41:14 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 01 Jun 2008 06:41:14 -0500 Subject: Need Tutorial For the following lib In-Reply-To: <0bdd04b8-23b6-4a68-bda2-6984428ce7bd@b1g2000hsg.googlegroups.com> References: <9950cf3f-e58a-413a-bdff-a40cc1c6cf6d@8g2000hse.googlegroups.com> <0bdd04b8-23b6-4a68-bda2-6984428ce7bd@b1g2000hsg.googlegroups.com> Message-ID: <4KCdnQj2nvh7F9_VnZ2dnUVZ_uidnZ2d@comcast.com> Gandalf wrote: > Hi scott, you couldn't be more wrong about my laziness. I straggle > with my poor English for hours to fined what I'm looking for. > I found a very simple and not comprehensive tutorial for the pyWinAuto > lib in this address http://pywinauto.openqa.org/ > but it only show how to do the basic, and my knowledge at this point > is not enough to figure the rest I need to know by myself > I found another simple lib for the watsup that based on winGuiAuto > lib in this address > http://www.tizmoi.net/watsup/intro.html > But for some risen I couldn't manage to ran it in my computer > > I'm trying to generate auto mouse double click or auto selecting text > (the selecting text part is the one I interest in. mouse double click > just do the same effect if the mouse cursor is on text) > > I'm sorry you feel I'm lazy. The truth is that event writing this > message takes me an enormous power. > weather you choose to help me or not I still going to keep trying , > But you have the opportunity to save me lots of trouble, So maybe one > day I could help others. > > so if you familiar with any good tutorial for this library please let > me know and if not then thank you anyway for wonting to help > > Y.G > > > What you want is an easy solution to what isn't an easy problem, but (as with your other post) you refuse to provide enough information to allow us to help you. If I were you, I would download wxPython and go through the demos that it includes. comp.python.wxpython list is excellent (at least as good as this one) for any follow-up questions. Windows events and mouse clicks are going to take a concerted effort (on your part) to learn (especially if you haven't accomplished such a task in another language). -Larry From Pratip.Mukherjee at FMR.COM Tue Jun 17 08:57:41 2008 From: Pratip.Mukherjee at FMR.COM (Mukherjee, Pratip) Date: Tue, 17 Jun 2008 08:57:41 -0400 Subject: How do I avoid using HTTPRedirectHandler with urllib2? Message-ID: Hi, I am new to Python, trying it as an alternative to Perl. I am having problem with python HTTP handling library, urllib2. How do I avoid using the HTTPRedirectHandler while making a HTTP request? For those familiar to Perl-LWP, this is done by using simple_request() on the UserAgent object. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From socyl at 987jk.com.invalid Mon Jun 9 11:54:28 2008 From: socyl at 987jk.com.invalid (kj) Date: Mon, 9 Jun 2008 15:54:28 +0000 (UTC) Subject: Q re documentation Python style References: Message-ID: Wow. That was a great bunch of advice. Thank you all very much! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From asdf at asdf.com Tue Jun 10 21:05:45 2008 From: asdf at asdf.com (asdf) Date: 11 Jun 2008 01:05:45 GMT Subject: Dynamic HTML from Python Script References: <484f151c$0$5009$607ed4bc@cv.net> <484f21aa$1@dnews.tpgi.com.au> Message-ID: <484f24e9$0$5020$607ed4bc@cv.net> > Well, there's a few ways you could approach it. > > You could create a cgi program from your script - this is probably the > solution you're looking for. > Output from the script does come up very often. There is a new output every 10 secs and it's possible that the script might be run indefinitely. Basically I want all that output displayed in a web browser > You could have the script run periodically and create a static html file > in the webroot... this would be acceptable, maybe preferable, if the > output from your script doesn't change frequently. > From kurdayon at yahoo.com Fri Jun 27 17:41:01 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Fri, 27 Jun 2008 14:41:01 -0700 (PDT) Subject: "method involving two objects" is that possible in Python? Message-ID: <8c8aec73-bd5b-4dfc-b91a-b100f3b9ddfa@m73g2000hsh.googlegroups.com> Hi, I just started to learn Python. I understood how one can create a class and define a method related with that class. According to my understanding every call of a methods is related with a specific object. For example, we have a method "length", than we call this method as the following "x.length()" or "y.length()" or "z.length()", where z, y, and z are objects of the class. I am wandering if it is possible to create a method which is related not with a single object (as in the previous example) but with a pare of objects. For example, I want to have a class for vectors, and I want to have a methods which calculate a dot product of two vectors. One of the possibilities is to use __mul__ and that I calculated dot product of "x" and "y" just as "x * y". However, I am wandering if I can declare a method in a way that allows me to calculate dot product as "dot(x,y)". Thank you in advance. From healey.rich at gmail.com Mon Jun 23 21:09:21 2008 From: healey.rich at gmail.com (Rich Healey) Date: Tue, 24 Jun 2008 11:09:21 +1000 Subject: IDE on the level of Eclipse or DEVc++? In-Reply-To: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> Message-ID: <48604941.6030707@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 cirfu wrote: > is there an IDE for python of the same quality as Eclipse or DEVC++? > > I am currently using the editor that coems iwth python and it is all > fine but for bigger projects it would be nice to have some way to > easier browse the projectfiles for example. I don't want to start a flamewar. But I like vim. - -- Rich Healey - healey.rich at gmail.com Developer / Systems Admin - OpenPGP: 0x8C8147807 MSN: bitchohealey at hotmail.com AIM: richohealey33 irc.psych0tik.net -> #hbh #admins richohealey irc.freenode.org -> #hbh #debian PythonNinja -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFIYElBLeTfO4yBSAcRAvjqAJ9DIbb5qxLTh+s2k0AsUkmxoC0TtACdFj3x hxVamWJkbDsslu8F+QhG2xA= =G4vQ -----END PGP SIGNATURE----- From rhamph at gmail.com Wed Jun 11 13:55:14 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Wed, 11 Jun 2008 10:55:14 -0700 (PDT) Subject: Producer-consumer threading problem References: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> <9482cbb7-297e-4429-b7a1-6d7c1dcc9070@t12g2000prg.googlegroups.com> <3d0a1204-526b-4447-a2cf-7f40860bb299@d1g2000hsg.googlegroups.com> Message-ID: <35245867-5534-4d3b-a86d-f469d44a4dda@q27g2000prf.googlegroups.com> On Jun 11, 6:00 am, George Sakkis wrote: > On Jun 11, 1:59 am, Rhamphoryncus wrote: > > > Why not use a normal Queue, put a dummy value (such as None) in when > > you're producer has finished, and have the main thread use the normal > > Thread.join() method on all your child threads? > > I just gave two reasons: > - Concurrency / interactivity. The main thread shouldn't wait for all > one million items to be produced to get to see even one of them. Then don't wait. The main thread can easily do other work while the producer and consumer threads go about their business. > - Limiting resources. Just like iterating over the lines of a file is > more memory efficient than reading the whole file in memory, getting > each consumed item as it becomes available is more memory efficient > than waiting for all of them to finish. That's why you give Queue a maxsize. Put it at maybe 5 or 10. Enough that the producer can operate in a burst (usually more efficient that switching threads after each item), then the consumer can grab them all in a burst. Then again, you may find it easier to use an event-driven architecture (like Twisted, as others have suggested.) From asdf at asdf.com Mon Jun 16 21:16:54 2008 From: asdf at asdf.com (asdf) Date: 17 Jun 2008 01:16:54 GMT Subject: 2Q's: How to autocreate instance of class;How to check for membership in a class Message-ID: <48571086$0$5010$607ed4bc@cv.net> So I'm writing a script which will create several instances of User() class. I want each instance to be named after the login name of a user. I don't know beforehand how many users the script will have to create or how they are named. Right now I've created a dictionary of usernames as keys and objects themselves as values. It works, but is very unwieldy, because every time I need to access a value from within an object I have to do something like dict-user[x].value. Is there a way of automatically naming objects from variable names. So for example if I know that var1=jsmith. Can I somehow do var1=User(). This obviously won't work because I tried this. It'll just create var1 of type User. My second question is how can I check if object is a member of a class. so let's say I create a=User(), b=User()... Can I do something similar to if x.Users()==TRUE: print "user already created" Right now I'm doing this using try-except which works but I'm looking for something cleaner. thanks for all the replies. From jgardner at jonathangardner.net Mon Jun 30 16:21:54 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 30 Jun 2008 13:21:54 -0700 (PDT) Subject: ask for a RE pattern to match TABLE in html References: <6a4f17690806260653i136681bdsabe0f6bb1dfab67b@mail.gmail.com> <62f752f3-d840-42de-a414-0d56d15d7c5a@w4g2000prd.googlegroups.com> Message-ID: <87bb8346-6498-4e51-b065-88d915dcff0d@p39g2000prm.googlegroups.com> On Jun 27, 10:32?am, "David C. Ullrich" wrote: > (ii) The regexes in languages like Python and Perl include > features that are not part of the formal CS notion of > "regular expression". Do they include something that > does allow parsing nested delimiters properly? > In perl, there are some pretty wild extensions to the regex syntax, features that make it much more than a regular expression engine. Yes, it is possible to match parentheses and other nested structures (such as HTML), and the regex to do so isn't incredibly difficult. Note that Python doesn't support this extension. See http://www.perl.com/pub/a/2003/08/21/perlcookbook.html From metallourlante at gmail.com Mon Jun 23 10:55:07 2008 From: metallourlante at gmail.com (Alex) Date: Mon, 23 Jun 2008 07:55:07 -0700 (PDT) Subject: learning unit testing in python Message-ID: Hi all. I'd like learn some basic unit testing with python. I red some articles about different testing framework like unittest or nose, but I'm a bit confused: what is the best choice? I'm not a professional developer (I'm a SEO) but I belive that unit testing is a good and pragmatic way to produce working software, so I'd like to find something really simple ad straightforward because I don't have to manage big programming projects. Thanks in advance, Alex From noagbodjivictor at gmail.com Sat Jun 28 23:22:51 2008 From: noagbodjivictor at gmail.com (Victor Noagbodji) Date: Sat, 28 Jun 2008 23:22:51 -0400 Subject: HTML Parsing Message-ID: > Hi everyone Hello > I am trying to build my own web crawler for an experiement and I don't > know how to access HTTP protocol with python. urllib2: http://docs.python.org/lib/module-urllib2.html > Also, Are there any Opensource Parsing engine for HTML documents > available in Python too? That would be great. BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/ http://www.crummy.com/software/BeautifulSoup/documentation.html All the best -- NOAGBODJI Paul Victor From badmuthahubbard at gmail.com Thu Jun 5 04:52:33 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Thu, 5 Jun 2008 11:52:33 +0300 Subject: Interesting Math Problem In-Reply-To: <748f2d520806040103q48689a01i310ee07df20a5e73@mail.gmail.com> References: <748f2d520806040103q48689a01i310ee07df20a5e73@mail.gmail.com> Message-ID: <8200bab70806050152u68aecf48hb2caffdf58c9aa5d@mail.gmail.com> On Wed, Jun 4, 2008 at 11:03 AM, BEES INC wrote: > My Solution (in Python): > > # round to one decimal place and > # separate into whole and fractional parts > parts = str(round(star_sum/num_raters, 1)).split('.') > whole = int(parts[0]) > frac = int(parts[1]) > if frac < 3: > ___frac = 0 > elif frac > 7: > ___frac = 0 > ___whole += 1 > else: > ___frac = 5 > # recombine for a star rating rounded to the half > stars = float(str(whole)+'.'+str(frac)) def roundstars(invalue): inv *= 2 inv += .5 return float(int(inv))/2 seems to work for me. > Mmmm? In-N-Out Burgers? Please reply if you've got a better solution. I've never had the pleasure, but I've heard they're a wonderful experience. -Chuckk -- http://www.badmuthahubbard.com From george.sakkis at gmail.com Thu Jun 12 00:41:21 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 11 Jun 2008 21:41:21 -0700 (PDT) Subject: Confusion with weakref, __del__ and threading References: <113f383e-9027-461b-88db-7e5331e7d361@59g2000hsb.googlegroups.com> <7ed2109d-3b88-484c-9d19-67706747c95f@v26g2000prm.googlegroups.com> <5da23b98-9434-41d4-9dd1-0a423fd387b1@26g2000hsk.googlegroups.com> <2a3ae0a4-144b-44ce-8e30-53b5586ccb7e@w4g2000prd.googlegroups.com> Message-ID: <68a9447a-799e-4143-8724-2ff55fc24b0c@w7g2000hsa.googlegroups.com> On Jun 11, 8:37?pm, Rhamphoryncus wrote: > On Jun 11, 2:15 pm, George Sakkis wrote: > > > > > On Jun 11, 2:01 pm, Rhamphoryncus wrote: > > > > On Jun 11, 10:43 am, George Sakkis wrote: > > > > > On Jun 11, 1:40 am, Rhamphoryncus wrote: > > > > > The trick here is that calling proxy.sleep(0.01) first gets a strong > > > > > reference to the Mystery instance, then holds that strong reference > > > > > until it returns. > > > > > Ah, that was the missing part; I thought that anything accessed > > > > through a proxy didn't create a strong reference. The good thing is > > > > that it seems you can get a proxy to a bounded method and then call it > > > > without creating a strong reference to 'self': > > > > That's not right. ?Of course a bound method has a strong reference to > > > self, otherwise you'd never be able to call it. ?There must be > > > something else going on here. ?Try using sys.setcheckinterval(1) to > > > make threads switch more often. > > > I tried that and it still works; all objects die at the main thread. > > Any other idea to break it ? > > Nothing comes to mind. > > However, none of this is guaranteed anyway, so you can't rely on it. > __del__ might be called by any thread at any point (even when you're > holding a lock, updating a datastructure.) Ok, you scared me enough to cut the link to the thread altogether, avoiding the cyclic reference and the weakref proxy. The original intent for keeping a reference to the thread was to be able to join() it later before some cleanup takes place. I have since found a less spooky way to synchronize them but regardless, I'd be interested for an explanation of what's really going on in the posted snippets. George From gagsl-py2 at yahoo.com.ar Tue Jun 24 05:23:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 24 Jun 2008 06:23:57 -0300 Subject: string.Template.delimiter cannot be overriden? References: <4rH5k.2032$to3.1384@newsfe15.phx> <35e212be-e85b-41fd-90c2-f90959053232@l28g2000prd.googlegroups.com> Message-ID: En Tue, 17 Jun 2008 02:20:23 -0300, Raymond Hettinger escribi?: > On Jun 16, 9:53?pm, kretik wrote: >> I've been trying to coax this class to use something other than the >> default '$' but it seems setting it to something else has no discernible >> effect. Is it necessary to inherit from the class to do this? > > Yes, subclassing is the intended way to produce variants of Template > with a different delimiter. Just out of curiosity, why was it done that way? I'd say the "obvious" way to change the default delimiter would be to set an instance attribute - so I guess this was a deliberate decision, but I can't figure out why it is better this way... -- Gabriel Genellina From tjreedy at udel.edu Wed Jun 11 15:22:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Jun 2008 15:22:49 -0400 Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: "Frank Millman" wrote in message news:f7cc4f0f-3e37-43e7-927a-0ed14a063930 at 25g2000hsx.googlegroups.com... | Thanks to all for the various replies. They have all helped me to | refine my ideas on the subject. These are my latest thoughts. | | Firstly, the Decimal type exists, it clearly works well, it is written | by people much cleverer than me, so I would need a good reason not to | use it. Speed could be a good reason, provided I am sure that any | alternative is 100% accurate for my purposes. The Decimal module is a Python (now C coded in 2.6/3.0, I believe) implementation of a particular IBM-sponsored standard. The standard is mostly good, but it is somewhat large with lots of options (such as rounding modes) and a bit of garbage (the new 'logical' operations, for instance) added by IBM for proprietary purposes. Fortunately, one can ignore the latter once you recognize them for what they are. As Nick indicated, it is not the first in its general category. And I believe the Decimal implementation could have been done differently. By writing you own class, you get just what you need with the behavior you want. I think just as important is the understanding of many of the issues involved, even if you eventually switch to something else. That is a pretty good reason in itself. tjr From bignose+hates-spam at benfinney.id.au Sat Jun 7 00:52:46 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 07 Jun 2008 14:52:46 +1000 Subject: Dynamically naming objects. References: <8a99c3fa-1eeb-49b3-a714-b6063ec1daab@d19g2000prm.googlegroups.com> <3d2a85b2-255d-4e93-8cfb-e2772f57b69a@u6g2000prc.googlegroups.com> Message-ID: <87tzg5kfs1.fsf@benfinney.id.au> Kalibr writes: > what I want to do is have, say 5 users in a game, so I'd have to > spawn 5 objects. I can't do that because I have'nt hardcoded any > object names for them. Python's built-in mapping type 'dict' is a good fit for this. Given: * a 'User' class that is initialised with the user's name * some way of getting a sequence of names (that you haven't told us yet), that I'll bind here to the name 'sequence_of_names' You can then write:: game_users = {} for name in sequence_of_names: game_users[name] = User(name) This will result in 'game_users' bound to a dict with names mapping to separate instances of the 'User' type. These instances can each be addressed by name from the 'game_users' mapping as 'game_users["Fred"]', etc. -- \ "Pinky, are you pondering what I'm pondering?" "Well, I think | `\ so, Brain, but do I really need two tongues?" -- _Pinky and | _o__) The Brain_ | Ben Finney From healey.rich at gmail.com Tue Jun 17 03:10:41 2008 From: healey.rich at gmail.com (Rich Healey) Date: Tue, 17 Jun 2008 17:10:41 +1000 Subject: print problem In-Reply-To: References: <2MWdnYXqCY3yy8rVnZ2dnUVZ_sbinZ2d@posted.internode> Message-ID: <48576371.7000209@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Gabriel Genellina wrote: > En Tue, 17 Jun 2008 03:15:11 -0300, pirata escribi?: > >> I was trying to print a dot on console every second to indicates >> running process, so I wrote, for example: >> >> for i in xrange(10): >> print ".", >> time.sleep(1) >> >> Idealy, a dot will be printed out each second. But there is nothing >> print out until after 10 seconds, all 10 dots come out together. >> >> I've tried lose the comma in the print statement, and it works. >> >> Is that because of the print statement buffer the characters until >> there is a new line character? > > Very probably, altough I can't reproduce it on Windows. Try invoking the script with python -u (unbuffered input/output): > > python -u your_script.py > Or just write to sys.stdout without the print wrapper.. - -- Rich Healey - healey.rich at gmail.com Developer / Systems Admin - OpenPGP: 0x8C8147807 MSN: bitchohealey at hotmail.com AIM: richohealey33 irc.psych0tik.net -> #hbh #admins richohealey irc.freenode.org -> #hbh #debian PythonNinja -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFIV2NxLeTfO4yBSAcRAkunAJ9w5lavHK4TIUbexX+pSYmPla9oOQCfT8tM tzOhQgcpO7dEG7WhE6FNZ4w= =IqJ1 -----END PGP SIGNATURE----- From pavlovevidence at gmail.com Mon Jun 2 09:41:48 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 2 Jun 2008 06:41:48 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> Message-ID: <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> On Jun 2, 9:07 am, Antoon Pardon wrote: > On 2008-06-02, Carl Banks wrote: > > > > > On Jun 2, 6:40 am, Antoon Pardon wrote: > >> On 2008-06-02, Carl Banks wrote: > > >> > On Jun 2, 5:38 am, Antoon Pardon wrote: > >> >> If you really need it, you can do data hiding in python. It just > >> >> requires a bit more work. > > >> >> ----------------------------- Hide.py --------------------------------- > >> >> class Rec(object): > >> >> def __init__(__, **kwargs): > >> >> for key,value in kwargs.items(): > >> >> setattr(__, key, value) > > >> >> def __getitem__(self, key): > >> >> return getattr(self, key) > > >> >> def __setitem__ (self, key, val): > >> >> setattr(self, key, val) > > >> >> class Foo(object): > > >> >> def __init__(self): > > >> >> hidden = Rec(x=0, y=0) > > >> >> def SetX(val): > >> >> hidden.x = val > > >> >> def SetY(val): > >> >> hidden.y = val > > >> >> def GetX(): > >> >> return hidden.x > > >> >> def GetY(): > >> >> return hidden.y > > >> >> self.SetX = SetX > >> >> self.SetY = SetY > >> >> self.GetX = GetX > >> >> self.GetY = GetY > > >> > In other words, it's a useless no-op. > > >> > In fact, I'd say this is even worse than useless. Creating accessor > >> > functions is a sort of blessing for external use. Knowing that there > >> > are accessor functions is likely to cause a user to show even less > >> > restraint. > > >> I think you completed missed the point. > > > I'm not sure I missed the point so much as I failed to read your mind. > > Fine with me, it is just the other side of the coin. > > >> This is just a proof of concept thing. In a real example there would > >> of course no Set en Get methods but just methods that in the course > >> of their execution would access or update the hidden attributes > > > Fair enough, but I don't see anything in your example that suggests a > > way to discriminate between access from within the class and access > > from outside the class, which is the crucial aspect of data hiding. > > The fact is that hidden and its attributes are not accessible from > outside the instance. They are only accessible to the local functions > of __init__. By binding those local functions as atributes to the > instance, hidden can be modified by what for all practical purposes > looks like a method call, but really is a closure call. You haven't hidden the data at all, all you've done is to change the means of accessing it. What difference does it make whether I write foo.getX() or foo.x? Everyone in the world still has full access to the data. You are not realizing that only useful(**) thing about data hiding is that some code has access to the data, other code does not. If you "hide" data equally from everyone it's just a useless spelling change. ** - Usefulness is questionable in most cases, but we assume it is here for the sake of argument. Carl Banks From cournape at gmail.com Wed Jun 4 09:47:45 2008 From: cournape at gmail.com (David Cournapeau) Date: Wed, 4 Jun 2008 22:47:45 +0900 Subject: How to make py2.5 distutil to use VC2005? In-Reply-To: References: Message-ID: <5b8d13220806040647o1148bf90x6b2b546e9cb339b5@mail.gmail.com> On Wed, Jun 4, 2008 at 11:38 AM, ?? wrote: > Well, IMO, the format of binary files generated by VC2003 and > VC2005 is compatible in most cases. Problem arise with the C runtime, not with object file format. In particular, python uses the C api for file handling, and the standard C is definitely not ABI compatible within VS versions. I strongly advise you against using VS 2005 (with the binary python; if you build python by yourself, then no problem; I don't know if it is possible to build python with VS 2005). You *will* get crashes in many cases. David From wuwei23 at gmail.com Tue Jun 3 01:23:52 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 2 Jun 2008 22:23:52 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> Message-ID: <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> On Jun 3, 2:11 pm, "Russ P." wrote: > Yes, that looks interesting, but I think it has a couple of drawbacks. > First, it requires another completely separate class for the > "implementation" (although perhaps that could be a nested class). That's hardly an enormous overhead, and it does clearly separate the interface you want your "users" to have from the implementation. Even better, since you seem so concerned with others meddling with your implementation directly, they could provide their own quite easily if they so choose. > Secondly, I think it essentially just adds a sort of inner namespace > through which the "private" data is accessed. That might be a good > idea, but I don't think it's quite the same as encapsulation. It's a clear separation of concerns, check. It removes the underscored methods you find so aesthetically offensive, check. I have absolutely no idea what _you_ mean by "encapsulation". Then again, I have no issue with the current convention and personally find the idea of adding a "private" keyword makes as much sense as being able to syntactically define "model", "view" and "controller" methods. From benjamin.kaplan at case.edu Sun Jun 29 11:42:33 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 29 Jun 2008 11:42:33 -0400 Subject: gelato - nvidia and python In-Reply-To: <65fcd6a4-131e-4d7c-96b3-402296bf2a18@y21g2000hsf.googlegroups.com> References: <65fcd6a4-131e-4d7c-96b3-402296bf2a18@y21g2000hsf.googlegroups.com> Message-ID: On Sun, Jun 29, 2008 at 11:34 AM, catalinfest at gmail.com < catalinfest at gmail.com> wrote: > Did somebody worked with gelato from nvidia and python? > I have some C cod from books nvidia . > This is : > " > GelatoAPI *r = GelatoAPI::CreateRenderer(); > r->Camera ("main"); > ... API calls through r ... > r->Render ("main"); > delete r; // Finished with this renderer > " > the code for python i create is only this : > " > python > Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) > [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import gelato > >>> from gelato import * > >>> r=gelato.CreateRenderer > >>> print r > > >>> dir(r) > ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', > '__getattribute__', '__hash__', '__init__', '__module__', '__name__', > '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', > '__setattr__', '__str__'] > " > And I blocked here... > Thank you . > -- You are looking at the function CreateRenderer, not the Renderer object. Try doing this: >>> import gelato >>> r = gelato.CreateRenderer*()* >>> dir(r) > > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eckhardt at satorlaser.com Tue Jun 24 12:01:42 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 24 Jun 2008 18:01:42 +0200 Subject: percent string replacement with index Message-ID: <7ci7j5-uu7.ln1@satorlaser.homedns.org> Hi! I'm still mostly learning Python and there is one thing that puzzles me about string formatting. Typical string formatting has these syntaxes: "%s is %s" % ("GNU", "not Unix") "%(1)s %(2)s" % ("1":"one", "2":"two") What I'm surprised is that this isn't supported: "%(1)s %(2)s" % ("zero", "one", "two") i.e. specifying the index in a sequence instead of the key into a map (maybe I would use [1] instead of (1) though). Further, the key can't be a simple number it seems, which makes this even more inconvenient to me. Can anyone explain this to me? Also, why isn't the 's' conversion (i.e. to a string) the default? I personally would like to just write something like this: "%1 is not %2" % ("zero", "one", "two") or maybe "%[1] is not %[2]" % ("zero", "one", "two") greetings! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From ethan at stoneleaf.us Wed Jun 11 10:39:43 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 11 Jun 2008 06:39:43 -0800 Subject: Alternative to Decimal type In-Reply-To: References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: <484FE3AF.5020504@stoneleaf.us> Frank Millman wrote: > Thanks to all for the various replies. They have all helped me to > refine my ideas on the subject. These are my latest thoughts. > > Firstly, the Decimal type exists, it clearly works well, it is written > by people much cleverer than me, so I would need a good reason not to > use it. Speed could be a good reason, provided I am sure that any > alternative is 100% accurate for my purposes. [snip] > For addition, subtraction, multiplication and division, the 'other' > number can be any of 2, 3, or 4 above. The result is a new Number > instance. The scale of the new instance is based on the following rule > > For addition and subtraction . . . > For multiplication . . . > For division . . . Out of curiosity, what is the purpose of these numbers? Do they represent money, measurements, or something else? The reason I ask is way back in physics class (or maybe chemistry... it was way back :) I was introduced to the idea of significant digits -- that idea being that a measured number is only accurate to a certain degree, and calculations using that number therefore could not be more accurate. Sort of like a built-in error range. I'm thinking of developing the class in the direction of maintaining the significant digits through calculations... mostly as I think it would be fun, and it also seems like a good test case to get me in the habit of unit testing. I'll call it something besides Number, though. :) Is anybody aware of such a class already in existence? -- Ethan From david at boddie.org.uk Fri Jun 20 18:21:39 2008 From: david at boddie.org.uk (David Boddie) Date: Sat, 21 Jun 2008 00:21:39 +0200 Subject: py2exe, PyQT, QtWebKit and jpeg problem References: Message-ID: On Friday 20 June 2008 17:24, Phil Thompson wrote: > On Fri, 20 Jun 2008 08:04:57 -0700 (PDT), Carbonimax > wrote: >> I have a problem with py2exe and QtWebKit : >> I make a program with a QtWebKit view. >> If I launch the .py directly, all images (jpg, png) are displayed but >> if I compile it with py2exe I have only png images. No jpg ! >> No error message, nothing. >> >> Have you a solution ? Thank you. > > At a guess, the JPEG support is implemented as a Qt plugin which you are > not including. Yes, that would appear to the be most obvious cause. See here for another report about this: http://lists.trolltech.com/qt4-preview-feedback/2008-03/msg00064.html David From goldnery at gmail.com Tue Jun 17 12:43:01 2008 From: goldnery at gmail.com (Gandalf) Date: Tue, 17 Jun 2008 09:43:01 -0700 (PDT) Subject: text alignment Message-ID: <39d1c620-9923-46e7-999d-ed86c8b465ff@34g2000hsh.googlegroups.com> Hi every one. What is the similar python WX style property for CSS text-align? I need this item text to start from the right direction: aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60)) aaa.LoadPage('../../aa.html') Thanks! From gabriel.rossetti at arimaz.com Wed Jun 11 03:21:03 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Wed, 11 Jun 2008 09:21:03 +0200 Subject: h2py.py bug? In-Reply-To: References: <484E771D.1050404@arimaz.com> Message-ID: <484F7CDE.9000300@arimaz.com> Gabriel Genellina wrote: > En Tue, 10 Jun 2008 09:44:13 -0300, Gabriel Rossetti > escribi?: > >> I wanted to use the h2py.py script (Tools/scripts/h2py.py) and it >> didn't like char litterals : >> >> Skipping: PC_ERROR = ord() >> >> where my *.h file contained : >> >> #define PC_ERROR '0' >> >> I searched the web and found a post with the same error : >> >> http://mail.python.org/pipermail/python-list/2005-September/340608.html >> >> but it got no replies, I tried the fix and it works. I have the >> following questions: >> >> 1) Why did it not get any attention, is something wrong with it? >> 2) If nothing is wrong, did the fix not get applied because a bug >> report wasn't filed? > > Very probably - bug reports outside the tracker are likely to go > unnoticed or forgotten. > Ok, I'll file one then. >> 3) Isn't turning a char literal into the ordinal value not contrary >> to what a C programmer had in mind when he/she defined it? I mean if >> you define a char literal then in python you would have used a string >> value : >> >> #define PC_ERROR '0' >> >> would become : >> >> PC_ERROR = '0' >> >> in python, and if you intended to use the char type for an 8 bit >> numerical value you would have done : >> >> #define PC_ERROR 0x30 >> >> where 0x30 is the '0' ascii hex value, so shouldn'it the line in the >> diff (see the post) be : >> >> body = p_char.sub("'\\1'", body) >> >> instead of : >> >> body = p_char.sub("ord('\\1')", body) > > It's not so clear what's the intended usage - chars are also integers > in C. (I prefer the current behavior, but certainly it may be wrong in > several places). > Yes, true, but if you intend to use it as an integer, wouldn't you use a numeric value instead of a character literal? From asmodai at in-nomine.org Thu Jun 19 10:39:42 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 19 Jun 2008 16:39:42 +0200 Subject: Extending Python with C: Cannot find MPI library In-Reply-To: <9100a146-a0bb-4958-a7c6-f23c9b518e89@a1g2000hsb.googlegroups.com> References: <9100a146-a0bb-4958-a7c6-f23c9b518e89@a1g2000hsb.googlegroups.com> Message-ID: <20080619143942.GL97799@nexus.in-nomine.org> -On [20080619 16:21], Spectrum (spectrumdt at gmail.com) wrote: > libmpi.so.0 => /usr/lib/openmpi/1.2.4-gcc/libmpi.so.0 >(0x0042f000) > libopen-rte.so.0 => /usr/lib/openmpi/1.2.4-gcc/libopen- >rte.so.0 (0x003d4000) > libopen-pal.so.0 => /usr/lib/openmpi/1.2.4-gcc/libopen- >pal.so.0 (0x00344000) These libraries are what your binaries (.so and such) needs to link against as well. I am not sure if you have to add a flag (-mpi) to your compiler or if you need to add a -L/usr/lib/openmpi/1.2.4-gcc -lmpi -lopen-rte -lopen-pal to the incantations. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B The distance to here is infinite... From eliben at gmail.com Fri Jun 20 15:37:09 2008 From: eliben at gmail.com (eliben) Date: Fri, 20 Jun 2008 12:37:09 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> Message-ID: <8d9283f0-2618-408b-9b75-bf6841dea44e@k37g2000hsf.googlegroups.com> > FWIW, when I had a similar challenge for dynamic coding, I just > generated a py file and then imported it. This technique was nice > because can also work with Pyrex or Psyco. > I guess this is not much different than using exec, at the conceptual level. exec is perhaps more suitable when you really need just one function at a time and not a whole file of related functions. > Also, the code above can be simplified to: get_counter = lambda > packet: packet[5:1:-1] > OK, but that was just a demonstration. The actual functions are complex enough to not fit into a single expression. Eli From johnjsal at NOSPAMgmail.com Mon Jun 16 09:14:38 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 16 Jun 2008 09:14:38 -0400 Subject: newbie question: for loop within for loop confusion References: Message-ID: <02a1b83d$0$25034$c3e8da3@news.astraweb.com> "takayuki" wrote in message news:ba3ce6db-6d2b-4de4-b1d2-00b95fefa8a8 at g16g2000pri.googlegroups.com... > John: There were two "inchworms" because "c" is in "inchworm" so it > shouldn't print. Thanks for your detailed description of the for > loop. lol, I even sat there looking at the word and said to myself "ok, it doesn't contain any of the four letters" :) From marc.wyburn at googlemail.com Fri Jun 13 05:41:30 2008 From: marc.wyburn at googlemail.com (marc wyburn) Date: Fri, 13 Jun 2008 02:41:30 -0700 (PDT) Subject: boolian logic References: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> Message-ID: On 13 Jun, 10:34, Aidan wrote: > marc wyburn wrote: > > HI all, I'm a bit stuck with how to work outboolianlogic. > > > I'd like to say if A is not equal to B, C or D: > > ? ?do something. > > > I've tried > > > if not var == A or B or C: > > and various permutations but can't seem to get my head around it. ?I'm > > pretty sure I need to know what is calulated first i.e the not or the > > 'OR/AND's > > > thanks, Marc. > > You mean like a ternary operation? > > ?>>> True and 1 or 0 > 1 > ?>>> False and 1 or 0 > 0 > > This of course depends on the 'true' result also being true.. it fails > if it is false... > > if that's not what you mean, then maybe this is what you want > > if not var==A or not var==B or not var==C: > ? ? ?# do something the not var==A or not var==B or not var==C was what I was after. I was being too literal with my script and trying not (A or B or C) which doesn't work. Thanks for the help. From grante at visi.com Tue Jun 10 22:43:54 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 10 Jun 2008 21:43:54 -0500 Subject: problems with opening files due to file's path References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> Message-ID: <_7ydnVc3Q5Z3ptLVnZ2dnUVZ_jqdnZ2d@posted.visi> On 2008-06-11, Alexnb wrote: >>>> path = "C:\Documents and Settings\Alex\My Documents\My >>>> Music\Rhapsody\Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm >>>> Yours.wma" Your string doesn't contain what you think it does. Do a "print path". Hint: the string "\01" consists of a single byte who's value is 001 base 8. >>>> os.startfile(path) > Traceback (most recent call last): > File "", line 1, in > os.startfile(path) > WindowsError: [Error 2] The system cannot find the file specified: > "C:\\Documents and Settings\\Alex\\My Documents\\My > Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\x01 - I'm > Yours.wma" Notice that the string in the error message contains \x01? That's the byte that got changed. > Here's another way: > >>>> os.startfile(r"%s"%path) > Traceback (most recent call last): > File "", line 1, in > os.startfile(r"%s"%path) > WindowsError: [Error 2] The system cannot find the file specified: > "C:\\Documents and Settings\\Alex\\My Documents\\My > Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\x01 - I'm > Yours.wma" > > Same output, however if I personally input it like so: > >>>> os.startfile("C:\\Documents and Settings\\Alex\\My Documents\\My >>>> Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\\01 - I'm >>>> Yours.wma") > > It works out fine because I can make each backslash doubles so it doesn't > mess stuff up. Right. > So if I could take the path varible and make ever "\" into a > "\\" then it would also work. I don't understand the part about the path variable. The backslash character is used in both C and Python as an escape character so that you can encode special values in string literals. For example: '\r' is a carriage return '\n' is a linefeed, \0nnn is a single byte with the octal value nnn, and so on. Microsoft's choice of '\' as a path separator was a terribly bad one (one of many made by Microsoft over the years). Most Windows system calls will accept forward slashes, so the easiest thing to do is usually just type the strings with forward slashes. -- Grant Edwards grante Yow! NOW do I get to blow at out the CANLDES?? visi.com From ananth99899 at gmail.com Sat Jun 21 01:40:51 2008 From: ananth99899 at gmail.com (www.hollywoodpopstars.blogspot.com) Date: Fri, 20 Jun 2008 22:40:51 -0700 (PDT) Subject: Kerala Couples Enjoying SEX At NET CAFE CENTER Message-ID: <59924f7f-2981-4551-8aab-cce4737ef135@i36g2000prf.googlegroups.com> Hi....Friends, watch and enjoy SECRET WEB-CAMS at LADIES HOSTELS and INTERNET CAFE SEX SCANDALS VIDEOS... http://www.hollywoodpopstars.blogspot.com http://www.googlemobilesphones.blogspot.com From nagle at animats.com Sun Jun 8 00:33:02 2008 From: nagle at animats.com (John Nagle) Date: Sat, 07 Jun 2008 21:33:02 -0700 Subject: multiprocessing module (PEP 371) In-Reply-To: <1c867dff-a909-4b9e-99ec-b096ddfbd83d@c58g2000hsc.googlegroups.com> References: <877a5774-d3cc-49d3-bb64-5cab8505a419@m3g2000hsc.googlegroups.com> <1c867dff-a909-4b9e-99ec-b096ddfbd83d@c58g2000hsc.googlegroups.com> Message-ID: <484b5d74$0$17208$742ec2ed@news.sonic.net> sturlamolden wrote: > On Jun 5, 11:02 am, pataphor wrote: > >> This is probably not very central to the main intention of your post, >> but I see a terminology problem coming up here. It is possible for >> python objects to share a reference to some other object. This has >> nothing to do with threads or processes, although it can be used as a >> *mechanism* for threads and processes to share data. > > It is complicated in the case of processes, because the object must be > kept in shared memory. The complicating factor is that the base > address of the memory mapping, which is not guaranteed to be the same > in the virtual address space of different processes. Introducing shared memory in Python would be a terrible idea, for many reasons, including the need for interprocess garbage collection and locking. Don't go there. Use message passing instead. John Nagle From exarkun at divmod.com Mon Jun 16 06:59:34 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 16 Jun 2008 06:59:34 -0400 Subject: Python GC does not work as it should be In-Reply-To: Message-ID: <20080616105934.4714.1605358387.divmod.quotient.9670@ohm> On Mon, 16 Jun 2008 17:51:00 +0700, Jaimy Azle wrote: >See this piece of code: > >/* API to invoke gc.collect() from C */ >Py_ssize_t >PyGC_Collect(void) >{ > Py_ssize_t n; > > if (collecting) > n = 0; /* already collecting, don't do anything */ > else { > collecting = 1; > n = collect(NUM_GENERATIONS - 1); > collecting = 0; > } > return n; >} > >If a system exception raised when executing collect(xxx), collecting state >variable would never be reset and python GC will not works forever until the >application restarted. A system exception? What's that? C doesn't have exceptions. Jean-Paul From dullrich at sprynet.com Thu Jun 12 13:39:29 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 12 Jun 2008 12:39:29 -0500 Subject: Making wxPython a standard module? References: Message-ID: In article , "Andrea Gavana" wrote: > Hi Diez & All, > > > And on a personal note: I find it *buttugly*. > > Do you mind explaining "why" you find it *buttugly*? My guess would be that "buttugly" is a colloquialism meaning "exquisitely lovely". >I am asking just > out of curiosity, obviously. I am so biased towards wxPython that I > won't make any comment on this thread in particular, but I am curious > to know why some people find it "ugly" or "bad" or whatever. It has > its own bugs and missing features, of course, but it is one of the > major GUI player in the arena, together with PyQt and PyGTK. > > Andrea. > > "Imagination Is The Only Weapon In The War Against Reality." > http://xoomer.alice.it/infinity77/ -- David C. Ullrich From aspersieman at gmail.com Fri Jun 20 03:42:23 2008 From: aspersieman at gmail.com (Aspersieman) Date: Fri, 20 Jun 2008 09:42:23 +0200 Subject: don't make it worse! - was Re: SPAM In-Reply-To: <485AE162.8050407@gmail.com> References: <88f0c3ba-46e1-4b30-a61d-482e5ecf339a@t12g2000prg.googlegroups.com> <485A0E77.2050009@gmail.com> <485AE162.8050407@gmail.com> Message-ID: <485B5F5F.8070207@gmail.com> An HTML attachment was scrubbed... URL: From s0suk3 at gmail.com Tue Jun 24 19:06:43 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Tue, 24 Jun 2008 16:06:43 -0700 (PDT) Subject: shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": References: <09b41308-0167-4231-b5e7-5baa1a9aff9d@u6g2000prc.googlegroups.com> Message-ID: <3b12d826-4a10-4ed3-b66e-f28f64910f05@m3g2000hsc.googlegroups.com> On Jun 24, 5:36 pm, John Machin wrote: > On Jun 25, 4:32 am, cirfu wrote: > > > if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": > > > cant i write something like: > > if char in "[A-Za-z]": > > You can write that if you want to, but it's equivalent to > if char in "zaZa]-[": > i.e. it doesn't do what you want. > > This gives the same reuslt as your original code, unaffected by > locale: > > if "A" <= char <= "Z" or "a" <= char <= "z": But doesn't that rely on the underlying character set? It's like performing math on C char's (maybe that's what the interpreter does internally?). If that's the case, using 'char.isalpha()' or 'char in string.letters' or regex's would be better. From dgetsman at amirehab.net Fri Jun 27 12:36:04 2008 From: dgetsman at amirehab.net (Damon Getsman) Date: Fri, 27 Jun 2008 09:36:04 -0700 (PDT) Subject: what is meaning of "@" in pyhon program. References: <88990b3d-1916-413f-83b9-796aabf43623@l28g2000prd.googlegroups.com> <19aa4978-242b-4732-b072-aa5ff16975b0@27g2000hsf.googlegroups.com> <486502bf$0$6426$426a74cc@news.free.fr> <4bfb891d-7a7b-45bc-b126-1d485c9206ee@m44g2000hsc.googlegroups.com> <48650adb$0$7975$426a74cc@news.free.fr> Message-ID: I didn't think that it was. I just spent about 10 minutes trying to google for the page that I found that on, but I wasn't able to turn it up. My google-fu sucks. I know that I was researching a particular part of the os module and that the snippets of script on the page had an example containing '@if' and '@for'. I don't remember what exactly I used to turn it up before, though, and the link isn't in my history, it was probably a month ago that I saw it. Sorry, I tried. On Jun 27, 10:44?am, Bruno Desthuilliers wrote: > Damon Getsman a ?crit : > > ie: > > @if os.exists(foo): > > ? ?etc > > ? ?etc > > > and > > > @for blah: > > ? ?etc > > ? ?etc > > This is not valid Python. period. From http Wed Jun 4 07:24:19 2008 From: http (Paul Rubin) Date: 04 Jun 2008 04:24:19 -0700 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> Message-ID: <7xk5h5tpcs.fsf@ruckus.brouhaha.com> NickC writes: > if/else was added solely because people kept coming up with ways of > embedding a pseudo conditional inside expressions and writing buggy > code in the process. All it really saves you in practice is a bit of > vertical whitespace, so, no, you still don't need it - but if you > insist on doing it, at least there's now an easy way to do it > correctly. Come on, it's more than vertical whitespace, it's extraneous variables and sometimes even extraneous functions and function call overhead. And Python is supposed to be unbureaucratic. People kept looking for ways to write conditional expressions instead of spewing the logic across multiple statements for a reason: the code is often cleaner that way. From bruno.42.desthuilliers at websiteburo.invalid Tue Jun 10 05:12:15 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 10 Jun 2008 11:12:15 +0200 Subject: Question by someone coming from C... In-Reply-To: References: Message-ID: <484e451b$0$10973$426a74cc@news.free.fr> Skye a ?crit : > Writing this app in Python, not sure what the "best practice" would > be. > > I want a bitfield global logging level that allows me to turn specific > debugging modules on and off. If I was doing this in C, I'd just use > some globals like: > > unsigned int debug_level = 0; > #define DEBUG_GENERAL 0x0001 > #define DEBUG_CONFIG 0x0002 > #define DEBUG_OPTIONS 0x0004 > etc etc > > So I guess my questions are: > > 1. there doesn't seem to be a way to define global constants like in > other languages? > 2. any special voodoo to use bitfields in Python? Others already gave you the best advises (namely: using the logging module). But let's answer your questions anyway: 1/ by convention, anything named ALL_UPPER is considered a constant. Anyone breaking your code by messing with a PSEUDO_CONSTANT is on it's own and has no right to complain. Consider it as a "warranty void if unsealed" warning. 2/ just use plain integers and bitwise operators. But we're usually more concerned about readability than about saving bits, and I've rarely (maybe twice ?) seen bitfields used that way in Python. From george.sakkis at gmail.com Fri Jun 13 19:02:26 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 13 Jun 2008 16:02:26 -0700 (PDT) Subject: importing part of a module without executing the rest References: Message-ID: On Jun 13, 5:52 pm, krishna.00... at gmail.com wrote: > file1.py > ---------- > a = 20 > from abc import * > print "Should this be printed when 'a' is alone imported from this > module" > > file2.py > ---------- > from file1 import a > print a > > (snipped) > > Of course, the option of using if __name__ == '__main__' in file1.py > for statements following 'a = 20' is not useful in my case as I need > all statements in file1 to be exectued when imported by someone else > (say file3.py) That's a bad code smell. In general, modules intended to be imported should not have any side effects at global scope before the "if __name__ == '__main__':" part. Put the "print ..." and all other statements with side effects in one or more functions and let the importing module call them explicitly if necessary. George From niklas.norrthon at hotmail.com Wed Jun 11 02:07:16 2008 From: niklas.norrthon at hotmail.com (Niklas Norrthon) Date: Tue, 10 Jun 2008 23:07:16 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> <4847d203$0$32733$426a74cc@news.free.fr> <87lk1jzgri.fsf@mulj.homelinux.net> <39a7805f-6590-4505-bfa2-0735090d553b@t12g2000prg.googlegroups.com> Message-ID: On 6 Juni, 03:09, "Russ P." wrote: > On Jun 5, 2:57 pm, Hrvoje Niksic wrote: > > > "Russ P." writes: > > > By the way, my recollection is that in C++ access defaults to private > > > if nothing is declared explicity. So normally the "private" > > > declaration is unnecessary. If it is left out, your little trick won't > > > work. > > > How about #define class struct > > I never thought of that one. I wonder what the C++ gurus would say > about that. > > Let me guess. They'd probably say that the access restrictions are for > your own good, and bypassing them is bound to do you more harm than > good in the long run. And they'd probably be right. Just because you > can break into a box labeled "DANGER HIGH VOLTAGE," that doesn't make > it a good idea. > > This just goes to show that the whole idea of using header files as > simple text insertions is flaky to start with, and adding the > preprocessor just compounds the flakiness. Needless to say, I'mnota > big fan of C and C++. From i.i at i.i Thu Jun 26 12:21:39 2008 From: i.i at i.i (Josip) Date: Thu, 26 Jun 2008 18:21:39 +0200 Subject: Storing value with limits in object References: <6tednUvC9-jDxMPVnZ2dnUVZ_hGdnZ2d@comcast.com> Message-ID: Thanks alot. I'm going to use this with few modifications to tailor it to my needs. Thumbs up! > #!/usr/bin/env python > > ## VERSION 2 > ## > ## changelog: > ## - Uses inheritance from _Limited > ## - Added _LimitedLong and llong > ## - limit choose between int, long, and float > > class _Limited(object): > def setlimits(self, lim): > ''' Set the limits and if value is not within limit, > raise ValueError > > The lim argument accepts: > - An instance of _Limited, from which to copy the limits > - A two-tuple, which specifies the limits i.e. (min, max) > > If lim isn't those or lim[0] > lim[1], raise > InvalidLimitsError > > Accepting _Limited instance is just for convenience > ''' > > if isinstance(lim, _Limited): > self.min, self.max = lim.limits > else: > try: > self.min, self.max = lim > if self.min > self.max: raise ValueError > except (ValueError, TypeError): > raise self.InvalidLimitsError, ('limit = %s' % > str(lim)) > > if not (self.min < self < self.max): > raise ValueError, \ > ('val = %s, min = %s, max = %s' % \ > (self, self.min, self.max)) > > def getlimits(self): > return (self.min, self.max) > > limits = property(getlimits, setlimits) > > class _LimitedInt(int, _Limited): > def __init__(self, value, base = 10): > int.__init__(value, base) > > class _LimitedLong(long, _Limited): > def __init__(self, value, base = 10): > long.__init__(value, base) > > class _LimitedFloat(float, _Limited): > def __init__(self, value): > float.__init__(value) > > > def lint(value, limits, base = None): > ''' Always Creates _LimitedInt instance, allows the use of base > ''' > if base: > ret = _LimitedInt(value, base) > else: > ret = _LimitedInt(value) > > ret.limits = limits > return ret > > def llong(value, limits, base = None): > ''' Always Creates _LimitedLong instance, allows the use of base > ''' > if base: > ret = _LimitedLong(value, base) > else: > ret = _LimitedLong(value) > > ret.limits = limits > return ret > > def lfloat(value, limits): > ''' Always Creates _LimitedFloat instance > ''' > ret = _LimitedFloat(value) > > ret.limits = limits > return ret > > def limit(value, limits): > ''' Automatically choose between _LimitedInt, _LimitedLong, > or _LimitedFloat. Cannot use _LimitedInt's/Long's base > ''' > if isinstance(value, (int, long)): > try: > ret = _LimitedInt(value) > except OverflowError: > ret = _LimitedLong(value) > elif isinstance(value, float): > ret = _LimitedFloat(value) > > ret.limits = limits > return ret From geonomica at gmail.com Fri Jun 6 13:04:18 2008 From: geonomica at gmail.com (gianluca) Date: Fri, 6 Jun 2008 10:04:18 -0700 (PDT) Subject: ctypes help Message-ID: hy, I've a huge problem with ctypes. I've compiled my C library and I'd like use it in python with ctype. One function need to pass a pointer to typed ( like this: typedef int value_type). In python I can access to that funtion but arise an exception because python don't know my value_type typedef. Please I need help, could anybody help me? Gianluca From thor__00 at yahoo.com Wed Jun 11 07:23:05 2008 From: thor__00 at yahoo.com (Thor) Date: Wed, 11 Jun 2008 13:23:05 +0200 Subject: Parallel python + ?? Message-ID: Hi, I am running a program using Parallel Python and I wonder if there is a way/module to know in which CPU/core the process is running in. Is that possible? ?ngel From socyl at 987jk.com.invalid Fri Jun 20 08:37:25 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 20 Jun 2008 12:37:25 +0000 (UTC) Subject: ISO dict => xml converter Message-ID: Hi. Does anyone know of a module that will take a suitable Python dictionary and return the corresponding XML structure? In Perl I use XML::Simple's handy XMLout function: use XML::Simple 'XMLout'; my %h = ( 'Foo' => +{ 'Bar' => +{ 'Baz' => [ { 'meenie' => 3 }, { 'meenie' => 7 } ], 'eenie' => 4, }, 'minie' => 1, 'moe' => 2, } ); print XMLout( \%h, KeepRoot => 1, KeyAttr => undef ); __END__ Is there a Python module that can do a similar conversion from a Python dict to an XML string? (FWIW, I'm familiar with xml.marshal.generic.dumps, but it does not produce an output anywhere similar to the one illustrated above.) TIA! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From bob at mellowood.ca Thu Jun 12 15:06:15 2008 From: bob at mellowood.ca (bvdp) Date: Thu, 12 Jun 2008 12:06:15 -0700 Subject: howto split string with both comma and semicolon delimiters References: <3e2540ab-1d2a-45a5-a5b6-3f7ae7a4efac@x35g2000hsb.googlegroups.com> Message-ID: dmitrey wrote: > hi all, > howto split string with both comma and semicolon delimiters? > > i.e. (for example) get ['a','b','c'] from string "a,b;c" > > I have tried s.split(',;') but it don't work > Thx, D. Howabout: s = s.replace(";", ",") s = s.split(",") From lew at lewscanon.com Mon Jun 30 07:51:21 2008 From: lew at lewscanon.com (Lew) Date: Mon, 30 Jun 2008 07:51:21 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: Message-ID: Robert Maas wrote: > /----------------------------------------------------------------------------\ > | ,-.-. | | > | | | |, . ,---.,---.,---. ,---.,---.,---.,---|,---. | > | | | || | `---.| || | | ||---'|---'| |`---. | > | ` ' '`---| `---'`---'` ' ` '`---'`---'`---'`---' | > | `---' | > | | | o | | | > | |---.,---.| ,---. .,---. ,---.| ,---.,---. |---.,---.,---. | > | | ||---'| | | || | ,---|| | ||---'---| || ,---| | > | ` '`---'`---'|---' `` ' `---^`---'`---|`---' `---'` `---^ | | > | | `---' ' | > | | | | | > | ,---.,---.|--- . . .,---.,---.,---|,---.,---. |---.,---.,---. | > | | || || | | || || || ||---'| ---| || ,---| | > | ` '`---'`---' `-'-'`---'` '`---'`---'` `---'` `---^o | > \--------(Rendered by means of )--------/ > (You don't need JavaScript or images to see that ASCII-text image!! > You just need to view this in a fixed-pitch font such as Monaco.) > > Then enter your best guess of the text (40-50 chars) into this TextField: > +--------------------------------------------------+ > | Your son totally needs a Wonder-Bra(r), double-D | > +--------------------------------------------------+ -- Lew From celoserpa at gmail.com Wed Jun 11 02:22:05 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Wed, 11 Jun 2008 03:22:05 -0300 Subject: Using ElementTree as backend for a chat web application issues In-Reply-To: References: <1e5bcefd0806091132p78f42109t1edb5e5acfaadb43@mail.gmail.com> Message-ID: <1e5bcefd0806102322k3e069cfanba6ba9ee01332e54@mail.gmail.com> Well folks, I appreciate your help, but I've got the problem solved by re-implementing the chat backend (server) in Rails. It is working great now (persisting the data in a mysql database, instead of XML files). At least this has led me to search more about concurrent issues and programming. I'm still confused on why this doesn't happen with my Rails backend, but I will eventually find out. Living and learning. Thanks for the attention, Marcelo. On Wed, Jun 11, 2008 at 12:47 AM, Gabriel Genellina wrote: > En Mon, 09 Jun 2008 15:32:00 -0300, Marcelo de Moraes Serpa < > celoserpa at gmail.com> escribi?: > > I've built a chat with a front-end Ajax client and backend usign >> ElementTree >> to persist the data. >> >> In some circunstances I could not yet discover (it seems random) when I >> edit/save the structure, the structure gets corrupted, elementree seems to >> get lost in its internal "cursor", usually something like this happens: >> >> >> >> >> >> >> id="3"/> >> >> Pretty strange, and it drives the whole application unusable. >> >> I don't know if the concurrent nature of the application (multiple users >> using the client at almost the same time and sending data to the server >> which in turn must save the data to the same global.xml file) has >> something >> to do with it - I don't know if ElementTree is suitable for this kind of >> thing. How to hanlde this concurrent issue? >> > > I don't think it's a problem with ElementTree. Perhaps you are writing the > same (global) configuration file from several threads at the same time? You > may need some locking mechanism in that case. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Thu Jun 26 20:44:44 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 26 Jun 2008 17:44:44 -0700 (PDT) Subject: list previous or following list elements References: Message-ID: <0d455050-45f1-4f39-b237-db06a4d43212@x35g2000hsb.googlegroups.com> Terry Reedy: > I believe > wordlist = open('words.txt','r').read().split('\n') > should give you the list in Python. This looks better (but it keeps the newlines too. Untested. Python 2.x): words = open("words.txt").readlines() for i, word in enumerate(words): if word.startswith("b"): print words[i+1] break Another possibility (untested, lazy, uses less memory, probably better): fin = open("words.txt") last_word = fin.next() for word in fin: if last_word.startswith("b"): print word break else: last_word = word fin.close() A note for the original poster: I suggest you to try to learn string methods (not the string module), they are designed to avoid you to use regular expressions most of the times, and they are faster and more readable too. I have seen that people that learn Python coming from Perl are often 'blind' to their existence. Bye, bearophile From __peter__ at web.de Wed Jun 18 08:08:10 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 18 Jun 2008 14:08:10 +0200 Subject: dict order References: Message-ID: Robert Bossy wrote: > I wish to know how two dict objects are compared. By browsing the > archives I gathered that the number of items are first compared, but if > the two dict objects have the same number of items, then the comparison > algorithm was not mentioned. If I interpret the comments in http://svn.python.org/view/python/trunk/Objects/dictobject.c?rev=64048&view=markup correctly it's roughly def characterize(d, e): return min(((k, v) for k, v in d.iteritems() if k not in e or e[k] != v), key=lambda (k, v): k) def dict_compare(d, e): result = cmp(len(d), len(e)) if result: return result try: ka, va = characterize(d, e) except ValueError: return 0 kb, vb = characterize(e, d) return cmp(ka, kb) or cmp(va, vb) Peter From fuzzyman at gmail.com Mon Jun 23 15:39:23 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 23 Jun 2008 12:39:23 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <79a1c500-1844-4405-8f52-21e845a85f9b@z66g2000hsc.googlegroups.com> Message-ID: <2e56b463-ccde-45ca-8c8f-de8debf9c3ad@2g2000hsn.googlegroups.com> On Jun 21, 7:52?am, Peter Otten <__pete... at web.de> wrote: > eliben wrote: > > On Jun 20, 2:44 pm, Peter Otten <__pete... at web.de> wrote: > >> eliben wrote: > >> > Additionally, I've found indentation to be a problem in such > >> > constructs. Is there a workable way to indent the code at the level of > >> > build_func, and not on column 0 ? > > >> exec"if 1:" + code.rstrip() > > >> Peter > > > Why is the 'if' needed here ? I had .strip work for me: > > A simple .strip() doesn't work if the code comprises multiple lines: > > >>> def f(): > > ... ? ? return """ > ... ? ? x = 42 > ... ? ? if x > 0: > ... ? ? ? ? ? ? print x > ... ? ? """ > ...>>> exec "if 1:\n" + f().rstrip() > 42 > >>> exec f().strip() > > Traceback (most recent call last): > ? File "", line 1, in > ? File "", line 2 > ? ? if x > 0: > ? ? ^ > IndentationError: unexpected indent > > You can of course split the code into lines, calculate the indentation of > the first non-white line, remove that indentation from all lines and then > rejoin. > textwrap.dedent will do all that for you... Michael Foord http://www.ironpythoninaction.com/ > Peter From brian_vanderburg2 at yahoo.com Thu Jun 26 11:18:08 2008 From: brian_vanderburg2 at yahoo.com (Allen) Date: Thu, 26 Jun 2008 11:18:08 -0400 Subject: Adding functions to an existing instance Message-ID: <27adnS2SrIrOLv7VnZ2dnUVZ_rjinZ2d@earthlink.com> I need a way to add a method to an existing instance, but be as close as possible to normal instance methods. Using 'new' module or such code as 'def addfunc(...): def helper(...) .. setattr(...)' causes a cyclic reference which requires using 'gc.collect' to release the object. Also 'new' is deprecated. I also made a helper that uses weakref, but the problem is when the object is gone, existing instance method object would not work: f = myobject.function myobject = None f() <--- would not work if it holds weak ref to myobject The best I can come up with is to create a parent class and try to simulate as best as possible. The code below works with no cyclic references that would be cause by 'new.instancemethod' etc, and without the weakref as well. Is there a simpler way of achieving the same without cyclic references? I know this is 'monkey patching' but for a small project I'm working on it is useful to be able to add functions dynamically to one instance without adding it to another instance of the same class, etc. class InstanceFunctionHelper(object): class FunctionCaller(object): def __init__(self, instance, func): self.__instance = instance self.__func = func def __call__(self, *args, **kwargs): return self.__func(self.__instance, *args, **kwargs) def add_instance_function(self, func, name = None): if name is None: name = func.__name__ if hasattr(self, name): delattr(self, name) try: self._instance_funcs[name] = func except AttributeError: self._instance_funcs = {name: func} def __setattr__(self, name, value): funcs = getattr(self, '_instance_funcs', None) if funcs and name in funcs: del funcs[name] object.__setattr__(self, name, value) def __delattr__(self, name): funcs = getattr(self, '_instance_funcs', None) if funcs and name in funcs: del funcs[name] else: object.__delattr__(self, name) def __getattr__(self, name): if name == '_instance_funcs': raise AttributeError funcs = object.__getattribute__(self, '_instance_funcs') if name in funcs: return InstanceFunctionHelper.FunctionCaller(self, funcs[name]) raise AttributeError x = 0 class Blah(InstanceFunctionHelper): def __init__(self): global x x += 1 def __del__(self): global x x -= 1 def Action(self, value): print self print value a = Blah() a.add_instance_function(Action) a.Action(5) a = None print x From ram.rachum at gmail.com Sun Jun 15 12:01:32 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Sun, 15 Jun 2008 09:01:32 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> Message-ID: On Jun 15, 6:58?pm, Christian Meesters wrote: > > I do need speed. Is there an option? > > Mind telling us what you *actually* want to achieve? (What do you want to > calculate?) > > Christian Physical simulations of objects with near-lightspeed velocity. From gabriel.rossetti at arimaz.com Sat Jun 28 14:03:31 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Sat, 28 Jun 2008 20:03:31 +0200 Subject: Do I need "self" and "other"? In-Reply-To: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> Message-ID: <48667CF3.1030402@arimaz.com> Kurda Yon wrote: > Hi, > > I found one example which defines the addition of two vectors as a > method of a class. It looks like that: > > class Vector: > def __add__(self, other): > data = [] > for j in range(len(self.data)): > data.append(self.data[j] + other.data[j]) > return Vector(data) > > In this example one uses "self" and "other". Does one really need to > use this words? And, if yes, why? I have replaced "self" by "x" and > "other" by "y" and everything looks OK. Is it really OK or I can have > some problem in some cases? > > Thank you! > -- > http://mail.python.org/mailman/listinfo/python-list > > > The first param "self" in an instance method is a convention, I would recommend not changing it. The "self" param is pass automatically when you call the method, like so : self.method(param) and this would have been defines as : def method(self, param): # do something here Self is like "this" in java, except it is explicitly added to the parameter list as the first parameter. You could name it whatever you want, but python programmers will throw tomatoes at you for naming it something else :-), since it mean "myself" in if the instance's perspective. Sometimes you have to pass it explicitly, like when calling your parent's method, be you'll see this when you study inheritance. I hope that helps, the "self" param had mixed me up some the first time I had seen it. Gabriel From rowland at river2sea.org Tue Jun 10 12:18:39 2008 From: rowland at river2sea.org (Rowland Smith) Date: Tue, 10 Jun 2008 12:18:39 -0400 Subject: chained exceptions Message-ID: Is anyone aware of a module or recipe for defining a composite/chained exception superclass? I've seen the PEP on chained exceptions wrt Python-3K, but I'm looking for something that is 2.5 compatible. -Rowland --------------------------- "The Dude abides." - The Dude, The Big Lebowski --------------------------- From exarkun at divmod.com Sat Jun 21 18:18:45 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 21 Jun 2008 18:18:45 -0400 Subject: Way to unblock sys.stdin.readline() call In-Reply-To: <37bbded6-af1c-4cd0-95fd-2b5536ec34cf@s50g2000hsb.googlegroups.com> Message-ID: <20080621221845.4714.468104778.divmod.quotient.11684@ohm> On Sat, 21 Jun 2008 12:35:02 -0700 (PDT), joamag wrote: >On Jun 21, 4:46 pm, C?dric Lucantis wrote: >> Le Saturday 21 June 2008 15:26:53 joamag, vous avez ?crit : >> >> > HI, >> >> > Is there any possible way to unblock the sys.stdin.readline() call >> > from a different thread. >> > Something like sys.stdin.write() but that would actually work ... >> > something to put characters in the stdin... >> >> Do you mean setting stdin in non-blocking mode ? On unix you can do it with >> the fcntl module (you'll find more infos in the libc docs) : >> >> fcntl.fcntl(sys.stdin, fcntl.F_SETFL, os.O_NONBLOCK) >> >> and catch IOErrors with errno = EAGAIN. But I don't know how to do it in a >> portable way, suggestions welcome :) >> >> -- >> C?dric Lucantis > >Thanks for the advice that's a way of solving my problem, but I really >need a portable way of doing it... > >The application I?m build is meant to be run in more platforms than >Unix ... so I really need a portable way of doing that or something >else that unblocks the read call in the stdin Twisted supports asynchronous handling of stdin on both POSIX and Windows. See stdiodemo.py and stdin.py under the Miscellaenous section at http://twistedmatrix.com/projects/core/documentation/examples/ Jean-Paul From tdahsu at gmail.com Fri Jun 13 12:16:19 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Fri, 13 Jun 2008 09:16:19 -0700 (PDT) Subject: Iterate creating variables? References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> <6bfhj5F3b47fmU1@mid.uni-berlin.de> <6bfj7bF3c3npoU1@mid.uni-berlin.de> <6bfk3fF3btpk3U1@mid.uni-berlin.de> Message-ID: <34d4366d-1aaa-4c65-99e7-cef8d6741dc1@e39g2000hsf.googlegroups.com> On Jun 13, 12:03?pm, "Diez B. Roggisch" wrote: > > Thank you, this is much closer to where I need to be... > > > The issue is (and this is the part that you don't know, because I > > didn't tell you!) is that I later need to call methods on > > "self.checkbox1", for instance: > > > self.checkbox1.GetValue() > > > to determine if the box is checked or not. > > > I should have included that piece in the initial problem description; > > my apologies. > > Then translate the above to > > self.checkboxes[1].GetValue() > > The point of all this is the following: If you have a variable (even if > not changing often, or being globally configured) number of objects, > it's a good idea to keep them around in a list. > > Even if you need specific parameters for the checkboxes, it would most > probably be better to do it like this > > checkbox_args = [ > ? ?("name", parameter, ...), > ? ?("other_name", other_parameter, ...), > ] > > for parameters in checkbox_args: > ? ? checkboxes.append(Checbbox(*parameters)) > > If you know on the other hand that you will have 10 checkboxes which > have all a defined meaning, it might be better to use a meaningful name > for them, like: > > self.create_backup = Checkbox(...) > self.perform_authorization = Checkbox(...) Trying self.checkboxes[1].GetValue(), gives me: 'NoneType' object has no attribute "GetValue" Thanks. From tdahsu at gmail.com Sat Jun 14 18:18:20 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Sat, 14 Jun 2008 15:18:20 -0700 (PDT) Subject: Avoiding redirects with urllib References: Message-ID: On Jun 14, 5:22?pm, Fernando Rodriguez wrote: > Hi, > > I'musing urllib to download pages from a site. How can I detect if a given > url is being redirected somewhere else? I want to avoid this, is it possible? > > Thanks in advance! Try this: import urllib url_opener = urllib.URLopener() # create URLopener #You could also work with urllib.FancyURLopener try: data = url_opener.open("http://www.somedomain.com/index.html") # open index.html except IOError, error_code: if error_code[0] == "http error": if error_code[1] == 301: #do something here if error_code[2] == 302: #do something here I hope that's of some help! I think you may want to delve deeper into FancyURLopener... From ethan at stoneleaf.us Tue Jun 10 10:06:11 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 10 Jun 2008 06:06:11 -0800 Subject: Alternative to Decimal type In-Reply-To: References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: <484E8A53.7010904@stoneleaf.us> Mel wrote: > Frank Millman wrote: > >> Hi all >> >> I have a standard requirement for a 'decimal' type, to instantiate and >> manipulate numeric data that is stored in a database. I came up with a >> solution long before the introduction of the Decimal type, which has >> been working well for me. I know the 'scale' (number of decimal >> places) of the number in advance. When I read the number in from the >> database I scale it up to an integer. When I write it back I scale it >> down again. All arithmetic is done using integers, so I do not lose >> accuracy. [snip] >> -------------------- >> from __future__ import division >> >> class Number(object): >> def __init__(self,value,scale): >> self.factor = 10.0**scale >> if isinstance(value,Number): >> value = value.value / value.factor > > I think this could lead to trouble. One complaint against binary floating > point is that it messes up low-order decimal digits, and this ensures that > all calculations are effectively done in binary floating point. Better, I > think would be > > if isinstance (value, Number): > self.value = value.value > self.scale = scale + value.scale > > and be done with it. Of course, this means self.scale no longer gives the > preferred number of fractional digits. My bias: I did a DecimalFloat class > way back when, when Decimal was being discussed, and separated the exponent > for calculations from the rounding precision for display. What about a little rewrite so the current implementation is like the original, and all calculations are done as integers? Or is this just getting closer and closer to what Decimal does? [only lightly tested] from __future__ import division class Number(object): def __init__(self, value, scale): if isinstance(value, Number): delta = value.scale - scale if delta > 0: self.value = value.value // 10**delta elif delta < 0: self.value = value.value * 10**abs(delta) else: self.value = value.value else: if not scale: scale += 1 self.scale = scale self.factor = 10**self.scale self.value = long(round(value * self.factor)) def __add__(self, other): answer = Number(other, self.scale) answer.value += self.value return answer def __sub__(self, rhs): answer = Number(rhs, self.scale) answer.value = self.value - answer.value return answer def __mul__(self, other): answer = Number(other, self.scale) answer.value *= self.value answer.value //= answer.factor return answer def __truediv__(self, rhs): answer = Number(rhs, self.scale) quotient = 0 divisor = answer.value dividend = self.value for i in range(self.scale+1): quotient = (quotient * 10) + (dividend // divisor) dividend = (dividend % divisor) * 10 answer.value = quotient return answer def __radd__(self, lhs): return self.__add__(lhs) def __rsub__(self, lhs): answer = Number(lhs, self.scale) answer.value = answer.value - self.value return answer def __rmul__(self, lhs): return self.__mul__(lhs) def __rtruediv__(self, lhs): answer = Number(lhs, self.scale) quotient = 0 divisor = self.value dividend = answer.value for i in range(self.scale+1): quotient = (quotient * 10) + (dividend // divisor) dividend = (dividend % divisor) * 10 answer.value = quotient return answer def __cmp__(self, rhs): other = Number(rhs, self.scale) if self.value < other.value: return -1 elif self.value > other.value: return 1 else: return 0 def __str__(self): s = str(self.value) if s[0] == '-': minus = '-' s = s[1:].zfill(self.scale+1) else: minus = '' s = s.zfill(self.scale+1) return '%s%s.%s' % (minus, s[:-self.scale], s[-self.scale:]) -- Ethan From three3q at arcor.de Sat Jun 28 08:11:45 2008 From: three3q at arcor.de (three3q) Date: Sat, 28 Jun 2008 14:11:45 +0200 Subject: matplotlib pylab plot() BadWindow error In-Reply-To: <16f10cf9-a966-4492-891b-d6aedb9ad428@p25g2000hsf.googlegroups.com> References: <16f10cf9-a966-4492-891b-d6aedb9ad428@p25g2000hsf.googlegroups.com> Message-ID: <48662a82$0$6558$9b4e6d93@newsspool3.arcor-online.net> Hi, > I have been warned not to use the show() command in interactive mode. I can't find the error but had better luck with interactivePython ipython which shippes with a pylab-friendly option. dan From Lie.1296 at gmail.com Tue Jun 17 01:36:07 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 16 Jun 2008 22:36:07 -0700 (PDT) Subject: How to catch StopIteration? References: <5f27181e-f558-4760-b6a8-4fb7ef4c5848@a9g2000prl.googlegroups.com> Message-ID: <7840d2fd-f176-40d7-bab0-095549d37f40@l28g2000prd.googlegroups.com> On Jun 17, 10:50?am, ccy56... at gmail.com wrote: > I'm writing to see calcuration process. > And so, I can't catch StopIteration... > > What is mistake? > > def collatz(n): > ? r=[] > ? while n>1: > ? ? r.append(n) > ? ? n = 3*n+1 if n%2 else n/2 > ? ? yield r > > for i, x in enumerate(collatz(13)): > ? try: > ? ? last = x[:i+1] > ? ? print x[:i+1] > ? except StopIteration: > ? ? print last.appnd(1) > > Output: > [13] > [13, 40] > [13, 40, 20] > [13, 40, 20, 10] > [13, 40, 20, 10, 5] > [13, 40, 20, 10, 5, 16] > [13, 40, 20, 10, 5, 16, 8] > [13, 40, 20, 10, 5, 16, 8, 4] > [13, 40, 20, 10, 5, 16, 8, 4, 2] > last.appnd(1) <= [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] ?# i want this > list In a for-loop, StopIteration is caught by the for-loop for your convenience (so you don't need to set up try-except of your own) def collatz(n): r=[] while n>1: r.append(n) n = 3*n+1 if n%2 else n/2 yield r for i, x in enumerate(collatz(13)): last = x[:i+1] print x[:i+1] last.append(1) print last PS: btw, you can't write 'print last.append(1)' because list operations like append doesn't return itself. From sniipe at gmail.com Tue Jun 24 09:18:14 2008 From: sniipe at gmail.com (sniipe at gmail.com) Date: Tue, 24 Jun 2008 06:18:14 -0700 (PDT) Subject: Difference between two dates References: Message-ID: <3355ac93-ed7f-4548-b674-224fbd5270b3@p25g2000hsf.googlegroups.com> Thank you for answers. I used C?dric Lucantis's way to resolve this problem and it works :D From bob at mellowood.ca Sun Jun 29 21:45:32 2008 From: bob at mellowood.ca (bvdp) Date: Sun, 29 Jun 2008 18:45:32 -0700 Subject: Function to import module to namespace In-Reply-To: <4cea42f2-b896-43a8-b8dd-ead2a1add327@z16g2000prn.googlegroups.com> References: <4cea42f2-b896-43a8-b8dd-ead2a1add327@z16g2000prn.googlegroups.com> Message-ID: John Machin wrote: Good questions. Short answer ... probably 'cause I've not thought the problem though completely :) > You are updating with *everything* in the 'more' module, not just the > functions. This includes such things as __name__, __doc__, __file__. > Could have interesting side-effects. > > One quick silly question: why do you want to do this anyway? > I'm writing a "simple" macro expander. I've got some mainline code which reads an input file, parses out macros, and expands them. So, in my input file I might have something like: a fjas j kj sdklj sdkl jfsdkl [ link somewhere sometext ] So, I need a function link() to evaluate and return "http://...." Instead of putting funcs like link() in my mainline I've stuck them in a module of their own. In the mainline I import funcs and then when I need to expand I have the following code: if not cmd in vars(funcs): error("Unknown function/variable '%s'" % cmd) if type(vars(funcs)[cmd]) == type(parse): txt = eval("""funcs.%s("%s")""" % (cmd, arg)) else: # not a func, just expand the variable if arg: error("Argument to variable '%s' not permitted." % cmd) txt = str(eval("funcs.%s" % cmd )) Of course, the question comes up ... what if a user (probably me) wants to add more functions? Easy enough to just edit funcs.py I suppose, but I thought it'd be nice to use more modules. So, I suppose that rather than adding the 2ndary module stuff to the default 'funcs.py' I could just as well have a look and check for the needed function in all the modules I've imported. > Sorry, *two* quick silly questions: are the add-on modules under your > control, or do you want to be able to do this with arbitrary modules? > [If under your control, you could insist that such modules had an > __all__ attribute with appropriate contents] Why would I want to do that ... and how? > A third: why do you want to import into an existing namespace? Now > that you know about __import__, why just not call the functions where > they are? Yeah, that would probably be cleaner (safer). Thanks. From grante at visi.com Sat Jun 14 15:17:56 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 14 Jun 2008 14:17:56 -0500 Subject: Creating a TCP/IP connection on already-networked computers References: <4853f269$0$11615$607ed4bc@cv.net> <4854123f$0$5017$607ed4bc@cv.net> Message-ID: On 2008-06-14, John Salerno wrote: > John Salerno wrote: >> if the program I write actually works and allows the two >> computers to speak to each other, will that be a result purely of the >> program, or will it have anything to do with the fact that they are >> already on a home network together? > > Here are the two programs. Server first, then client. They work, which > in itself amazes me that it's so simple to create a network connection > like this! But my basic question is this: would this connection work if > the two computers (each running one of these scripts) were completely > unrelated to one another? That depends on your definition of "unrelated." > My two are on a home network, but if I were to run the server > program and have a friend of mine (who lives somewhere else) > run the client program, would it still work? Yes, if the routers/firewalls/PCs were set up properly and if you changed the IP addresses in the programs appropriately. -- Grant Edwards grante Yow! I want the presidency at so bad I can already taste visi.com the hors d'oeuvres. From maehhheeyy at gmail.com Tue Jun 10 17:30:20 2008 From: maehhheeyy at gmail.com (maehhheeyy) Date: Tue, 10 Jun 2008 14:30:20 -0700 (PDT) Subject: can't assign to literal References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> Message-ID: On Jun 10, 1:21?pm, Matimus wrote: > On Jun 10, 12:53?pm, maehhheeyy wrote: > > > this is stopping my program from running properly. is there something > > wrong in my code when that happens? > > yes > > Post your code, or at least the full error message if you want more > details. > > Matt for 1 in oids, vals head_oids: SyntaxError: can't assign to literal From eliben at gmail.com Sat Jun 21 02:10:16 2008 From: eliben at gmail.com (eliben) Date: Fri, 20 Jun 2008 23:10:16 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> <485bd4f8$0$30999$426a74cc@news.free.fr> Message-ID: > d = {} > execcode in globals(), d > return d['foo'] > > My way: > > return function(compile(code, '', 'exec'), globals()) > With some help from the guys at IRC I came to realize your way doesn't do the same. It creates a function that, when called, creates 'foo' on globals(). This is not exactly what I need. Eli From casey.mcginty at gmail.com Mon Jun 30 04:52:24 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Sun, 29 Jun 2008 22:52:24 -1000 Subject: Help with Borg design Pattern In-Reply-To: <200806280525.54549.maric@aristote.info> References: <200806280525.54549.maric@aristote.info> Message-ID: On Fri, Jun 27, 2008 at 5:25 PM, Maric Michaud wrote: > Yes it is, but it's rather unneeded in Python, we prefer simply create a > module level dictionnary, these tricks are used in language like C++ or > Java. > > In python : > > mymodule.py : > > ModuleOptions = {} > > othermodule.py : > > import mymodule > > mymodule.ModuleOptions['Verbose'] = True > > or if you think encapsulation is important : > > mymodule.py : > > _ModuleOptions = {} > > def get_option(opt) : > return _ModuleOptions[opt] > .... > > And you're done. > > Using a module level instance seems the right way to go. I'm trying something like this. mymodule.py: class MyDict( dict): ... ... MyDict = MyDict() othermodule.py: import mymodule print mymodule.MyDict I'm running into a slight problem however that my run-time defined logging level is not correctly set until after the module has initialized, preventing any log messages from showing up. Is there a pythonic way to get around this? I'm thinking of adding a module init routine, but I don't feel like this is clean solution. - Casey -------------- next part -------------- An HTML attachment was scrubbed... URL: From stdenton at sbcglobal.net Sat Jun 7 17:11:29 2008 From: stdenton at sbcglobal.net (Sam Denton) Date: Sat, 07 Jun 2008 16:11:29 -0500 Subject: Need help porting Perl function In-Reply-To: References: Message-ID: kj wrote: > Hi. I'd like to port a Perl function that does something I don't > know how to do in Python. (In fact, it may even be something that > is distinctly un-Pythonic!) > > The original Perl function takes a reference to an array, removes > from this array all the elements that satisfy a particular criterion, > and returns the list consisting of the removed elements. Hence > this function returns a value *and* has a major side effect, namely > the target array of the original argument will be modified (this > is the part I suspect may be un-Pythonic). The two solutions thus far use the .index() method, which itself runs in O(n) time. This means that the provided functions run in O(n^2) time, which can be a problem if the list is big. I'd go with this: def partition(alist, criteria): list1, list2 = [], [] for item in alist: if criteria(item): list1.append(item) else: list2.append(item) return (list1, list2) def mod(alist, criteria=lambda x: x % 2 == 0): alist[:], blist = partition(alist, criteria) return blist >>> partition(range(10), lambda x: x % 2 == 0) ([0, 2, 4, 6, 8], [1, 3, 5, 7, 9]) >>> l=range(10) >>> mod(l) [1, 3, 5, 7, 9] >>> l [0, 2, 4, 6, 8] From tjreedy at udel.edu Fri Jun 13 16:00:14 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 13 Jun 2008 16:00:14 -0400 Subject: Mapping None. Why? References: Message-ID: "David C. Ullrich" wrote in message news:dullrich-571EC3.12043113062008 at text.giganews.com... | In article | , | Paddy wrote: | | > True, but None is not a function. It's a sentinel value to turn on the | > functionality. | | Uh, thanks. I think I knew that - I was just suggesting why | the way map works makes sense. filter(None, iterable) works the same way: None-> identity function, The immediate reason is the Python has no builtin id(). But apparently there is also historical precedent in the functional community for this convention. From lists at cheimes.de Sun Jun 8 06:20:32 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 08 Jun 2008 12:20:32 +0200 Subject: How to get System.Timers.Timer In-Reply-To: References: <2KSdncr7xeVoztbVnZ2dnUVZ_qninZ2d@comcast.com> Message-ID: John Machin wrote: > One grabs one's googler and goes a-huntin' ... > ==>> http://msdn.microsoft.com/en-us/library/system.timers.aspx > Looks like part of .NET so one might expect that one already have it. > However one would need to use IronPython to access it ... Or the PythonDotNET extension for CPython. Christian From sexxxy at autograf.pl Wed Jun 18 12:20:57 2008 From: sexxxy at autograf.pl (sexxxyy) Date: Wed, 18 Jun 2008 09:20:57 -0700 (PDT) Subject: The best FREE porn on the Net Message-ID: <2585e0da-ce84-4035-8487-9982d8b4ab67@f36g2000hsa.googlegroups.com> http://rozrywka.yeba.pl/show.php?id=2737 From maric at aristote.info Wed Jun 11 04:36:56 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 11 Jun 2008 10:36:56 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <783c55ec-a294-4600-91d9-4a0d78632c49@t12g2000prg.googlegroups.com> <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> Message-ID: <200806111036.58055.maric@aristote.info> Le Wednesday 11 June 2008 08:11:02 Russ P., vous avez ?crit?: > http://www.sofcheck.com > > Here is an excerpt from their website: > > "SofCheck?s advanced static error detection solutions find bugs in > programs before programs are run. By mathematically analyzing every > line of software, considering every possible input, and every path > through the program, SofCheck?s solutions find any and all errors that > cause a program to crash or produce an undefined result." Don't mix commercial discourse with technical, it desserves your point. Theoretically, wether a program has bugs or not is not computable. Static analysis as they imply is just nonsense. AFAIK, the efforts needed to make good static analysis are proven, by experience, to be at least as time consuming than the efforts needed to make good unit and dynamic testing. -- _____________ Maric Michaud From koski at emile.com Wed Jun 25 16:52:36 2008 From: koski at emile.com (Ilkka Koski) Date: Wed, 25 Jun 2008 15:52:36 -0500 Subject: Router debug References: Message-ID: <1214427156_6921@news-in1.superfeed.net> T.S.10.05.2008."Lis?ydinvoimaloiden rakentamisella ei ole tulevissa Euroopan ilmastotalkoissamme MIT??N merkityst?!"... .. Anteeksi nyt varmaan on sattunut maamme kivimmanluokan ydinlobbareillemme kirjoitusvirhe..Vaan eik? mit?, "ei mit??n merkityst?!" Turun-Sanoman p??kirjoituksesta vihon viimeiseksi luulisi l?ytyv?n tuollaista sanomaa. Vasta parisen kuukautta sitten kun TVO/Posiva YVA-kokouksissa kun olimme saaneet suut silm?t t?yteen vakuutuksia, ett? maahamme on saatava hyviss? ajoin ennen vuoden vaihdetta k?yntiin v?hint??n kolme, ellei per?ti enemm?n ydinvoimalahankkeita, nimenomaan ilmaston talkoitamme varten! Huikeaa muutosta ilmassa, vallan vallatonta muuten. Vain muutama p?iv? sitten maatamme suorastaan j?risytt?nyt YLE:n gallub kun esitteli maassamme olevan v?hint??n 2/3 ydinvastarinnan. Jo sen julkaisu enteili muutosten jykevyytt? aiemmista 80% ydinmy?nn?ist? olevan vailla vertaa. Huikein viesti oli siin?, ett? tuskin 4% suomalaisista oli edell? kerrotun TVO/Posivan triplavoimalan takana! On sanomatta selv??, ett? t?t? taustatuin masinoitua ydinalasajomenttaliteettia on osattu odotella jo vapun Heiniluoman NATO-vastakommentista asti. Koska NATO-j?senyyden viiv?stymisest? seuraa Pertti Simolan TVO:n YVA 4 kokouslausunnon alasajoennakointeja. Suomen ydinaikeiten tielle oli jo kasaantunut rajua vastustusta. My?s EU:n vaatimat 38<50% vuoden 2050 uudisenergtiatavoitteet osaltaan olivat nakertamassa ydinimpperialismin perussavijalkaa. KTM Pekkarisen jatkoa gallubista ei tarvinnut kauoja odotella. Ei tullut 3 uutta ydinvoimalahanketta t?lle vuodelle, ei edes ensi vuodelle. Hauskasti ydinvisiot sai yks kaks mit??n taustoittamatta 2v aikaviiveet tuosta vaan! Myrtyneiden ydinherraskaisten shokkia, p?lyilevi? ja h?mm?styneit?, suorastaan kauhistuneita kommenttejaan siit?, ett? mites kuitataan vuosittainen per?ti +10% ydins?hk?tarpeemme jatkovuosina saa vain silkkaa torua julkisuuden selkosilta nyt. Tulee eitt?m?tt? mieleen, enemm?n kuin paljon on maailmalta t?ytynyt tulla Suomen megamuutoksen takaamiseksi! Ilmasto kun oli se viimeinen keppihevonen ydinvoiman suomalaisuuden, ty?paikkojen luonnin, halpuusilluusiuoiden ja jopa Cernin viimevuotisen polttoainejatkuvuusennakointien kadottua totaaliseen laserjalostuksen 90% saannin romahdettua 11%. Nyt alkaa selke?sti ydinaavikoitumisen luomat ionosf??rituhot, It?merikuolemat kampamaneetteineen mehil?iskatoineen kaikkineen kasaamaan tulisia hiili? ydinalasajon kansainv?liseen kiihdytt?miseen. Maailman uraanivarojen loppuiminen energiapositiivisen? ei j?t? my?s selittelyille sijaa. Yht? kaikki ydinalan alasajo ALKOI! Joko mukana menee vain se, tai sit? k?ytt?v? ihmiskunta on luonnon selke? ja kiistaton Einsteinin ennakoima FAKTA! From deets at nospam.web.de Mon Jun 9 11:36:25 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 09 Jun 2008 17:36:25 +0200 Subject: How to find the first space? References: <7a91cc8f-2e93-46e9-8360-a01da9170187@m44g2000hsc.googlegroups.com> Message-ID: <6b5110F3a49r4U3@mid.uni-berlin.de> Johny wrote: > How can I find the first space using regex? > > For example I have text > Text=' This is a sample ' > > The last space I can remove by > Text=re.sub(r"\s(?!\w)",'',Text) > > but I do not know how to remove the first space. > Can anyone help? Use the strip-method, as defined on stringlike objects. Diez From ian.g.kelly at gmail.com Sun Jun 1 14:49:17 2008 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 1 Jun 2008 12:49:17 -0600 Subject: SPOJ, Problem Code: sumtrian, Reducing time taken to solve. In-Reply-To: References: Message-ID: <3fc761710806011149u176fcd61nc93e7e35825b5376@mail.gmail.com> On Sun, Jun 1, 2008 at 7:25 AM, Shriphani wrote: > I was trying to solve the sumtrian problem in the SPOJ problem set > ( https://www.spoj.pl/problems/SUMTRIAN/ ) and this is the solution I > submitted: http://pastebin.ca/1035867 > > The result was, "Your solution from 2008-06-01 15:13:06 to problem > SUMTRIAN, written in Python, > has exceeded the allowed time limit." > > I suspect that the first portion of my solution which looks at the > input, figures out the number of triangles and forms a list that > contains lists containing each row of the triangle, is wrong. I am not > too sure how to optimize it. I would appreciate help. Since you asked, I went and tried the problem myself and managed to get a solution accepted with a bit of work. Here are my suggestions with regard to your code: * You absolutely need to use psyco for this problem. The accepted solutions have memory usage of 36M+, which on SPOJ is a sure sign that psyco was used, and they're already just a hair under the time limit. * Instead of guessing "it's probably the input step", why don't you profile your code so that you *know* where the bottlenecks are? * Use xrange instead of range in for loops, and certainly don't use while loops for iteration. * max is quite slow for comparing only two things. It's faster to compare the two things yourself. Since this line may be executed millions of times, the difference could be quite significant. From phillip.oldham at gmail.com Fri Jun 13 04:43:36 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Fri, 13 Jun 2008 01:43:36 -0700 (PDT) Subject: Functionality similar to PHP's SimpleXML? Message-ID: <2cff2ee3-970d-4ba0-97e5-821c65fbf0d6@d1g2000hsg.googlegroups.com> I'm sure I'll soon figure out how to find these things out for myself, but I'd like to get the community's advice on something. I'm going to throw together a quick project over the weekend: a spider. I want to scan a website for certain elements. I come from a PHP background, so normally I'd: - throw together a quick REST script to handle http request/responses - load the pages into a simplexml object and - run an xpath over the dom to find the nodes I need to test One of the benefits of PHP's dom implementation is that you can easily load both XML and HTML4 documents - the HTML gets normalised to XML during the import. So, my questions are: Is there a python module to easily handle http request/responses? Is there a python dom module that works similar to php's when working with older html? What python module would I use to apply an XPath expression over a dom and return the results? From bruno.42.desthuilliers at websiteburo.invalid Fri Jun 27 04:28:06 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 27 Jun 2008 10:28:06 +0200 Subject: Adding functions to an existing instance In-Reply-To: References: <27adnS2SrIrOLv7VnZ2dnUVZ_rjinZ2d@earthlink.com> Message-ID: <4864a48c$0$2671$426a74cc@news.free.fr> Allen a ?crit : > bruno.desthuilliers at gmail.com wrote: >> On 26 juin, 17:18, Allen wrote: >>> I need a way to add a method to an existing instance, but be as close as >>> possible to normal instance methods. >> >> def set_method(obj, func, name=None): >> if not name: >> name = func.__name__ >> setattr(obj, name, func.__get__(obj, type(obj))) >> >> class Toto(object): >> pass >> >> toto = Toto() >> >> def titi(self): >> print self >> >> set_method(toto, titi) >> > > I tried that. func.__get__(obj, type(obj)) creates a bound method Indeed, since this is how bound methods are created anyway. > and > then sets an attribute to that, creating a cyclic reference. toto > contains a reference to the bound method, the bound method contains a > reference to the instance toto. Yes, true. I suppose you have good reasons to worry about cyclic references here, but I fail to imagine what they are. Another solution might be to create new class on the fly from the instance's class, inserting the function in the attribs dict, and then rebind the instance's __class__ to this new class, but that might be a bit overkill. From eliben at gmail.com Fri Jun 20 15:44:52 2008 From: eliben at gmail.com (eliben) Date: Fri, 20 Jun 2008 12:44:52 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> Message-ID: <8711b1fe-8256-4f6f-a3d7-f99f44eb23b0@e53g2000hsa.googlegroups.com> On Jun 20, 3:19 pm, George Sakkis wrote: > On Jun 20, 8:03 am, eliben wrote: > > > > > On Jun 20, 9:17 am, Bruno Desthuilliers > > 42.desthuilli... at websiteburo.invalid> wrote: > > > eliben a ?crit :> Hello, > > > > > In a Python program I'm writing I need to dynamically generate > > > > functions[*] > > > > (snip) > > > > > [*] I know that each time a code generation question comes up people > > > > suggest that there's a better way to achieve this, without using exec, > > > > eval, etc. > > > > Just to make things clear: you do know that you can dynamically build > > > functions without exec, do you ? > > > Yes, but the other options for doing so are significantly less > > flexible than exec. > > > > > But in my case, for reasons too long to fully lay out, I > > > > really need to generate non-trivial functions with a lot of hard-coded > > > > actions for performance. > > > > Just out of curiousity : could you tell a bit more about your use case > > > and what makes a simple closure not an option ? > > > Okay. > > > I work in the field of embedded programming, and one of the main uses > > I have for Python (and previously Perl) is writing GUIs for > > controlling embedded systems. The communication protocols are usually > > ad-hoc messages (headear, footer, data, crc) built on top of serial > > communication (RS232). > > > The packets that arrive have a known format. For example (YAMLish > > syntax): > > > packet_length: 10 > > fields: > > - name: header > > offset: 0 > > length: 1 > > - name: time_tag > > offset: 1 > > length: 1 > > transform: val * 2048 > > units: ms > > - name: counter > > offset: 2 > > length: 4 > > bytes-msb-first: true > > - name: bitmask > > offset: 6 > > length: 1 > > bit_from: 0 > > bit_to: 5 > > ... > > > This is a partial capability display. Fields have defined offsets and > > lengths, can be only several bits long, can have defined > > transformations and units for convenient display. > > > I have a program that should receive such packets from the serial port > > and display their contents in tabular form. I want the user to be able > > to specify the format of his packets in a file similar to above. > > > Now, in previous versions of this code, written in Perl, I found out > > that the procedure of extracting field values from packets is very > > inefficient. I've rewritten it using a dynamically generated procedure > > for each field, that does hard coded access to its data. For example: > > > def get_counter(packet): > > data = packet[2:6] > > data.reverse() > > return data > > > This gave me a huge speedup, because each field now had its specific > > function sitting in a dict that quickly extracted the field's data > > from a given packet. > > It's still not clear why the generic version is so slower, unless you > extract only a few selected fields, not all of them. Can you post a > sample of how you used to write it without exec to clarify where the > inefficiency comes from ? > > George The generic version has to make a lot of decisions at runtime, based on the format specification. Extract the offset from the spec, extract the length. Is it msb- first ? Then reverse. Are specific bits required ? If so, do bit operations. Should bits be reversed ? etc. A dynamically generated function doesn't have to make any decisions - everything is hard coded in it, because these decisions have been done at compile time. This can save a lot of dict accesses and conditions, and results in a speedup. I guess this is not much different from Lisp macros - making decisions at compile time instead of run time and saving performance. Eli From bedouglas at earthlink.net Wed Jun 18 23:33:38 2008 From: bedouglas at earthlink.net (bruce) Date: Wed, 18 Jun 2008 20:33:38 -0700 Subject: python/ruby question.. Message-ID: <049e01c8d1bd$44fcee30$0301a8c0@tmesa.com> hi... can someone point me to where/how i would go about calling a ruby app from a python app, and having the python app being able to get a returned value from the ruby script. something like test.py a = os.exec(testruby.rb) testruby.py foo = 9 return foo i know this doesn't work... but i've been searching for hours on this with no luck.... (and yeah, i'm relatively new to both ruby/python!!) thanks From Lie.1296 at gmail.com Sun Jun 1 14:51:14 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 1 Jun 2008 11:51:14 -0700 (PDT) Subject: How to get all the variables in a python shell References: <61f7681d-5cd3-4093-96f9-82f0e7383217@y38g2000hsy.googlegroups.com> Message-ID: <5d8f08ae-adcc-4eee-a6db-87d684df955f@q24g2000prf.googlegroups.com> On Jun 2, 1:29?am, Lie wrote: > lixinyi... at gmail.com wrote: > > Hi! > > > I'm currently working on a scientific computation software built in > > python. > > What I want to implement is a Matlab style command window <-> > > workspace interaction. > > > For example, you type 'a=1' in the command window, and you see a list > > item named 'a' in the workspace. > > You double click the icon of the item, and you see its value. You can > > modify the value of the list item, > > 1 -> 100 etc, ?after which if you go back to the command window and > > type 'a' ?and press enter, you see that > > varable a's value has been changed to 100. > > > So my question is : if you have two DOS command windows running under > > WINDOWS OS, how can you make them share the same internal variable > > buffer? Or is there any easier way to implement such kind of > > interaction? > > > Maybe I could just build a small database to store all the values and > > access them from both programs, but chances are sometimes I have to > > deal with big arrays, and they will eat extra memory if I keep them in > > a database. Is there anyway to access a shell's local memory buffer? > > I tried to use shell.interp.locals() in wxPython, but there's too many > > variables in the list which I don't actually need. > > > Come on guys, give me some ideas. Thanks in advance! > > In all kinds of code, it's best to seperate the workers code and the > UI code, in your case, you should create a backend (worker), which is > a class that stands on its own, and two foreground class (UI) that is > completely independent of each other but have the same interface. The > backend code would have an event that is raised when it is changed to > notify the UI (esp. The gui one) that it has changed since last time, > possibly passing info on what have been changed. The front ends, would > watch for this event as necessary (I don't think it is necessary for > the command line to watch this event) and react to it as necessary > like refreshing the view. The front-end window may only call functions > on the backend to interact with the data being worked on (in short the > backend class is opaque). > > This obliviate the need to share data between the two (or more) > windows (UI) because all the data are contained in the backend class > that the frontend can't access directly. To clarify what I meant, the front ends should never contain any working data except the ones needed for the UI to illustrate what it wanted to show at the moment, and even then, it is accessed in read only fashion. And actually because of Python's Global Interpreter Lock, which means that your program would all be contained in the same python interpreter instance (unless you do some workarounds), passing objects/ lists around between python program is cheap because they're just a "reference" passing (like pointer passing in C/C++) This approach is a simple "server-client" method (not a true server- client method though, since a true one cannot share unserialized data), and is extremely scalable, it's easy to add a third window for example, there is no need for every front end to be aware that there are other front ends, since it just watches for the "Changed" event from the backend. From kalakouentin at yahoo.com Mon Jun 2 02:08:17 2008 From: kalakouentin at yahoo.com (kalakouentin) Date: Mon, 02 Jun 2008 06:08:17 -0000 Subject: "Faster" I/O in a script Message-ID: I use python in order to analyze my data which are in a text form. The script is fairly simple. It reads a line form the input file, computes what it must compute and then write it it to a buffer/list. When the whole reading file is processed (essential all lines) then the algorithms goes ahead and writes them one by one on the output file. It works fine. But because of the continuous I/O it takes a lot of time to execute. I think that the output phase is more or less optimized. (A loop that reads the solutions list sequentially and puts "/n" in the appropriate intervals). Do you know a way to actually load my data in a more "batch-like" way so I will avoid the constant line by line reading? I guess I could read and store the whole text in a list with each cell being being a line and then process each line one by one again but I don't really think that would offer me a significant time gain. Thanx in advance for the time reading this. Pantelis From omer at no-log.org Thu Jun 26 10:11:36 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Thu, 26 Jun 2008 16:11:36 +0200 Subject: ask for a RE pattern to match TABLE in html In-Reply-To: <6a4f17690806260653i136681bdsabe0f6bb1dfab67b@mail.gmail.com> References: <6a4f17690806260653i136681bdsabe0f6bb1dfab67b@mail.gmail.com> Message-ID: <200806261611.36746.omer@no-log.org> Le Thursday 26 June 2008 15:53:06 oyster, vous avez ?crit?: > that is, there is no TABLE tag between a TABLE, for example >
    1.the curd of milk separated from the whey and prepared ? > in many ways as a food.
    something with out table tag
    > what is the RE pattern? thanks > > the following is not right > [^table]*?
  • The construct [abc] does not match a whole word but only one char, so [^table] means "any char which is not t, a, b, l or e". Anyway the inside table word won't match your pattern, as there are '<' and '>' in it, and these chars have to be escaped when used as simple text. So this should work: re.compile(r'.*') ^ this is to avoid matching a tag name starting with table (like ) -- C?dric Lucantis From stefan_ml at behnel.de Mon Jun 9 17:08:43 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 09 Jun 2008 23:08:43 +0200 Subject: Web Crawler - Python or Perl? In-Reply-To: References: <484D7329.6060107@behnel.de> <1a91e16d-ccfc-487a-80fc-4d9992455eb9@p25g2000hsf.googlegroups.com> Message-ID: <484d9bdc$0$6606$9b4e6d93@newsspool2.arcor-online.net> Ray Cote wrote: > Beautiful Soup is a bit slower, but it will actually parse some of the > bizarre HTML you'll download off the web. [...] > I don't know if some of the quicker parsers discussed require > well-formed HTML since I've not used them. You may want to consider > using one of the quicker HTML parsers and, when they throw a fit on the > downloaded HTML, drop back to Beautiful Soup -- which usually gets > _something_ useful off the page. So does lxml.html. And if you still feel like needing BS once in a while, there's lxml.html.soupparser. http://codespeak.net/lxml/elementsoup.html Stefan From pavlovevidence at gmail.com Mon Jun 9 18:33:40 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 9 Jun 2008 15:33:40 -0700 (PDT) Subject: Question by someone coming from C... References: Message-ID: On Jun 9, 5:00 pm, Skye wrote: > Writing this app in Python, not sure what the "best practice" would > be. > > I want a bitfield global logging level that allows me to turn specific > debugging modules on and off. If I was doing this in C, I'd just use > some globals like: > > unsigned int debug_level = 0; > #define DEBUG_GENERAL 0x0001 > #define DEBUG_CONFIG 0x0002 > #define DEBUG_OPTIONS 0x0004 > etc etc > > So I guess my questions are: > > 1. there doesn't seem to be a way to define global constants like in > other languages? > 2. any special voodoo to use bitfields in Python? Apart from the good advice "use the logging module", here is the Pythonic way you'd do this sort of thing in general. (There's not always a spiffy built-in module for anything you want to do; just usually. :) The lack of globals is a minor issue; you can get globally accessible values by storing them in a module and importing that module. The way I'd do the above is to define a module, say config.py, to hold configuration options. Then I'd define each condition in its own variable: debug_general = False debug_config = False debug_options = False I could then enable debugging by changing the value: import config config.debug_general = True And I could use print debugging output based on the config settings like this: import config if config.debug_general or config.debug_options: print_debugging_info() But again, the logging modules handles all this for you so no point for this particular task. P.S. I'd do it more or less this way in C, too. Carl Banks From bignose+hates-spam at benfinney.id.au Wed Jun 25 06:32:26 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 25 Jun 2008 20:32:26 +1000 Subject: python -regular expression - list element References: <62e21ec1-18f3-4572-b223-1b8a5c40688c@f63g2000hsf.googlegroups.com> Message-ID: <87abh9pzyd.fsf@benfinney.id.au> antar2 writes: > for x in list1: > re.compile(x) > for y in list2: > re.compile(y) > if x in y: > z = re.sub(x, 'u', y) > but this does not work You need to frotz the hymangirator with spangule. That, or show us the actual result you're seeing and how it differs from what you expect to happen. -- \ "I must say that I find television very educational. The minute | `\ somebody turns it on, I go to the library and read a book." -- | _o__) Groucho Marx | Ben Finney From eliben at gmail.com Sat Jun 21 01:28:44 2008 From: eliben at gmail.com (eliben) Date: Fri, 20 Jun 2008 22:28:44 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> <8711b1fe-8256-4f6f-a3d7-f99f44eb23b0@e53g2000hsa.googlegroups.com> <195ccfd2-3751-44ac-af5e-22c77f8999b7@k37g2000hsf.googlegroups.com> Message-ID: > So you are saying that for example "if do_reverse: data.reverse()" is > *much* slower than "data.reverse()" ? I would expect that checking the > truthness of a boolean would be negligible compared to the reverse > itself. Did you try converting all checks to identity comparisons with > None ? I mean replacing every "if compile_time_condition:" in a loop > with > > compile_time_condition = compile_time_condition or None > for i in some_loop: > if compile_time_condition is None: > ... > > It's hard to believe that the overhead of identity checks is > comparable (let alone much higher) to the body of the loop for > anything more complex than "pass". > There are also dict accesses (to extract the format parameters, such as length and offsets) to the format, which are absent. Besides, the fields are usually small, so reverse is relatively cheap. Eli From justin.mailinglists at gmail.com Tue Jun 3 22:10:38 2008 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Tue, 3 Jun 2008 19:10:38 -0700 (PDT) Subject: Handling some isolated iso-8859-1 characters References: Message-ID: <16ad09c5-5095-4444-8739-285f8d665fd3@q24g2000prf.googlegroups.com> On Jun 4, 2:38 am, Daniel Mahoney wrote: > I'm working on an app that's processing Usenet messages. I'm making a > connection to my NNTP feed and grabbing the headers for the groups I'm > interested in, saving the info to disk, and doing some post-processing. > I'm finding a few bizarre characters and I'm not sure how to handle them > pythonically. > > One of the lines I'm finding this problem with contains: > 137050 Cleo and I have an anouncement! "Mlle. =?iso-8859-1?Q?Ana=EFs?=" > Sun, 21 Nov 2004 16:21:50 -0500 > 4478 69 Xref: > sn-us rec.pets.cats.community:137050 > > The interesting patch is the string that reads "=?iso-8859-1?Q?Ana=EFs?=". > An HTML rendering of what this string should look would be "Anaïs". > > What I'm doing now is a brute-force substitution from the version in the > file to the HTML version. That's ugly. What's a better way to translate > that string? Or is my problem that I'm grabbing the headers from the NNTP > server incorrectly? >>> from email.Header import decode_header >>> decode_header("=?iso-8859-1?Q?Ana=EFs?=") [('Ana\xefs', 'iso-8859-1')] >>> (s, e), = decode_header("=?iso-8859-1?Q?Ana=EFs?=") >>> s 'Ana\xefs' >>> e 'iso-8859-1' >>> s.decode(e) u'Ana\xefs' >>> import unicodedata >>> import htmlentitydefs >>> for c in s.decode(e): ... print ord(c), unicodedata.name(c) ... 65 LATIN CAPITAL LETTER A 110 LATIN SMALL LETTER N 97 LATIN SMALL LETTER A 239 LATIN SMALL LETTER I WITH DIAERESIS 115 LATIN SMALL LETTER S >>> htmlentitydefs.codepoint2name[239] 'iuml' >>> From Lie.1296 at gmail.com Mon Jun 9 17:45:40 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 9 Jun 2008 14:45:40 -0700 (PDT) Subject: Separators inside a var name References: Message-ID: <2eb6cdc2-cd9e-42d4-9460-d9f9df680365@l17g2000pri.googlegroups.com> On Jun 10, 3:38?am, Rainy wrote: > On Jun 9, 2:05?pm, "Sebastian \"lunar\" Wiesner" > > wrote: > > ?Rainy at Montag 09 Juni 2008 19:29: > > > > I have a stylistic question. In most languages words in var. name are > > > separated by underscores or cap letters, resulting in var names like > > > var_name, VarName and varName. I don't like that very much because all > > > 3 ways of naming look bad and/or hard to type. > > > Then you better get used to such names, as they are common for many widely > > spread languages including C, C++, C#, Java, Python, Ruby, Perl and many > > more ;) ?You may like these or dislike these names, but you won't come > > around them ;) > > Well, I was thinking of using some obscure language for personal > projects > that may not need good libs, etc. But of course I agree that there are > no mainstream widely used languages that allow this. > > > > > > From what I understand, scheme can have variables like var-name. I'm > > > curious about reasons that python chose to disallow this. > > > "-" is an operator in Python. ?How should the parser know, > > whether "var-name" means "the object bound to var_dash_name" or "subtract > > the object bound to name from the object bound to var"? > > As I mentioned in another post, differentiate between var1 - var2 and > var-name. As Sebastian have said, it just can't work like that in python and most languages. var1-var2 is a subtraction, because - is an operator. Operator must allow spaces and lack of spaces, how would you want these to be interpreted then: a+b, a-b, a/b, a*b, a**b? In Lisp/Scheme there is no room for ambiguity since their syntax made it impossible that a-b means subtraction. Translated to python, your idea would mean we have to do this: sub(a, dashed-name) for all subtraction. [1] Lisp/Scheme have syntax like this: (- a b) for subtraction, (+ a b) for addition > > > > > Scheme can allows such names, because its a functional programming language. > > Subtracting in this language is not done through operators, but through > > functions. ?Therefore there is a clear difference between referencing a > > name or subtracting two ones: var-name vs (- var name). > > > > Another question I have is what other languages allow this naming scheme? > > > Other lisp dialects do, due to the same reasons as scheme. ? > > > > Were there any languages that allowed space as a separator? > > > None that I know of. ?Probably one could use unicode characters, that look > > like a space in languages, which allow unicode characters in identifiers > > (as Java or C#, iirc), but I doubt this. ?Anyway, even if allowed, this > > would be silly, since it obscures code to the eyes of the reader. > > Yes, that's of course out. I meant using real space. Real space or space-lookalike, allowing blank characters for variable names is a bad idea. It hurts readability by a factor of twenty. > > > What would be a practical way to separate variables from keywords in that > > > case? "some long variable name", 'just a string', or maybe using 2 spaces: > > > one var ?+ ?other var ?+ ?third var ? > > > I can't image a practical way to allow a space as character in names, while > > still maintaining it syntactic element for separation of names. ?Quotes are > > normally used for string or characters literals and a double space is hard > > to distinguish from a single space, and things like ${a name with spaces} > > is a lot nastier than names with underscores (which aren't bad at all, > > imho). > > I agree about ${name with spaces}. I would be interested in the > approach > of using something else for strings and using quotes for var names. > Not > perfect either but might be better than underscores... Err.. what's actually your problem with underscore? Quoting names is the worse idea ever, I'm sure he only reference it as a joke. Especially since it would be ambiguous whether the thing in the quote is a name or a string > > > > I think being able to easy have very long names for vars that are easy to > > > type would be a fairly significant advantage. > > > Names shouldn't be long, they should be expressive. ?If you can't give an > > object a _short_, but _expressive_ name, your object is too complicated ;) > > I'm not sure, I often find myself needing to use 4 words for var name, > and > then underscores I think don't look too good, I would say that > underscores > are kind of ok for 2 words, not very good for 3 words and bad for 4+ > words. > I think if spaces were allowed, I would sometimes use 5 word > variables. I think you need to think simple. KISS principle. Add documentation then use short, expressive names. Generally a shorter the name is more readable than 5-words names. Which ones is clearer: class Math(object): def add(a, b): return a + b def sub(a, b): return a - b and: class Mathematic(object): def addition(left_hand_side_operand, right_hand_side_operand): return left_hand_side_operand + right_hand_side_operand def subtraction(left_hand_side_operand, right_hand_side_operand): return left_hand_side_operand - right_hand_side_operand and short names also saves some typing. > > Btw, I don't really understand your refusal of underscores. ?In my opinion > > such names are harder to read than underscores, which look more like a real > > space, because the leave a space in the middle of a line, that you look at. > > If they are too hard for you to type, whats the point in swapping the dash > > and the underscore in your keyboard layout? > > To me, underscores_look_very_ugly. What_if_I_typed > part_of_every_sentence > with_an_underscore? Ugly! Swapping the dash and underscore are not a > bad > idea, it doesn't fix uglyness, though, and it adds a problem if you > have > to work on another system, because you will always type dash by > mistake > (which will look nice but won't work ;-) ). From ram.rachum at gmail.com Sun Jun 15 08:02:15 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Sun, 15 Jun 2008 05:02:15 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> Message-ID: On Jun 15, 2:48?pm, Peter Otten <__pete... at web.de> wrote: > ram.rac... at gmail.com wrote: > > Quick question: > > I have python code that does a lot of floating point arithmetic. How > > do I make it do the arithmetic in 64 bit? (I have a 64 bit CPU.) If > > I'll install a 64-bit operating system, will that do the trick? > > The Python float type uses a C double internally which is 64 bit even on 32 > bit CPUs. > > Peter Does it mean that even now it does arithmetic in 64 bit? I'm not getting enough precision. Is there any way to increase it? Ram. From bryancchan at gmail.com Mon Jun 2 18:23:29 2008 From: bryancchan at gmail.com (Chanman) Date: Mon, 2 Jun 2008 15:23:29 -0700 (PDT) Subject: Importing xlrd Message-ID: This is probably a simple question to most of you, but here goes. I've downloaded the xlrd (version 0.6.1) module and placed in in the site-packages folder. Now, when I write a script, I type: import sys import xlrd When I run it, there is an import error saying there is no module named xlrd. However when I type sys.path, the site-packages folder is definitely in the path. Do I somehow need to run the xlrd setup.py first before importing? Any help would be appreciated. From google at mrabarnett.plus.com Wed Jun 18 19:19:54 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 18 Jun 2008 16:19:54 -0700 (PDT) Subject: Does '!=' equivelent to 'is not' References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> <20080617120941.GE7349@dragontoe.org> <0fcecc82-0edd-4f57-865a-b2e558577281@x35g2000hsb.googlegroups.com> <44841b35-468b-447b-a925-1de019e0f63f@f24g2000prh.googlegroups.com> Message-ID: On Jun 18, 9:43?pm, Lie wrote: > On Jun 19, 2:51?am, Paul McGuire wrote: > > > On Jun 18, 2:22?pm, Lie wrote: > > > > I'm not a native English speaker, although I think my parents would > > > have liked me to be more straightforward when talking, cause I tend to > > > say things like "possibly", "maybe", "probably", and other ambiguous > > > expressions to the extent that it has frustrated them now and then. > > > Well, at least you *talk* to your parents! ?Mostly what I get from my > > kids is, "can I borrow 10 dollars?" > > lol, I rarely initiate the talk to my parents unless I have to, they > usually starts talking first which I usually responded with the > ambiguous statements. Well, in fact, I rarely initiate a talk with > anybody, it's my nature to keep myself in the shade until I have to be > in the light. > "'Tis better to remain silent and be thought a fool, than open one's mouth and remove all doubt." - Samuel Johnson. :-) > But I never asked for money up straight like that though. From littlesweetmelon at gmail.com Thu Jun 5 05:01:10 2008 From: littlesweetmelon at gmail.com (=?GB2312?B?zPC5zw==?=) Date: Thu, 5 Jun 2008 17:01:10 +0800 Subject: How to make py2.5 distutil to use VC2005? In-Reply-To: <5b8d13220806050134s3e6ad9dfn15bd4c5924551bdc@mail.gmail.com> References: <5b8d13220806040647o1148bf90x6b2b546e9cb339b5@mail.gmail.com> <5b8d13220806050134s3e6ad9dfn15bd4c5924551bdc@mail.gmail.com> Message-ID: > The problem is not compiler, but runtime. For example, if python is > built with runtime foo, and yours with runtime bar, and you use in bar > a file handle, you're screwed: > > http://msdn.microsoft.com/en-us/library/ms235460(VS.80).aspx > > That's why you cannot build a python extension with VS 2005 for python > 2003, in a reliable way. Thank you for providing this document. Indeed, passing internal pointers of one CRT lib to another is dangerous. But in most cases, the python extension only focus on computational-intensive jobs rather than API-intensive jobs. Therefore it is safe to let VS2003-built python to call VS2005-built extensions with some attentions. When you use distutil to trigger compilation, a special *python script* will check whether the default compiler is VS2003. If there is no VS2003, this script will pop-up the error for incompatible compilers. I really really wonder how to *force* distutil to use my specified compile. eg: (pseudo) python setup.py build -c VC2005 or python setup.py build --compiler=C:\VC8\cc --linker=C:\VC8\ld Regards, --- ShenLei From bruno.42.desthuilliers at websiteburo.invalid Wed Jun 25 03:27:52 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 25 Jun 2008 09:27:52 +0200 Subject: newb question on strings In-Reply-To: <5a29e27d-c1b4-4028-8e20-841c58e3f006@27g2000hsf.googlegroups.com> References: <998616c1-8b96-49a7-b830-f122f5f0ee54@a32g2000prf.googlegroups.com> <5a29e27d-c1b4-4028-8e20-841c58e3f006@27g2000hsf.googlegroups.com> Message-ID: <4861f36c$0$17492$426a74cc@news.free.fr> Dan Bishop a ?crit : > On Jun 24, 4:04 pm, "shand... at gmail.com" wrote: >> Are you trying to escape for a regular expression? >> >> Just do re.escape(). >> >>>>> print re.escape('Happy') >> Happy >>>>> print re.escape("Frank's Diner") >> Frank\'s\ Diner >> >> If you're escaping for URLs, there's urllib2.quote(), for a command >> line, use subprocess.list2cmdline. > > And if you're escaping for string literals in Python (or C and its > descendants), you can do: > >>>> print "Frank's Diner".encode('string-escape') > Frank\'s Diner > And finally, if you're escaping it to use it for a SQL query, any DB-API compliant adapter will automatically escape it's params if used correctly. From tjreedy at udel.edu Thu Jun 5 17:20:05 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 5 Jun 2008 17:20:05 -0400 Subject: Token Error: EOF in multiline statement References: <8d7b532c-9801-4a56-b9fa-ca0e7e152bdf@e39g2000hsf.googlegroups.com> Message-ID: "Matimus" wrote in message news:8d7b532c-9801-4a56-b9fa-ca0e7e152bdf at e39g2000hsf.googlegroups.com... | On Jun 5, 12:58 pm, maehhheeyy wrote: | > I'm not sure what it means but it always highlights the last line with | > nothing on it. My program has 63 lines and it highlights the 64th | > line. This keeps popping up whenever I try to run my program. Can you | > please help me fix this? | | You are going to have to post the code or at least the exception text. | It sounds like the last line of your code is missing a needed | parentheses, but it is impossible to know without more input. or { or [ or ''' or """ or the last line ends with '\' From johnjsal at NOSPAMgmail.com Mon Jun 16 20:21:35 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 16 Jun 2008 20:21:35 -0400 Subject: Buffer size when receiving data through a socket? Message-ID: <20080616202135.41c407de.johnjsal@NOSPAMgmail.com> I wrote some pretty basic socket programming again, but I'm still confused about what's happening with the buffer_size variable. Here are the server and client programs: -------------- from socket import * host = '' port = 51567 address = (host, port) buffer_size = 1024 server_socket = socket(AF_INET, SOCK_STREAM) server_socket.bind(address) server_socket.listen(5) while True: print 'waiting for connection...' client_socket, client_address = server_socket.accept() print '...connected from:', client_address while True: data = client_socket.recv(buffer_size) if not data: break client_socket.send('%s %s' % ('You typed:', data)) client_socket.close() server_socket.close() ------------ from socket import * host = 'localhost' port = 51567 address = (host, port) buffer_size = 1024 client_socket = socket(AF_INET, SOCK_STREAM) client_socket.connect(address) while True: data = raw_input('> ') if not data: break client_socket.send(data) data = client_socket.recv(buffer_size) if not data: break print data client_socket.close() --------------- I tried changing buffer_size to 10 and I got this output: john at john-laptop:~$ python myclient.py > hello You typed: > something hello > this is a long string You typed: > why doesn't this work right something > john at john-laptop:~$ My first question is, isn't buffer_size the number of bytes being sent at one time? If so, why doesn't 'hello' get printed after the server returns the data to the client? Isn't 'hello' just 5 bytes? Secondly, how is it working that once I type in a new string (e.g. 'something') and then the server returns data to the client, it prints the *previous* string, (i.e. 'hello')? Wouldn't the data variable get overwritten with the value, or is the value being stored somewhere else at this point? Thanks! From aweraw at gmail.com Tue Jun 10 00:37:53 2008 From: aweraw at gmail.com (Aidan) Date: Tue, 10 Jun 2008 14:37:53 +1000 Subject: Python, subprocess, dump, gzip and Cron Message-ID: <484e0521$1@dnews.tpgi.com.au> Hi, I'm having a bit of trouble with a python script I wrote, though I'm not sure if it's related directly to python, or one of the other software packages... The situation is that I'm trying to create a system backup script that creates an image of the system, filters the output though gzip, and then uploads the data (via ftp) to a remote site. The problem is that when I run the script from the command line, it works as I expect it, but when it is run by cron I only get a 20 byte file where the compressed image should be... does anyone have any idea as to why this might be happening? Code follows #!/usr/bin/python from subprocess import PIPE, Popen from ftplib import FTP host = 'box' filename = '%s.img.gz' % host ftp_host = '192.168.1.250' ftpuser, ftppass = 'admin', 'admin' dest_dir = '/share/%s' % host dump = Popen('dump 0uaf - /',shell=True,stdout=PIPE) gzip = Popen('gzip',shell=True,stdin=dump.stdout,stdout=PIPE) ftp = FTP(ftp_host) ftp.login(ftpuser,ftppass) ftp.cwd(dest_dir) ftp.storbinary('STOR %s' % filename,gzip.stdout) ftp.quit() print "Image '%s' created" % filename I appreciate all feedback. Thanks in advance. From mallikarjun.melagiri at hcl.in Wed Jun 4 06:38:11 2008 From: mallikarjun.melagiri at hcl.in (Mallikarjun Melagiri) Date: Wed, 04 Jun 2008 16:08:11 +0530 Subject: Problem with PEXPECT in Python References: 1183258018.859050.241980@o11g2000prd.googlegroups.com Message-ID: <48467093.30508@hcl.in> Hi Noah, I am new to python. I'm trying to use pexpect. Following is my problem definition: I should have a script on my machine A, which should 'ssh' to machine B and from there it shud copy a file to machine C thru 'scp'. Please help me. Regards Mallik From Robert.Bossy at jouy.inra.fr Wed Jun 18 05:22:40 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 18 Jun 2008 11:22:40 +0200 Subject: dict order Message-ID: <4858D3E0.7050004@jouy.inra.fr> Hi, I wish to know how two dict objects are compared. By browsing the archives I gathered that the number of items are first compared, but if the two dict objects have the same number of items, then the comparison algorithm was not mentioned. Note that I'm not trying to rely on this order. I'm building a domain-specific language where there's a data structure similar to python dict and I need an source of inspiration for implementing comparisons. Thanks RB From maric at aristote.info Mon Jun 30 05:27:09 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 30 Jun 2008 11:27:09 +0200 Subject: List Performance In-Reply-To: References: <42358e0b-a351-4862-8f6a-1938eedeff6c@s21g2000prm.googlegroups.com> Message-ID: <200806301127.11398.maric@aristote.info> Le Monday 30 June 2008 09:23:46 Peter Otten, vous avez ?crit?: > Ampedesign wrote: > > If I happen to have a list that contains over 50,000 items, will the > > size of the list severely impact the performance of appending to the > > list? > > No. > > $ python -m timeit -n20000 -s"items = []" "items.append(42)" > 20000 loops, best of 3: 0.554 usec per loop > $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" > 20000 loops, best of 3: 0.529 usec per loop But it surely could, if the box happens to be out of memory and begin to swap, while it's not, of course, an issue with python lists... -- _____________ Maric Michaud From fernandoREMOVE_THIS at easyjob.net Sun Jun 15 04:39:31 2008 From: fernandoREMOVE_THIS at easyjob.net (Fernando Rodriguez) Date: Sun, 15 Jun 2008 08:39:31 +0000 (UTC) Subject: Avoiding redirects with urllib References: Message-ID: Hello Fernando, >> I hope that's of some help! I think you may want to delve deeper >> into >> FancyURLopener... > The problem is that I'm using a subclass of FancyOpener and it doesn't > raise those exceptions. > Ok, forget it, I should have read the "fine" manual. O:-) From mike at ipglobal.net Mon Jun 30 10:53:54 2008 From: mike at ipglobal.net (Support Desk) Date: Mon, 30 Jun 2008 09:53:54 -0500 Subject: regex help Message-ID: <12af01c8dac1$1dc54530$a501a8c0@office.ipglobal.net> Hello, I am working on a web-app, that querys long distance numbers from a database of call logs. I am trying to put together a regex that matches any number that does not start with the following. Basically any number that does'nt start with: 281 713 832 or 1281 1713 1832 is long distance any, help would be appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alia_khouri at yahoo.com Sun Jun 1 04:47:55 2008 From: alia_khouri at yahoo.com (Alia Khouri) Date: Sun, 1 Jun 2008 01:47:55 -0700 (PDT) Subject: python's setuptools (eggs) vs ruby's gems survey/discussion Message-ID: <71ff8ebc-96e6-40f8-bcf2-43a0a2bd4135@w7g2000hsa.googlegroups.com> Can we open up the discussion here about how to improve setuptools which has become the de facto standard for distributing / installing python software. I've been playing around with ruby's gems which seems to be more more mature and usable. >From my perspective, the relative immaturity of setuptools and its simultaneous widespread use is a clear python weakness and can make python less easy to absorb than it should be. A few questions (please add more) so far are: (1) Should setuptools be standard? (2) What bugs you most about the current featureset? (3) Which features do you need the most (list in order of need)? (4) Shouldn't we just port gems to python? (5) What's the best community process to improve setuptools? (6) What's your ideal conception of the 'standard python package manager? To give this discussion some ammunition, I will post the output of the different '--help' for either tool: ================================================== SETUPTOOLS ================================================== C:\TMP>easy_install --help Global options: --verbose (-v) run verbosely (default) --quiet (-q) run quietly (turns verbosity off) --dry-run (-n) don't actually do anything --help (-h) show detailed help message Options for 'easy_install' command: --prefix installation prefix --zip-ok (-z) install package as a zipfile --multi-version (-m) make apps have to require() a version --upgrade (-U) force upgrade (searches PyPI for latest versions) --install-dir (-d) install package to DIR --script-dir (-s) install scripts to DIR --exclude-scripts (-x) Don't install scripts --always-copy (-a) Copy all needed packages to install dir --index-url (-i) base URL of Python Package Index --find-links (-f) additional URL(s) to search for packages --delete-conflicting (-D) no longer needed; don't use this --ignore-conflicts-at-my-risk no longer needed; don't use this --build-directory (-b) download/extract/build in DIR; keep the results --optimize (-O) also compile with optimization: -O1 for "python -O", -O2 for "python -OO", and -O0 to disable [default: -O0] --record filename in which to record list of installed files --always-unzip (-Z) don't install as a zipfile, no matter what --site-dirs (-S) list of directories where .pth files work --editable (-e) Install specified packages in editable form --no-deps (-N) don't install dependencies --allow-hosts (-H) pattern(s) that hostnames must match --local-snapshots-ok (-l) allow building eggs from local checkouts usage: easy_install-script.py [options] requirement_or_url ... or: easy_install-script.py --help ================================================== GEMS ================================================== C:\TMP>gem --help RubyGems is a sophisticated package manager for Ruby. This is a basic help message containing pointers to more information. Usage: gem -h/--help gem -v/--version gem command [arguments...] [options...] Examples: gem install rake gem list --local gem build package.gemspec gem help install Further help: gem help commands list all 'gem' commands gem help examples show some examples of usage gem help platforms show information about platforms gem help show help on COMMAND (e.g. 'gem help install') Further information: http://rubygems.rubyforge.org C:\TMP>gem help commands GEM commands are: build Build a gem from a gemspec cert Manage RubyGems certificates and signing settings check Check installed gems cleanup Clean up old versions of installed gems in the local repository contents Display the contents of the installed gems dependency Show the dependencies of an installed gem environment Display information about the RubyGems environment fetch Download a gem and place it in the current directory generate_index Generates the index files for a gem server directory help Provide help on the 'gem' command install Install a gem into the local repository list Display gems whose name starts with STRING lock Generate a lockdown list of gems mirror Mirror a gem repository outdated Display all gems that need updates pristine Restores installed gems to pristine condition from files located in the gem cache query Query gem information in local or remote repositories rdoc Generates RDoc for pre-installed gems search Display all gems whose name contains STRING server Documentation and gem repository HTTP server sources Manage the sources and cache file RubyGems uses to search for gems specification Display gem specification (in yaml) uninstall Uninstall gems from the local repository unpack Unpack an installed gem to the current directory update Update the named gems (or all installed gems) in the local repository which Find the location of a library For help on a particular command, use 'gem help COMMAND'. Commands may be abbreviated, so long as they are unambiguous. e.g. 'gem i rake' is short for 'gem install rake'. ======================================================= Hope this discussion can be constructive. In any case, I do appreciate the effort that went into creating setuptools (Thanks Phillip J. Eby :-). It's existence is clearly better than otherwise. Best, AK From eliben at gmail.com Tue Jun 24 01:18:47 2008 From: eliben at gmail.com (eliben) Date: Mon, 23 Jun 2008 22:18:47 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485f4f35$0$28417$426a74cc@news.free.fr> Message-ID: <0967da3a-1fea-401e-896d-9c099b3054ce@c58g2000hsc.googlegroups.com> > If code generation is not the best, and I fail to see any performance issue > that could explain such a choice, except a misunderstanding of > what "compilation" means in python, just don't use it, use closures or > callable instances, there are many way to achieve this. And while we're on the topic of what compilation means in Python, I'm not sure I fully understand the difference between compiled (.pyc) code and exec-ed code. Is the exec-ed code turned to bytecode too, i.e. it will be as efficient as compile-d code ? Eli From asdf at asdf.com Wed Jun 11 21:19:28 2008 From: asdf at asdf.com (asdf) Date: 12 Jun 2008 01:19:28 GMT Subject: matplotlib question Message-ID: <485079a0$0$11641$607ed4bc@cv.net> basically I need to plot a graph of data vs time. However when i use matplotlib the hr:min tick marks come out very close together and appear jumbled. So 12:00 comes out very close to 12:30 for example. There are two things I would like to do. First, is to increase the horizontal dimension of the graph. So basically increase the horizontal number of pixels. The data will always be from midnight to midnight it's just that i want it stretched out more horizontally. Also, how do i specify that i only want hourly tickmarks. So under the x-axis i only want to see 12:00 1:00 etc. thanks From pchilds at gmail.com Tue Jun 3 15:18:18 2008 From: pchilds at gmail.com (Paul Childs) Date: Tue, 3 Jun 2008 12:18:18 -0700 (PDT) Subject: Creating object in function doesn't seem to create a new object. Message-ID: <0d321eb1-8bc3-4ae4-893f-9ad137d9eca4@25g2000hsx.googlegroups.com> Hi folks, I'll start off with the code I wrote... (ActivePython 2.4 on Windows XP SP2) ------------------------------- class FlightCondition(object): lsf = [0,'Low Speed Flare'] vto = [0,'Vertical Take-Off'] def get_flight_condition(flight_data): fc1 = FlightCondition() for row in flight_data: fc1.lsf[0] += 1 fc1.vto[0] += 1 print 'in function get_flight_condition' print fc1.lsf print fc1.vto return fc1 for count in range(3): fc = get_flight_condition([1,2,3]) print 'returned fc' print fc.lsf print fc.vto --------------------------------- When I run it I get... in function get_flight_condition [3, 'Low Speed Flare'] [3, 'Vertical Take-Off'] returned fc [3, 'Low Speed Flare'] [3, 'Vertical Take-Off'] in function get_flight_condition [6, 'Low Speed Flare'] [6, 'Vertical Take-Off'] returned fc [6, 'Low Speed Flare'] [6, 'Vertical Take-Off'] in function get_flight_condition [9, 'Low Speed Flare'] [9, 'Vertical Take-Off'] returned fc [9, 'Low Speed Flare'] [9, 'Vertical Take-Off'] --------------------------------- I thought that when I wrote fc1 = FlightCondition() in the function it would create a new FlightCondition object which would be passed back every time. Instead it seems to re-reference the old version and continue to add to it. --------------------------------- What I expected was... in function get_flight_condition [3, 'Low Speed Flare'] [3, 'Vertical Take-Off'] returned fc [3, 'Low Speed Flare'] [3, 'Vertical Take-Off'] in function get_flight_condition [3, 'Low Speed Flare'] [3, 'Vertical Take-Off'] returned fc [3, 'Low Speed Flare'] [3, 'Vertical Take-Off'] in function get_flight_condition [3, 'Low Speed Flare'] [3, 'Vertical Take-Off'] returned fc [3, 'Low Speed Flare'] [3, 'Vertical Take-Off'] --------------------------------- Could someone please explain to me why I get the output I did instead of what I expected. How do I code my function so I get a new fc1 every time and my desired output? Thanks in advance. /Paul From davidj411 at gmail.com Fri Jun 20 16:34:59 2008 From: davidj411 at gmail.com (davidj411) Date: Fri, 20 Jun 2008 13:34:59 -0700 (PDT) Subject: sublassing as a verb Message-ID: docs on urllib module say this about the FancyUrlOpener: "class FancyURLopener( ...) FancyURLopener subclasses URLopener providing default handling for ..." does that mean the FancyURLopener is a subclass of URLopener? From 42flicks at gmail.com Tue Jun 10 06:42:39 2008 From: 42flicks at gmail.com (Mike) Date: Tue, 10 Jun 2008 22:42:39 +1200 Subject: TWITTER API and urllib2 Message-ID: <2b54d4370806100342h7a34f5f3p13ba81a6e873f14f@mail.gmail.com> Hello, I've spent the last couple of nights hacking away at a Python wrapper for the Twitter API that I can use for various things. I'm having trouble with one of the methods: user_timeline. ( http://groups.google.com/group/twitter-development-talk/web/api-documentation#HelpMethods ). This is the only method that is returning a HTTP 401. It seems strange and I'm not sure how to debug it further as the other methods requring authentication work. Please keep in mind the code is missing alot of polish :) - Though I'm open to suggestions on improvements. If anyone is familiar with this I'd really appreciate a hint as it has me stumped! (I really need this method for my functionality too!) --- import urllib2, urllib, urlparse class TwitterMethods(object): def __init__(self): pass def url_request(self,uri,authentication=None): auth = urllib2.HTTPBasicAuthHandler() netlock = urlparse.urlparse(uri) if authentication: passwdMgr = urllib2.HTTPPasswordMgrWithDefaultRealm() passwdMgr.add_password(None,netlock[1],authentication.username,authentication.password) auth = urllib2.HTTPBasicAuthHandler(passwdMgr) req = urllib2.Request(uri) o = urllib2.build_opener(auth) try: f = o.open(req) print f.readlines([0]) except o.error: print "error" #except: # print "unknown error" return def UserTimeline(self,authentication): self.url_request("http://twitter.com/statuses/user_timeline.xml ",authentication) class TwitterAuth(object): def __init__(self,username,password): self.username = username self.password = password p = TwitterMethods() auth = TwitterAuth('email at gmail.com','password') p.UserTimeline(auth) -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Thu Jun 12 21:10:49 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 12 Jun 2008 18:10:49 -0700 (PDT) Subject: howto split string with both comma and semicolon delimiters References: <3e2540ab-1d2a-45a5-a5b6-3f7ae7a4efac@x35g2000hsb.googlegroups.com> Message-ID: On Jun 12, 8:06 pm, bvdp wrote: > dmitrey wrote: > > hi all, > > howto split string with both comma and semicolon delimiters? > > > i.e. (for example) get ['a','b','c'] from string "a,b;c" > > > I have tried s.split(',;') but it don't work > > Thx, D. > > Howabout: > > s = s.replace(";", ",") > s = s.split(",") I've wondered in the past whether there would be sufficient need for things like s.split((',', ';')) and s.partition((',', ';')). From ebgssth at gmail.com Tue Jun 17 10:19:47 2008 From: ebgssth at gmail.com (js) Date: Tue, 17 Jun 2008 23:19:47 +0900 Subject: The best way to package a Python module? In-Reply-To: <8763sa9msw.fsf@benfinney.id.au> References: <8763sa9msw.fsf@benfinney.id.au> Message-ID: Thanks everyone for details. I'll try stealing some of the good bits of python-central of debian for my purpose. On Mon, Jun 16, 2008 at 10:43 AM, Ben Finney wrote: > Jean-Paul Calderone writes: > >> >What has changed is that the tools in common use for Debian >> >packaging of Python libraries have taken on the role of generating >> >those per-version copies at install time. >> >> exarkun at boson:~$ ls -l /usr/lib/python2.{4,5}/site-packages/sqlite/main.py >> lrwxrwxrwx 1 root root 63 2007-12-27 15:29 /usr/lib/python2.4/site-packages/sqlite/main.py -> /usr/share/pycentral/python-sqlite/site-packages/sqlite/main.py >> lrwxrwxrwx 1 root root 63 2007-12-27 15:29 /usr/lib/python2.5/site-packages/sqlite/main.py -> /usr/share/pycentral/python-sqlite/site-packages/sqlite/main.py >> exarkun at boson:~$ >> >> That doesn't seem to agree with your statement. Am I missing something? > > You are missing an inspection of the contents of the actual package > file. The package file itself contains only a single copy of the > Python module (at /usr/share/pycentral/site-packages/sqlite/main.py). > > What you see there on your filesystem was created at install time; the > installation tool figures out, at install time, which Python versions > need to be supported on this particular system, and creates those > symlinks. > > Thus, the change that's occurred is that the user doesn't need to > choose between "Python SQLite library for Python 2.4" and "Python > SQLite library for Python 2.5". > > There is no longer a separation at the package level by Python > version, so the user merely needs to choose (given your example) the > single "Python SQLite library", and the install process takes care of > setting it up for all supported versions of Python on the system. > > -- > \ "[Freedom of speech] isn't something somebody else gives you. | > `\ That's something you give to yourself." ?_Hocus Pocus_, | > _o__) Kurt Vonnegut | > Ben Finney > -- > http://mail.python.org/mailman/listinfo/python-list From ivan.illarionov at gmail.com Wed Jun 4 12:54:08 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 4 Jun 2008 16:54:08 +0000 (UTC) Subject: can python do some kernel stuff? References: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> <48366cfa$0$15168$607ed4bc@cv.net> <28c432f0-657c-4272-8cd4-a9081b013279@w5g2000prd.googlegroups.com> <69nigsF3499pqU2@mid.uni-berlin.de> <4836994e$0$11625$607ed4bc@cv.net> <69nls3F344g2cU1@mid.uni-berlin.de> <4836a876$0$11623$607ed4bc@cv.net> Message-ID: On Wed, 04 Jun 2008 11:24:11 -0500, Grant Edwards wrote: >> I can't understand why somebody might want to do kernel stuff in >> Python. > > we choose to put Python in kernel-space and do the other things, not > because they are easy, but because they are hard, because that goal > will serve to organize and measure the best of our energies and > skills... > > ;) tinypy rewritten in assembly probably could do the kernel job. CPython is far too big for the kernel. Another crazy idea. What about initd/launchd replacement in pure Python? Python would be the first PID. Isn't it more practical? Ivan From frank-milton at hotmail.com Tue Jun 3 17:18:10 2008 From: frank-milton at hotmail.com (Milton) Date: Tue, 3 Jun 2008 14:18:10 -0700 (PDT) Subject: How to increase the depth of the python traceback? Message-ID: <8d36d9cf-af00-43e2-8540-b50a2df04bd2@a1g2000hsb.googlegroups.com> How to increase the depth of the python traceback? I have some code that gets an exception deep in the python logging module and the traceback produced does not go back far enough to show my own code. How can the traceback limit be controlled in Python 2.5. The docs indicate that there is an attribute in the sys module ?tracebacklimit? that defaults to 1000 (affectively no limit). I cannot find this attribute in the sys module of Python2.5 From zaikenv at gmail.com Fri Jun 27 10:55:02 2008 From: zaikenv at gmail.com (Joel Corbin) Date: Fri, 27 Jun 2008 10:55:02 -0400 Subject: what is meaning of "@" in pyhon program. In-Reply-To: <88990b3d-1916-413f-83b9-796aabf43623@l28g2000prd.googlegroups.com> References: <88990b3d-1916-413f-83b9-796aabf43623@l28g2000prd.googlegroups.com> Message-ID: Hi Evan, The @ is a "decorator", knowing this should help you search for a better explanation than I could give... Have a look here to start: http://mail.python.org/pipermail/tutor/2006-September/048978.html Joel On Fri, Jun 27, 2008 at 10:48 AM, Evan wrote: > HI, > > When I check example of "cmd2" module (a enhancement of cmd module), I > can not understand all, for example: the character "@", > > +++++++++++++++++++++++++++++++++++++++++++++++++++++ > def options(option_list): > .................. > > class cmd(...): > ............................... > @options([make_option('-p', '--piglatin', action="store_true", > help="atinLay")]) > +++++++++++++++++++++++++++++++++++++++++++++++++++++ > > I do not understand what "@options" does, most time, I know what the > meaning of character "*" and character "**", but I was not use "@" > before. > > Thanks for your help. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nyamatongwe+thunder at gmail.com Sat Jun 28 19:19:56 2008 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sat, 28 Jun 2008 23:19:56 GMT Subject: pxssh submit su commands = very very slow In-Reply-To: <39f89067-8ee6-470a-92ce-77b46a344f37@34g2000hsf.googlegroups.com> References: <39f89067-8ee6-470a-92ce-77b46a344f37@34g2000hsf.googlegroups.com> Message-ID: gert: > This works but after the su command you have to wait like 2 minutes > before each command gets executed ? > s.sendline ('su') > s.expect('Password:') A common idiom seems to be to omit the start of the expected reply since it may not be grabbed quickly enough. Then the prompt has to time out. Try s.expect('assword:') Neil From gherron at islandtraining.com Sat Jun 28 12:04:20 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 28 Jun 2008 09:04:20 -0700 Subject: 2D online multiplayer framework? In-Reply-To: <6dc6195b-b8a0-42a9-a982-3a4b70943c24@r37g2000prm.googlegroups.com> References: <6dc6195b-b8a0-42a9-a982-3a4b70943c24@r37g2000prm.googlegroups.com> Message-ID: <48666104.3010507@islandtraining.com> George Oliver wrote: > I'm looking for a framework to support a 2D online real-time > multiplayer game (rugby league football with a lo-fi pixel look). The > GameProgramming page at the Python wiki had some suggestions but so > far nothing looks that promising, does anyone have some > recommendations? > > It would be ideal to play this through a web browser but I don't know > if that's practical. > > This aspect of programming is pretty new to me so I'm not sure if I > should start with something general like Twisted or if there's a > different path I should take. > > > thanks, George > -- > http://mail.python.org/mailman/listinfo/python-list > Pyglet is my favorite: http://www.pyglet.org/ Twisted might be fine for the "online multiplayer" parts, but really if you want a 2D/3D real-time game, start with a game framework. Gary Herron From jeffnyman at gmail.com Thu Jun 5 02:54:02 2008 From: jeffnyman at gmail.com (Jeff Nyman) Date: Wed, 4 Jun 2008 23:54:02 -0700 (PDT) Subject: os.path.walk -- Can You Limit Directories Returned? Message-ID: <65971e97-09eb-4295-a090-517341a86065@e53g2000hsa.googlegroups.com> Greetings all. I did some searching on this but I can't seem to find a specific solution. I have code like this: ========================================= def walker1(arg, dirname, names): DC_List.append((dirname,'')) os.path.walk('\\\\vcdcflx006\\Flex\\Sites', walker1, 0) ========================================= The Sites\ directory is set up like this: Sites\ Baltimore Birmingham .... And so forth. Each of the city directories has directories under it as well. The problem is that my code grabs every single directory that is under the various city directories when what I really want it to do is just grab the directories that are under Sites\ and that's it. I don't want it to recurse down into the sub-directories of the cities. Is there a way to do this? Or is os.path.walk not by best choice here? Any help and/or advice would be appreciated. - Jeff From toolmaster at 163.com Wed Jun 18 04:09:12 2008 From: toolmaster at 163.com (WaterWalk) Date: Wed, 18 Jun 2008 01:09:12 -0700 (PDT) Subject: Name lookup inside class definition References: <1c1a1181-905c-4401-ae00-36b3fabebab9@v1g2000pra.googlegroups.com> Message-ID: <24ea79d9-3715-43b9-b337-50627f84e69c@w4g2000prd.googlegroups.com> Ah, I see. Thank you all. From ivan.illarionov at gmail.com Wed Jun 4 03:44:38 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 4 Jun 2008 07:44:38 +0000 (UTC) Subject: Best way to modify code without breaking stuff. References: Message-ID: On Wed, 04 Jun 2008 00:25:19 -0700, Jesse Aldridge wrote: > I've got a module that I use regularly. I want to make some extensive > changes to this module but I want all of the programs that depend on the > module to keep working while I'm making my changes. What's the best way > to accomplish this? Version control system. http://en.wikipedia.org/wiki/List_of_revision_control_software Make your module a versioned repository. Make your changes in different place, then commit them. I use SVN and mercurial. Ivan From david at hlacik.eu Wed Jun 4 18:26:25 2008 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Thu, 5 Jun 2008 00:26:25 +0200 Subject: no module named py Message-ID: Hello, what this beautifull mesage which is messing me whole day means : *python: error , ('No module named py',), No module named py* as a result of class pdg.py which is called from nnrpd_auth.py. To be detailed ... news server inn is calling that when doing autentification , it calls nnrpd_auth.py where instance of my class is hooked into inn , when authentification begins it calls method authenticate(arguments) from pdg. I will provide as many information as needed to solve this mistery, becouse i really need to solve it. Thanks! #!/usr/bin/env python import ldap from nnrpd import syslog class news: server = 'ldap://dev01.net.hlacik.eu' user_dn = 'cn=pdg,ou=Operators,o=Polarion' user_pw = 'Pdg1' connectcodes = { 'READPOST':200, 'READ':201, 'AUTHNEEDED':480, 'PERMDENIED':502 } authcodes = { 'ALLOWED':281, 'DENIED':502 } def newsauth(self,match_username,match_password): base_dn = 'ou=Users,o=Polarion' filter = "(uid=" + match_username + ")" attrs = ['userPassword'] try : l = ldap.initialize(self.server) l.bind_s(self.user_dn, self.user_pw) raw_res = l.search_s( base_dn, ldap.SCOPE_SUBTREE, filter, attrs ) l.unbind() except ldap.SERVER_DOWN: print "Error, server down" return 2 except ldap.INVALID_CREDENTIALS: print "Error, invalid credentials" return 2 except ldap.LDAPError, e: print "Error, %s" % e for results in raw_res: (cn,search) = results for password in search["userPassword"]: if password == match_password: return 1 return 0 def authenticate(self, attributes): # just for debugging purposes syslog('notice', 'nnrpd_auth authenticate() invoked: hostname %s, ipaddress %s, interface %s, user %s' % (\ attributes['hostname'], \ attributes['ipaddress'], \ attributes['interface'], \ attributes['user'])) try: syslog('notice', "result %s" % self.newsauth('boss','bbbb')) except Exception, msg: syslog('notice', "error %s, %s, %s" % (type(msg),msg.args,msg)) # do username passworld authentication #if self.newsauth(attributes['user'], str(attributes['pass'])): # syslog('notice', 'authentication by username succeeded') # return ( self.authcodes['ALLOWED'], 'No error' ) #else: # syslog('notice', 'authentication by username failed') # return ( self.authcodes['DENIED'], 'Access Denied!') ------------------- nnrpd_auth_py : # # Sample authentication and authorization class. It defines all methods known # to nnrpd. # # Import functions exposed by nnrpd. This import must succeed, or nothing # will work! from nnrpd import * from pdg import * myauth = news() # ...and try to hook up on nnrpd. This would make auth object methods visible # to nnrpd. try: set_auth_hook(myauth) syslog('notice', "authentication module successfully hooked into nnrpd") except Exception, errmsg: syslog('error', "Cannot obtain nnrpd hook for authentication method: %s" % errmsg[0]) -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Sat Jun 7 20:07:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 7 Jun 2008 17:07:51 -0700 (PDT) Subject: Can this be done with list comprehension? References: Message-ID: <45692181-3b90-49c9-a0e5-8af933034a49@z16g2000prn.googlegroups.com> On Jun 8, 8:31 am, Karlo Lozovina <_karlo_ at _mosor.net_> wrote: > This is what I'm trying to do (create a list using list comprehesion, then > insert new element at the beginning of that list): > > result = [someFunction(i) for i in some_list].insert(0, 'something') result = ['something'] + [someFunction(i) for i in some_list] From pfreixes at gmail.com Fri Jun 13 07:55:30 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Fri, 13 Jun 2008 13:55:30 +0200 Subject: GIL cpu multi core usage problem In-Reply-To: References: <207312b70806091126t6d9c3479hfe39368cd06b029e@mail.gmail.com> Message-ID: <207312b70806130455h4db9c6dn91485837b7a4bf1c@mail.gmail.com> Hi, When you say this "C extensions (usually) release the GIL when they don't call into any Python code" do you talk about this macros ? Py_BEGIN_ALLOW_THREADS Py_END_ALLOW_THREADS On Wed, Jun 11, 2008 at 3:52 AM, Gabriel Genellina wrote: > En Mon, 09 Jun 2008 15:26:09 -0300, Pau Freixes > escribi?: > > Surly this is a recurring theme into python dev world, but I need your >> help >> for confirm if the follow image it's really >> >> http://www.milnou.net/~pfreixes/img/cpu_usage_gil_problem.png >> >> >> I'm writing a brief article for my blog and I need to make sure about the >> current problem with GIL and multi core environments, this picture try to >> explain with images the problem for scheduling multiple threads running >> python code of same interpreter into multiple cpu cores. Can anyone >> confirm >> to me this picture ? >> > > Yes, if both threads are executing pure Python code, they can't run > simultaneously. > > Note that: > - C extensions (usually) release the GIL when they don't call into any > Python code > - The interpreter also releases the GIL before any I/O operation > If the process is I/O bound then the GIL is not so important, and if it's > CPU bound you may benefit from reimplementing the critical parts in C (by > example, using NumPy for a number-crunching process). Another alternative is > to use multiple processes with some form of IPC instead of multiple threads. > These are the usual arguments against "fear of GIL". You should consider > your specific application to see if the GIL is actually a problem in your > case or not. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From pythonreptile at gmail.com Tue Jun 3 19:33:20 2008 From: pythonreptile at gmail.com (pythonreptile at gmail.com) Date: Tue, 3 Jun 2008 16:33:20 -0700 (PDT) Subject: Constructor re-initialization issue References: <00d47094-b687-48f2-9dc0-c92994a4f70c@y38g2000hsy.googlegroups.com> Message-ID: <513f9db0-b971-4644-aa1f-d990e335920a@u6g2000prc.googlegroups.com> On Jun 3, 12:59 pm, George Sakkis wrote: > On Jun 3, 6:11 pm, pythonrept... at gmail.com wrote: > > > > > Hello all, > > > I have come across this issue in Python and I cannot quite understand > > what is going on. > > > class Param(): > > def __init__(self, data={}, condition=False): > > if condition: > > data['class']="Advanced" > > print data > > > In the previous example, I expect the variable data to be re- > > initialized every time I construct an object type Param. However, when > > I do the following: > > > Param(condition=True) > > Param(condition=False) > > > The second call still prints {'class': 'Advanced'} > > > Shouldn't data be initialized to {} since it is the default in > > __init__? Why would the state of data be preserved between two > > independent instantiations? > > > Any help would be greatly appreciated. > > > M. > > This must be by far the most FAQ.. unfortunately it seems it will > remain for 3.x as well:http://www.python.org/doc/faq/general/#why-are-default-values-shared-... Thanks for clearing this up for me. M. From a.harrowell at gmail.com Wed Jun 25 14:33:05 2008 From: a.harrowell at gmail.com (TYR) Date: Wed, 25 Jun 2008 11:33:05 -0700 (PDT) Subject: Mobile Devices References: Message-ID: <549d4fcd-7c89-47dc-9a44-8e3e6ac92ed2@d77g2000hsb.googlegroups.com> On Jun 25, 10:38?am, rodmc wrote: > Hi, > > I have been scouting around online for information on how to use > Python and a GUI toolikit to develop mobile devices. At present I am > using wxPython for desktop apps and would like to continue using that > if possible. Anyway, I would like to know what people would recommend > for developing mobile applications which can run on Windows Mobile and > Mac OS X (iPhone etc)? It would also be cool if the same apps could > run where possible (or atleast part of them) on desktop machines as > well. > > Any tips, experiences etc welcome. This is really to stimulate some > general discussion. > > Best, > > rod I know nothing of running Python on WinMob devices, but I see no reason why it shouldn't be possible. However MS doesn't, as far as I know, support it or provide any tools/sdks/ecosystem services. Apple has its own rather closed ecosystem for iPhone support, but as everyone knows there is a vigorous hacker community doing unofficial things with them. However, I'm not aware of any python activity. Most mobile Python activity is in the nokiasphere; there is a Nokia- backed version of Python for S60 devices, which is fully supported, includes Python libs that wrap the devices' native functionality up to and including N95 accelerometers, and has a desktop mobile device emulator for convenience. However, wxPython wouldn't really be relevant as pyS60 includes its own native GUI toolkit, appuifw; no reason why you couldn't install the module and try, though, but using appuifw does ensure that your GUI will look like all the other stuff on the phone. It won't, of course, work on your PC. From shandy.b at gmail.com Tue Jun 24 17:04:04 2008 From: shandy.b at gmail.com (shandy.b at gmail.com) Date: Tue, 24 Jun 2008 14:04:04 -0700 (PDT) Subject: newb question on strings References: Message-ID: <998616c1-8b96-49a7-b830-f122f5f0ee54@a32g2000prf.googlegroups.com> Are you trying to escape for a regular expression? Just do re.escape(). >>> print re.escape('Happy') Happy >>> print re.escape("Frank's Diner") Frank\'s\ Diner If you're escaping for URLs, there's urllib2.quote(), for a command line, use subprocess.list2cmdline. Generally, the module that consumes the string should provide a function like escape(). On Jun 24, 1:27?pm, regex_jedi wrote: > ok, I have looked a lot of places, and can't seem to get a clear > answer... > > I have a string called > ? ?each_theme > > Some values of the string may contain a single quote as in - > ? ?Happy > ? ?Sad > ? ?Nice > ? ?Frank's Laundry > ? ?Explosion > > Notice that the 4th value has a single quote in it. Well, I need to > make sure that the single quote is escaped before handing it off for > further processing to a class I later call for some other processing. > > So I thought, no big deal, I should be able to find a way to escape > the single quote on the string. ?I am a perl and PHP guy, so I do a > lot of regex stuff. ?I did a quick search and found someone had said > to use this re.sub function, so I tried. ?But the following doesn't > work. To be honest, I am a little lost with all the modules and > classes required to do simple math or string functions in Python. > None of it seems built it in.. its all import modules... ?Here is what > I am trying... > > ? ? ? ? # escape single quotes in theme name > ? ? ? ? re.sub('''(['"])''', r'\\\1', each_theme) > > you python masters... show me the way please... > > thanks > regex_jedi From gagsl-py2 at yahoo.com.ar Fri Jun 13 05:47:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Jun 2008 06:47:22 -0300 Subject: boolian logic References: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> Message-ID: En Fri, 13 Jun 2008 06:15:52 -0300, marc wyburn escribi?: > HI all, I'm a bit stuck with how to work out boolian logic. > > I'd like to say if A is not equal to B, C or D: > do something. > > I've tried > > if not var == A or B or C: > and various permutations but can't seem to get my head around it. I'm > pretty sure I need to know what is calulated first i.e the not or the > 'OR/AND's if A not in (B, C, D): ... "or" has less priority than not, and all boolean operators have less priority than comparisons. So your expression above reads as: if (not (var==A)) or B or C and the three or'ed expressions are evaluated from left to right (short-circuit: stop as soon as any true value is found). Evaluation order is defined in the Reference Manual, see in particular, operator precedence is summarized in -- Gabriel Genellina From giles.thomas at resolversystems.com Wed Jun 4 14:17:39 2008 From: giles.thomas at resolversystems.com (Giles Thomas) Date: Wed, 4 Jun 2008 11:17:39 -0700 (PDT) Subject: ANN: Resolver One 1.1 released References: <827962c7-36ad-4e66-bae3-0ca033054501@a1g2000hsb.googlegroups.com> <4846D9BF.90406@behnel.de> Message-ID: <6670b267-c2be-4fe3-9e83-48d3fa77fc70@s50g2000hsb.googlegroups.com> Stefan Behnel wrote: > Giles Thomas wrote: > > We are proud to announce the release of Resolver One, version 1.1 - the > > largest IronPython application in the world, we think, at 38,000 lines > > of production code backed up by 130,000 lines of unit and functional > > tests. > > Is it really IronPython specific code or would it run on standard Python? It's really IronPython-specific, which is both a blessing - there's a suprising amount of really good .NET classes out there and it's great to be able to script them using Python from a grid-based environment - and a curse, because we lose the cross-platform capabilities and the C extensions like numpy. We're working on sorting out the latter with a project called Ironclad () which aims to get C extensions working in IronPython. For the cross-platform stuff, in the longer term we hope to be Mono-compatible and so be able to support Linux and the Mac. All the best, Giles -- Giles Thomas MD & CTO, Resolver Systems Ltd. giles.thomas at resolversystems.com +44 (0) 20 7253 6372 Try out Resolver One! (Free registration required) 17a Clerkenwell Road, London EC1M 5RD, UK VAT No.: GB 893 5643 79 Registered in England and Wales as company number 5467329. Registered address: 843 Finchley Road, London NW11 8NA, UK From dbpokorny at gmail.com Wed Jun 18 17:58:04 2008 From: dbpokorny at gmail.com (dbpokorny at gmail.com) Date: Wed, 18 Jun 2008 14:58:04 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> Message-ID: Wow, I was completely wrong about sorted dicts and odicts. On Jun 17, 4:21 am, bearophileH... at lycos.com wrote: > mean. I think for this data structure it's important to keep all the > normal dict operations at the same speed. If you use a C Why keep the normal dict operations at the same speed? There is a substantial cost this entails. It seems that some odict solutions take up 4n words per entry in the limit (ignoring the fixed percentage growth space for lists and dicts). This is n words for _keys and 3n words for the underlying dict. What about storing the key:value pairs as a pair of lists (maybe interleaved)? Key lookup then becomes an O(n) operation, but the storage requirements are reduced to 2n from 4n. Here is a hypothetical (somewhat contrived) example: odicts are used to store the attributes of XML elements in a medium-sized XML document (say 250K). If the required munging does some surgery on elements 3-4 layers deep in a few places, then the number of key lookups may be relatively small. (Assuming that very few odicts will have more than 30 entries, each individual lookup will be fairly quick as well). The document has to be loaded into memory anyway, so the extra cost of key lookups is more than compensated for by the substantial reduction in the number of cache line misses. The main concern is that doubling the size of the data structure in order to turn key lookup into an O(1) operation may give worse performance in the common case (this is a personal impression from reading the use case list in the rationale), and a data structure like this seems to be way off by itself in the time-space complexity landscape. In this case the odict no longer inherits from the dict. Cheers, David From __peter__ at web.de Sun Jun 15 14:43:55 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Jun 2008 20:43:55 +0200 Subject: randrange loops References: <6e424f2a-872d-4dd1-b28d-cf2a985895c9@j22g2000hsf.googlegroups.com> Message-ID: luislupe at gmail.com wrote: > I've created a method where the script defines twenty variables and > several of them should be random having a maximum and a minimum value. > > What I did was this: > > from random import randrange as rr, random > > self.tr2_vezes = self.rr(self.d_tr2_vezes[0],self.d_tr2_vezes[-1], > 1) # just an example, others are similar > > The minimum and maximum limits are never lower than -50 and higher > than 250 and are integer. > > Many times, not always, the problem is that the script just loops > forever and no value is chosen for the variable. > > What's happening here? What am I doing wrong? You don't provide enough information. Please show as a small script that demonstrates the behaviour you describe. Peter From george.sakkis at gmail.com Thu Jun 5 13:22:44 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 5 Jun 2008 10:22:44 -0700 (PDT) Subject: Tuples part 2 References: <6d3e6d40-63a6-40d1-8ea4-5ddf40238d8d@m44g2000hsc.googlegroups.com> <99bc30fb-532a-4c4f-9f5e-e7a18c28d2a5@z72g2000hsb.googlegroups.com> <0ecaaa47-3ad4-4f67-9d48-94d5d1951bc6@y21g2000hsf.googlegroups.com> Message-ID: On Jun 5, 11:48 am, Ivan Illarionov wrote: > On 5 ???, 19:38, George Sakkis wrote: > > > > > On Jun 5, 11:21 am, Ivan Illarionov wrote: > > > > On 5 ???, 18:56, Ivan Illarionov wrote: > > > > > On 5 ???, 18:19, "victor.hera... at gmail.com" > > > > wrote: > > > > > > On Jun 5, 3:49 pm, Ivan Illarionov wrote: > > > > > > > On 5 ???, 01:57, "victor.hera... at gmail.com" > > > > > > wrote: > > > > > > > > Hi Everyone, > > > > > > > > i have another question. What if i wanted to make n tuples, each with > > > > > > > a list of coordinates. For example : > > > > > > > > coords = list() > > > > > > > for h in xrange(1,11,1): > > > > > > > for i in xrange(1, 5, 1) : > > > > > > > for j in xrange(1, 5, 1) : > > > > > > > for k in xrange(1,2,1) : > > > > > > > coords.append((i,j,k)) > > > > > > > lista+str(h)= tuple coords > > > > > > > print tuple(coords) > > > > > > > > so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do > > > > > > > it the way i show you above but it is not working properly. I wish you > > > > > > > could help me with that. Thanks again, > > > > > > >>> from itertools import repeat, izip > > > > > > >>> coords = tuple((i,j,k) for i in xrange(1,5) for j in xrange(1,5) for k in xrange(1,2)) > > > > > > >>> locals().update(("tuple%s" % i, coord) for i, coord in izip(xrange(1,11), repeat(coords))) > > > > > > >>> tuple1 > > > > > > > ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (2, 1, 1), (2, 2, 1), (2, > > > > > > 3, 1), (2 > > > > > > , 4, 1), (3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1), (4, 1, 1), (4, 2, > > > > > > 1), (4, 3 > > > > > > , 1), (4, 4, 1)) > > > > > > > Does this help? > > > > > > > But I don't understand why you need this? > > > > > > > Ivan > > > > > > Hi, > > > > > > What i need is, for example: > > > > > > tuple 1=((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)) > > > > > > tuple 2=((2, 1, 1), (2, 2, 1), (2, 3, 1), (2, 4, 1)) > > > > > > tuple 3=((3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1)) > > > > > > and so on. Please help me and sorry for not taking the time to post my > > > > > questions properly. > > > > > > Victor > > > > > Or even so: > > > > > locals().update(("tuple_%s" % i, tuple((i,j,k) for j in range(1,5) for > > > > k in range(1,2))) for i in range(1,5)) > > > > > Ivan > > > > Tried to make it readable: > > > > def iter_coords(i): > > > for j in xrange(1,5): > > > for k in xrange(1,2): > > > yield i, j, k > > > > def iter_vars(): > > > for i in xrange(1, 5): > > > yield "tuple_%s" % i, tuple(iter_coords(i)) > > > > locals().update(dict(iter_vars())) > > > locals().update() works by accident here because it's in global scope; > > it doesn't work within a function. > > > Use a proper data structure, like a dict or a list, and access each > > tuple list as 'tuples[n]' instead of 'tuple_n'. > > > George > > OP wanted variables and I showed him how to do this. I agree that a > list or a dict would be better. > > Ivan Generating variable names at runtime doesn't work for locals and it is a bad solution for globals in 99.9% of the cases. It is usually more helpful to point someone who can't even express his problem clearly to the right direction, rather than taking his pseudocode literally and coming up with a semi-working translation. George From deets at nospam.web.de Sun Jun 15 16:12:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 15 Jun 2008 22:12:00 +0200 Subject: Removing inheritance (decorator pattern ?) In-Reply-To: References: Message-ID: <6blbcoF3b6v17U1@mid.uni-berlin.de> George Sakkis schrieb: > I have a situation where one class can be customized with several > orthogonal options. Currently this is implemented with (multiple) > inheritance but this leads to combinatorial explosion of subclasses as > more orthogonal features are added. Naturally, the decorator pattern > [1] comes to mind (not to be confused with the the Python meaning of > the term "decorator"). > > However, there is a twist. In the standard decorator pattern, the > decorator accepts the object to be decorated and adds extra > functionality or modifies the object's behavior by overriding one or > more methods. It does not affect how the object is created, it takes > it as is. My multiple inheritance classes though play a double role: > not only they override one or more regular methods, but they may > override __init__ as well. Here's a toy example: > > class Joinable(object): > def __init__(self, words): > self.__words = list(words) > def join(self, delim=','): > return delim.join(self.__words) > > class Sorted(Joinable): > def __init__(self, words): > super(Sorted,self).__init__(sorted(words)) > def join(self, delim=','): > return '[Sorted] %s' % super(Sorted,self).join(delim) > > class Reversed(Joinable): > def __init__(self, words): > super(Reversed,self).__init__(reversed(words)) > def join(self, delim=','): > return '[Reversed] %s' % super(Reversed,self).join(delim) > > class SortedReversed(Sorted, Reversed): > pass > > class ReversedSorted(Reversed, Sorted): > pass > > if __name__ == '__main__': > words = 'this is a test'.split() > print SortedReversed(words).join() > print ReversedSorted(words).join() > > > So I'm wondering, is the decorator pattern applicable here ? If yes, > how ? If not, is there another way to convert inheritance to > delegation ? Factory - and dynamic subclassing, as shown here: import random class A(object): pass class B(object): pass def create_instance(): superclasses = tuple(random.sample([A, B], random.randint(1, 2))) class BaseCombiner(type): def __new__(mcs, name, bases, d): bases = superclasses + bases return type(name, bases, d) class Foo(object): __metaclass__ = BaseCombiner return Foo() for _ in xrange(10): f = create_instance() print f.__class__.__bases__ Diez From johnjsal at gmailNOSPAM.com Fri Jun 27 22:56:40 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Fri, 27 Jun 2008 22:56:40 -0400 Subject: Using just the Mako part of Pylons? Message-ID: <4865a871$0$5024$607ed4bc@cv.net> I just installed Pylons onto my hosting server so I could try out templating with Mako, but it seems a little more complicated than that. From the look of it all, the site seems to want a full Pylons application. Is it possible to just use regular HTML files with a bit of the Mako language embedded, or will I actually have to use all aspects of Pylons? In other words, can I use *just* Mako (sort of like as a replacement for PHP) without having to use a framework? For example, I'd like to just test out the <%include /> tag and see it in action, but the site doesn't seem to be looking for a regular HTML file (like index.html), it seems to want a "controller". So is Pylons overkill for just this? How would I try out *just* Mako? Thanks! From goldnery at gmail.com Thu Jun 12 22:22:58 2008 From: goldnery at gmail.com (Gandalf) Date: Thu, 12 Jun 2008 19:22:58 -0700 (PDT) Subject: Charset (hopefully for the last time I ask) References: Message-ID: <9a899d5a-fb53-4fd7-8e61-89a04a35c780@d77g2000hsb.googlegroups.com> Yes, it is 1255 it's surprising you know that. any way this is the code I tried search=cnrl.GetValue() search= search.decode("cp1255") search=search.encode("utf8") word='' category=1 cur.execute('select * from hebrew_words where word like ?', [''+search+'']) this is the error it send me : 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) have any idea? Thank you for trying any way. it worms my Jewish art :) From mensanator at aol.com Mon Jun 9 01:53:15 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 8 Jun 2008 22:53:15 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net><484ad07b$0$25721$607ed4bc@cv.net> <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> <484c9830$0$5009$607ed4bc@cv.net> Message-ID: On Jun 8, 9:40?pm, John Salerno wrote: > Mensanator wrote: > > On Jun 8, 3:19?am, "Terry Reedy" wrote: > >> "Mensanator" wrote in message > > >>news:8d7c0912-422f-4480-a034-078f9dbcae24 at 2g2000hsn.googlegroups.com... > >> | On Jun 7, 6:43?pm, "Terry Reedy" wrote: > >> | > zip(range(9,2000000000), iterable) > >> | > >> | Oh, dear. You didn't actually try this, did you? > > >> Works fine in Py3, which is what I use now. > > > You really ARE cruel to the newbies, aren't you? > > > Don't you think it would have been appropriate > > to attach a large red label: WARNING! PY3! > > Heh heh, don't worry. Every time I see a range function, I immediately > think "creates a list". Not sure how I got into that habit, but it > happens every time! :) You probably got into that habit because that's what it does in 2.x, create a list. Now, if you're expecting that to happen you'll in for a surprise when you switch to Py3, won't you? From wicijowski at gmail.com Tue Jun 3 08:52:18 2008 From: wicijowski at gmail.com (janislaw) Date: Tue, 3 Jun 2008 05:52:18 -0700 (PDT) Subject: Ideas for master's thesis References: <15f65d1f-0e99-4661-a33f-4f16bb7d5ad2@l64g2000hse.googlegroups.com> Message-ID: <8099fd0b-607f-41a4-b918-03c765540407@59g2000hsb.googlegroups.com> On Jun 3, 2:27?am, miller.pau... at gmail.com wrote: > I'm sure you could probably find something having to do with Pypy > (http://codespeak.net/pypy/dist/pypy/doc/home.html) that would be both > manageable and significant enough to warrant a Master's thesis. The Pypy will fade out. You can for example write a compiler for LISP to CPython bytecode. Fits well for a master thesis. Regards, Jan Wicijowski From panyongzhi at gmail.com Mon Jun 2 09:22:14 2008 From: panyongzhi at gmail.com (Fossil Pan) Date: Mon, 2 Jun 2008 06:22:14 -0700 (PDT) Subject: a question about the #prefix of sys.argv References: Message-ID: <26ccd41d-3a6a-4b0e-9583-efb2d964441d@b5g2000pri.googlegroups.com> On Jun 2, 8:50 am, Aldarion wrote: > On 6?2?, ??8?05?, Peter Otten <__pete... at web.de> wrote: > > > Aldarion wrote: > > > for the little script > > > #egg.py > > > import sys > > > for k,v in enumerate(sys.argv): > > > print k,v > > > > it ignores the part after # on linux > > > below is the running output on windows and linux. no clue here. > > > This has nothing to do with python, it's the shell that treats the # and > > everything that follows as a comment. > > > $ ./listargs.py alpha #beta > > 0 ./listargs.py > > 1 alpha > > > But you can escape it: > > > $ ./listargs.py alpha \#beta > > 0 ./listargs.py > > 1 alpha > > 2 #beta > > > $ ./listargs.py alpha '#beta' > > 0 ./listargs.py > > 1 alpha > > 2 #beta > > > Peter > > thanks everyone for the quickly reply, i see now. Thank you Aldarion for your post. From bj_666 at gmx.net Sat Jun 7 04:15:01 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Jun 2008 08:15:01 GMT Subject: Parsing a path to components References: <7d7dd66c-b2bb-4a9a-a2e4-589079cda97b@e39g2000hsf.googlegroups.com> <14bf5448-4677-4ced-9d79-b4eb0c048218@56g2000hsm.googlegroups.com> Message-ID: <6auuc5F38s3s9U1@mid.uni-berlin.de> On Fri, 06 Jun 2008 23:57:03 -0700, s0suk3 wrote: > You can just split the path on `os.sep', which contains the path > separator of the platform on which Python is running: > > components = pathString.split(os.sep) Won't work for platforms with more than one path separator and if a separator is repeated. For example r'\foo\\bar/baz//spam.py' or: In [140]: os.path.split('foo//bar') Out[140]: ('foo', 'bar') In [141]: 'foo//bar'.split(os.sep) Out[141]: ['foo', '', 'bar'] Ciao, Marc 'BlackJack' Rintsch From usenet at technicalbloke.com Thu Jun 19 04:10:28 2008 From: usenet at technicalbloke.com (Roger Heathcote) Date: Thu, 19 Jun 2008 09:10:28 +0100 Subject: Combining music or video files? In-Reply-To: <02a1ba97$0$25051$c3e8da3@news.astraweb.com> References: <4855d5a5$0$11609$607ed4bc@cv.net> <1bydnYdof97ddsjVnZ2dnUVZ_uSdnZ2d@earthlink.com> <02a1ba97$0$25051$c3e8da3@news.astraweb.com> Message-ID: <3N6dnZKoI4fricfVnZ2dneKdnZydnZ2d@bt.com> John Salerno wrote: > "Dennis Lee Bieber" wrote in message > news:1bydnYdof97ddsjVnZ2dnUVZ_uSdnZ2d at earthlink.com... >> On Sun, 15 Jun 2008 22:53:19 -0400, John Salerno >> declaimed the following in comp.lang.python: >> Even the simplest format -> WAV, which is normally uncompressed >> audio samples, is wrapped in layers of informational packets. >> >> snip other stuff!!! > > Yikes! Then what I'm reading from your post (and others) is no, I can't do > it my way. ;) It *did* seem a little too easy, after all! > > I can't speak for video (and I'd imagine it's a factor more difficult) but it's really not that hard to concatenate audio in python. What you need to do... Import the right modules for the audio formats you want to read. Decide on a master output format, say CD quality - PCM 16bit 44.1Khz Stereo. Open a file for appending Read through each of your source files loading them into memory Get the sample rate and format Run the sample data through a function to convert it to the master output format* Squirt it to disk Finally take the resulting file, calculate a new header and munge the two together. Voila :) *I'm sure several modules have functions/methods for this but it wouldn't be very hard to roll your own either. Roger Heathcote http://www.technicalbloke.com From newsgroup.spamfilter at virtualinfinity.net Mon Jun 23 21:14:41 2008 From: newsgroup.spamfilter at virtualinfinity.net (Daniel Pitts) Date: Mon, 23 Jun 2008 18:14:41 -0700 Subject: MD5 hash for url and utf unicode converting to ascii In-Reply-To: References: Message-ID: <486066cc$0$20012$7836cce5@newsrazor.net> joe shoemaker wrote: > I would like to convert url into md5 hash. My question is that md5 > hash will create collision at 2^64. If you do long(value,16), where > value is the md5 hash string, would value returned from long(value, > 16) be unique as long as md5 hashed string is unique? when you move > md5 hashed string to long, where will the collision occur, at anything MD5's are not meant to be unique keys. They are designed to make it difficult to alter the original value and maintain the same hash. This prevents both errors and malevolent data tampering. Also note, I believe MD5 are typically 128 bits long, not 64, but the calculation for collision is more complicated than that. -- Daniel Pitts' Tech Blog: From alfasub000 at gmail.com Thu Jun 12 01:41:16 2008 From: alfasub000 at gmail.com (alfasub000 at gmail.com) Date: Wed, 11 Jun 2008 22:41:16 -0700 (PDT) Subject: catastrophic regexp, help! References: <26bda6a4-ad16-4b06-aff4-12e311ebaf81@59g2000hsb.googlegroups.com> Message-ID: On Jun 11, 11:07 pm, cirfu wrote: > On 11 Juni, 10:25, Chris wrote: > > > > > On Jun 11, 6:20 am, cirfu wrote: > > > > pat = re.compile("(\w* *)*") > > > this matches all sentences. > > > if fed the string "are you crazy? i am" it will return "are you > > > crazy". > > > > i want to find a in a big string a sentence containing Zlatan > > > Ibrahimovic and some other text. > > > ie return the first sentence containing the name Zlatan Ibrahimovic. > > > > patzln = re.compile("(\w* *)* zlatan ibrahimovic (\w* *)*") > > > should do this according to regexcoach but it seems to send my > > > computer into 100%CPU-power and not closable. > > > Maybe something like this would be of use... > > > def sentence_locator(s, sub): > > cnt = s.upper().count(sub.upper()) > > if not cnt: > > return None > > tmp = [] > > idx = -1 > > while cnt: > > idx = s.upper().find(sub.upper(), (idx+1)) > > a = -1 > > while True: > > b = s.find('.', (a+1), idx) > > if b == -1: > > b = s.find('.', idx) > > if b == -1: > > tmp.append(s[a+1:]) > > break > > tmp.append(s[a+1:b+1]) > > break > > a = b > > cnt -= 1 > > return tmp > > yes, seems very unpythonic though :) > must be a simpler way that isnt slow as hell. Why wouldn't you use character classes instead of groups? i.e: pat = re.compile(r'([ \w]*Zlatan Ibrahimivoc[ \w]*)') sentence = re.match(text).groups() As has been mentioned earlier, certain evil combinations of regular expressions and groups will cause python's regular expression engine to go (righteously) crazy as they require the internal state machine to branch out exponentially. From Caseyweb at gmail.com Thu Jun 5 07:48:08 2008 From: Caseyweb at gmail.com (Casey) Date: Thu, 5 Jun 2008 04:48:08 -0700 (PDT) Subject: Python and Harry Potter? References: <6aprloF38p4l7U1@mid.dfncis.de> Message-ID: Python fan??? Harry speaks Python fluently. We should all be so lucky! I'm told Harry is looking forward to Py3K and getting rid of all the old (hog)warts .... From ptmcg at austin.rr.com Sat Jun 14 14:48:27 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 14 Jun 2008 11:48:27 -0700 (PDT) Subject: Subclassing list, what special methods do this? References: <7ba7e964-2d34-4594-8cfc-79dbf904df18@f63g2000hsf.googlegroups.com> Message-ID: On Jun 13, 1:38?pm, Mike Kent wrote: > For Python 2.5 and new-style classes, what special method is called > for mylist[2:4] = seq and for del mylist[2:4] (given that mylist is a > list, and seq is some sequence)? > > I'm trying to subclass list, and I'm having trouble determining what > special methods I have to override in my class for the above two > operations. ?From my testing, it seems to be __setslice__ for both, > but the docs say __setslice__ and brethren are deprecated. ?I would > have thought that __setitem__ and __delitem__ would be what was > called, but again, my testing says otherwise. Or you could forget this "subclassing" stuff, and just implement __setitem__, __getitem__, __delitem__, __len__, and __iter__ in your own class, and not worry about what list does or doesn't do. You could have your class contain a list to implement with, and then delegate to it from your class's code. Overall, I think Python as a language favors composition/delegation over inheritance - c/d is so easy to do with __getattribute__, and inheritance is largely unnecessary since type/interface is not checked until runtime. Yet many O-O texts are written around C++ and Java's static type models, so we see a preponderance of patterns and conventional O-O wisdom recommending inheritance. For Python, it ain't necessarily so... -- Paul From deets at nospam.web.de Fri Jun 13 12:03:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 13 Jun 2008 18:03:53 +0200 Subject: Iterate creating variables? In-Reply-To: References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> <6bfhj5F3b47fmU1@mid.uni-berlin.de> <6bfj7bF3c3npoU1@mid.uni-berlin.de> Message-ID: <6bfk3fF3btpk3U1@mid.uni-berlin.de> > > Thank you, this is much closer to where I need to be... > > The issue is (and this is the part that you don't know, because I > didn't tell you!) is that I later need to call methods on > "self.checkbox1", for instance: > > self.checkbox1.GetValue() > > to determine if the box is checked or not. > > I should have included that piece in the initial problem description; > my apologies. Then translate the above to self.checkboxes[1].GetValue() The point of all this is the following: If you have a variable (even if not changing often, or being globally configured) number of objects, it's a good idea to keep them around in a list. Even if you need specific parameters for the checkboxes, it would most probably be better to do it like this checkbox_args = [ ("name", parameter, ...), ("other_name", other_parameter, ...), ] for parameters in checkbox_args: checkboxes.append(Checbbox(*parameters)) If you know on the other hand that you will have 10 checkboxes which have all a defined meaning, it might be better to use a meaningful name for them, like: self.create_backup = Checkbox(...) self.perform_authorization = Checkbox(...) From sjmachin at lexicon.net Fri Jun 6 19:27:18 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 6 Jun 2008 16:27:18 -0700 (PDT) Subject: File-writing not working in Windows? References: <80a7b951-591b-41a2-b76c-f97d75db0dad@25g2000hsx.googlegroups.com> Message-ID: <250e2658-4b9b-45ca-b8c6-56ae71b62726@v1g2000pra.googlegroups.com> On Jun 7, 1:18 am, tda... at gmail.com wrote: > All, > [code snipped] > > This code works PERFECTLY in Linux. Where I have a match in the file > I'm processing, it gets cut out from the start of the match until the > end of the match, and written to the temporary file in tempdir. > > It does not work in Windows. It does not create or write to the > temporary file AT ALL. It creates the tempdir directory with no > problem. > > Here's the kicker: it works perfectly in Windows if Windows is running > in VMware on a Linux host! (I assume that that's because VMware is > passing some call to the host.) > > Can anyone tell me what it is that I'm missing which would prevent the > file from being created on Windows natively? > > I'm sorry I can't provide any more of the code, and I know that that > will hamper your efforts in helping me, so I apologise up front. > > Assumptions: > You can assume self.checkbox25.GetValue() is always false for now, and > self.Info[x][0] contains a two character string like "00" or "09" or > "14". There is always a match in the fileTarget, so self.Info[x][2] > will always be true at some point, as will self.Info[x][4]. I am > cutting an HTML file at predetermined comment sections, and I have > control over the HTML files that are being cut. (So I can force the > file to match what I need it to match if necessary.) Assume nothing. Don't believe anyone who says "always". Insert some print statements and repr() calls to show what's actually there. > I hope however that it's something obvious that a Python guru here > will be able to spot and that this n00b is missing! *IF* the problem is in the code, it would be easier to spot if you had removed large chunks of indentation before posting. Less is more: change "if (foo == 2):" to "if foo == 2:", "foo == True" to "foo", and "foo == False" to "not foo". Browse http://www.python.org/dev/peps/pep-0008/ HTH, John From sjmachin at lexicon.net Sat Jun 21 19:40:29 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 21 Jun 2008 16:40:29 -0700 (PDT) Subject: My n00bie brain hurts after "Python setup.py install". References: <6a4560d6-0ec5-4a2b-9c93-fa1febe23f07@p25g2000pri.googlegroups.com> Message-ID: <8d006140-582d-44d2-be15-112bb56eea68@f24g2000prh.googlegroups.com> On Jun 22, 9:05 am, bsag... at gmail.com wrote: > I downloaded Mark Pilgrims's feedparser.py in a zipfile to my Windows > machine, unzipped it and tried to install it to no avail. > > Here is the result => > > C:\>python c:\scripts\feedparser-4.1\setup.py install The convention is to run setup.py from the current directory, unless instructed otherwise; what did the package's readme say? Try: cd \scripts\feedparser-4.1 python setup.py install > running install > running build > running build_py > file feedparser.py (for module feedparser) not found > running install_lib > warning: install_lib: 'build\lib' does not exist -- no Python modules > to install > running install_egg_info > Writing C:\Python25\Lib\site-packages\feedparser-4.1-py2.5.egg-info > > WTF? The file feedparser.py did exist in the same place as setup.py. > Even if it works, what exactly does this setup.py do for me? If I just > manually place feedparser.py in my Python site-packages file it works > fine. In general, a setup.py install may do lots of things besides coping 1 file. Manually placing files in site-packages is not a good habit to get into. > As for that egg-info file, I googled "python eggs" and now I am > really confused. Eggs are part of a new experimental package distribution scheme. Don't worry about it. Cheers, John From pecora at anvil.nrl.navy.mil Mon Jun 2 11:05:43 2008 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Mon, 02 Jun 2008 17:05:43 +0200 Subject: php vs python References: Message-ID: In article , Ethan Furman wrote: > Jerry Stuckle wrote: > > > > > As I've said before - good programmers can write good code in any > > language. > > > > So... an eloquent speaker of English is also an eloquent speaker of > Spanish/French/German? Oh, Bull. Computer languages are so narrow they are more like dialects of a single language. If you know English you can learn to speak to a Brit, Scot, or Aussie. That's more like it...if you really want to stretch the definition of a language. And it is a stretch. Anyone speak C? Sheeze. -- -- Lou Pecora From pfreixes at gmail.com Thu Jun 19 04:14:15 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Thu, 19 Jun 2008 10:14:15 +0200 Subject: please critique my thread code In-Reply-To: <9ZWdnVMfvdwglMfVnZ2dnUVZ8q_inZ2d@bt.com> References: <222a1935-20dd-44a0-bc42-71a25be96d30@79g2000hsk.googlegroups.com> <9ZWdnVMfvdwglMfVnZ2dnUVZ8q_inZ2d@bt.com> Message-ID: <207312b70806190114x2802263s7c8397e300535aac@mail.gmail.com> > > MRAB wrote: > > Erm, shurely the bottleneck will be bandwidth not processor/memory?* If it > isn't then - yes, you run the risk of actually DOSing their servers! > > Your mac will run thousands of threads comfortably but your router may not > handle the thousands of TCP/IP connections you throw at it very well, > especially if it is a domestic model, and sure as hell sourceforge aren't > going to want more than a handfull of concurrent connections from you. > > Typical sourceforge page ~ 30K > Project pages to read = 240000 > > = ~6.8 Gigabytes The best path for avoid congestion network problem and probably "DOS attack" it's use a equilibrate number of parallel connection with a number of threads. One router can handle hundred connections and Mac thread implementation may be also - with a lot of memory or stack size profiling. If you run hundred threads you will be fight with OS, Webserver, Router and network starvation problems. I believe use a 64 number of threads it's ok, but probably all 64 thread connections will be performance for the same sourceforge web server - balancing algorithm - and may be that this week up suspicion to the admin. May be, you can use httplib [1] for do a persistent connection and reuse same connection for same thread. [1] http://www.python.org/doc/2.4.2/lib/httplib-examples.html -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From Michael.Coll-Barth at VerizonWireless.com Thu Jun 5 14:37:19 2008 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Thu, 5 Jun 2008 14:37:19 -0400 Subject: Please unregister this mail-address out of mailing-list. In-Reply-To: References: Message-ID: <20080605185002.46A9F1E401A@bag.python.org> > -----Original Message----- > From: Hank @ITGroup > I am writing this letter to unsubscribe this mail-address from python > mail-list. > -- > http://mail.python.org/mailman/listinfo/python-list > No problem, Hank. You will be officially off of this 'mail-list' after a visit to this site; http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From sjmachin at lexicon.net Fri Jun 20 08:12:53 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 20 Jun 2008 05:12:53 -0700 (PDT) Subject: Pyparsing performance boost using Python 2.6b1 References: Message-ID: On Jun 19, 8:40 pm, Paul McGuire wrote: > I just ran my pyparsing unit tests with the latest Python 2.6b1 > (labeled internally as Python 2.6a3 - ???), Hi, Paul. If it says 2.6a3, that's what it is. Look at the thread of replies to Barry Warsaw's announcement of 2.6b1 ... [from memory] there was a delay expected before MvL would make a Windows msi available, and in the meantime the download page would point to "the alpha version". Cheers, John From aishwaryagroup at gmail.com Wed Jun 11 01:16:31 2008 From: aishwaryagroup at gmail.com (AISHWARYA) Date: Tue, 10 Jun 2008 22:16:31 -0700 (PDT) Subject: MANAGEMENT SOFTWARE Message-ID: ******************************************************* http://maintanancemanagementsoftwareservises.blogspot.com From kay.schluehr at gmx.net Tue Jun 3 13:53:10 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 3 Jun 2008 10:53:10 -0700 (PDT) Subject: parser recommendation References: <686de663-94d2-4e8b-b079-197793d0a8cc@2g2000hsn.googlegroups.com> Message-ID: <68d0244e-d0e3-4495-b11c-9a90e38260f1@d1g2000hsg.googlegroups.com> On 3 Jun., 19:34, "Filipe Fernandes" wrote: > # The current implementation is only somewhat object-oriented. The > # LR parser itself is defined in terms of an object (which allows multiple > # parsers to co-exist). However, most of the variables used during table > # construction are defined in terms of global variables. Users shouldn't > # notice unless they are trying to define multiple parsers at the same > # time using threads (in which case they should have their head examined). > > Now, I'm invariably going to have to use threads... I'm not exactly > sure what the author is alluding to, but my guess is that to overcome > this limitation I need to acquire a thread lock first before > "defining/creating" a parser object before I can use it? Nope. It just says that the parser-table construction itself relies on global state. But you will most likely build your parser offline in a separate run. From wuwei23 at gmail.com Thu Jun 5 12:36:17 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 5 Jun 2008 09:36:17 -0700 (PDT) Subject: Import removing first module component References: <75481b47-87ec-4a84-8063-7abbdb286d62@u6g2000prc.googlegroups.com> Message-ID: On Jun 6, 1:44 am, koblas wrote: > Another person pointed out that I should check on the __init__.py and > make sure lmtp is defined in the __all__ block. I didn't have an > __init__.py at that level of the tree, which must have been causing > problems, but clearly I don't understand the full inheritance of > __init__.py and sub-directories. Heya, If you're not sure about packages, it's covered in the python docs here: http://docs.python.org/tut/node8.html#SECTION008400000000000000000 An __all__ variable doesn't have to be defined, the __init__.py can be empty, as it's the presence of that file that informs python that the folder is a package. The example in the docs should help you here. From alex.m.gusarov at gmail.com Fri Jun 20 10:39:19 2008 From: alex.m.gusarov at gmail.com (Alex Gusarov) Date: Fri, 20 Jun 2008 21:39:19 +0700 Subject: py2exe & application add-ons In-Reply-To: <11cda8d4-1359-42cb-8f8d-16dd57eb0442@z16g2000prn.googlegroups.com> References: <11cda8d4-1359-42cb-8f8d-16dd57eb0442@z16g2000prn.googlegroups.com> Message-ID: Thanks everybody, yes, I use 'exec' for files. And "freeze" modules - thanks too, I almost forgot this opportunity. -- Best regards, Alex Gusarov From geoff.bache at jeppesen.com Wed Jun 25 04:49:04 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Wed, 25 Jun 2008 01:49:04 -0700 (PDT) Subject: Terminating processes on Windows (handles and IDs) References: <98b73a28-fa07-4eac-8f3c-aec65aa819fe@k37g2000hsf.googlegroups.com> <36a78f0c-cbd4-45cd-a69f-44566f47b15f@b1g2000hsg.googlegroups.com> Message-ID: <20fee08e-b75d-4d4f-a4c9-b329fdc5d07c@t54g2000hsg.googlegroups.com> Thanks for the help Tim! Good to see this is being sorted in Python at last, although it'll be some time before I can use only Python 2.6 I suspect... I'm making use of _handle now and it works - most of the time. The remaining issues are probably PyGTK problems rather than python ones though, and hence off topic here. Regards, Geoff From tdahsu at gmail.com Sun Jun 8 10:29:48 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Sun, 8 Jun 2008 07:29:48 -0700 (PDT) Subject: File-writing not working in Windows? References: <80a7b951-591b-41a2-b76c-f97d75db0dad@25g2000hsx.googlegroups.com> <5c4313fb-3672-4b03-9d62-58fd6e3a76bd@w34g2000prm.googlegroups.com> Message-ID: On Jun 8, 4:11?am, Lie wrote: > On Jun 6, 10:18?pm, tda... at gmail.com wrote: > > > > > > > All, > > > I have the following code: > > ? ? ? ? ? ?for fileTarget in dircache.listdir("directory"): > > ? ? ? ? ? ? ? ? (dirName, fileName) = os.path.split(fileTarget) > > ? ? ? ? ? ? ? ? f = open(fileTarget).readlines() > > ? ? ? ? ? ? ? ? copying = False > > ? ? ? ? ? ? ? ? for i in range(len(f)): > > ? ? ? ? ? ? ? ? ? ? for x in range (0,24,1): > > ? ? ? ? ? ? ? ? ? ? ? ? if (re.search(self.Info[x][3], f[i])): > > #If we have a match for our start of section... > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (self.Info[x][2] == True): > > #And it's a section we care about... > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? copying = > > True ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?#Let's start copying the lines out > > to the temporary file... > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (os.name == "posix"): > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (self.checkbox25.GetValue() == > > False): > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? tempfileName = "tempdir/" + > > self.Info[x][0] + "_tmp_" + fileName + ".txt" > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? tempfileName = > > self.textctrl07.GetValue() + "/" + self.Info[x][0] + "_xyz.txt" > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (self.checkbox25.GetValue() == > > False): > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? tempfileName = "tempdir\\" + > > self.Info[x][0] + "_tmp_" + fileName + ".txt" > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? tempfileName = > > self.textctrl07.GetValue() + "\\" + self.Info[x][0] + "_xyz.txt" > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? copying = False > > ? ? ? ? ? ? ? ? ? ? ? ? if (re.search(self.Info[x][4], f[i])): > > #Now we've matched the end of our section... > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? copying = > > False ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #So let's stop copying out to > > the temporary file... > > ? ? ? ? ? ? ? ? ? ? if (copying == True): > > ? ? ? ? ? ? ? ? ? ? ? ? g = open(tempfileName, > > 'a') ? ? ? ? ? ? ? ? ? ? #Open that file in append mode... > > > g.write(f[i]) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #Write the line... > > ? ? ? ? ? ? ? ? ? ? ? ? g.close() > > > This code works PERFECTLY in Linux. ?Where I have a match in the file > > I'm processing, it gets cut out from the start of the match until the > > end of the match, and written to the temporary file in tempdir. > > > It does not work in Windows. ?It does not create or write to the > > temporary file AT ALL. ?It creates the tempdir directory with no > > problem. > > > Here's the kicker: it works perfectly in Windows if Windows is running > > in VMware on a Linux host! ?(I assume that that's because VMware is > > passing some call to the host.) > > > Can anyone tell me what it is that I'm missing which would prevent the > > file from being created on Windows natively? > > > I'm sorry I can't provide any more of the code, and I know that that > > will hamper your efforts in helping me, so I apologise up front. > > > Assumptions: > > You can assume self.checkbox25.GetValue() is always false for now, and > > self.Info[x][0] contains a two character string like "00" or "09" or > > "14". ?There is always a match in the fileTarget, so self.Info[x][2] > > will always be true at some point, as will self.Info[x][4]. ?I am > > cutting an HTML file at predetermined comment sections, and I have > > control over the HTML files that are being cut. ?(So I can force the > > file to match what I need it to match if necessary.) > > > I hope however that it's something obvious that a Python guru here > > will be able to spot and that this n00b is missing! > > > Thanks! > > Well, not to be rude, but that's quite a spaghetti code, some of the > guilt, however, was for the mailing program that cuts 80+ lines. > Others was the use of things like "for i in range(len(f)):" or "if (a > == True)". > > Try checking whether you're trying to write to a path like r"\dir > \file.txt" or r"dir\file.txt" instead of r"C:\dir\file.txt" in > Windows. > > If that doesn't solve the problem, tell us a few things: > - Any error messages? Or simply nothing is written out? > - Has a blank file get created?- Hide quoted text - > > - Show quoted text - Thanks to everyone for the help. I really do appreciate your suggestions and time; again I apologise for not being able to give you all the code to diagnose. I understand that it made this more difficult and thank you for the input! The error was not with the script. The error was with the HTML that was being parsed! It's the last thing I considered to check, and where I should have started. John, thank you for the link to the style guide. I can see its use and will make my code conform to the standards. Thanks again to everyone! From zephyrfalcon!NO_SPAM! at gmail.com Sat Jun 7 12:58:39 2008 From: zephyrfalcon!NO_SPAM! at gmail.com (Hans Nowak) Date: Sat, 07 Jun 2008 12:58:39 -0400 Subject: Dynamically naming objects. In-Reply-To: <3d2a85b2-255d-4e93-8cfb-e2772f57b69a@u6g2000prc.googlegroups.com> References: <8a99c3fa-1eeb-49b3-a714-b6063ec1daab@d19g2000prm.googlegroups.com> <3d2a85b2-255d-4e93-8cfb-e2772f57b69a@u6g2000prc.googlegroups.com> Message-ID: <15z2k.1218$LL4.885@bignews7.bellsouth.net> Kalibr wrote: > On Jun 7, 1:20 pm, Hans Nowak wrote: >> Kalibr wrote: >>> I've been developing a small script to fiddle with classes, and came >>> accross the following problem. Assuming I get some user input asking >>> for a number, how would I spawn 'n' objects from a class? >>> i.e. I have a class class 'user' and I don't know how many of them I >>> want to spawn. >>> Any ideas? >> Sure. This will give you a list of n instances of user: >> >> [user() for i in range(n)] >> >> Of course, you could also use a good old for loop: >> >> for i in range(n): >> u = user() >> ...do something with u... >> >> Hope this helps! >> >> -- >> Hans Nowak (zephyrfalcon at gmail dot com)http://4.flowsnake.org/ > > whoops, replied to author.... > > What I wanted to ask before was won't 'u' be overwritten with a new > object each time the loop ticks over? Yes, so you have to store it somewhere, if you want to keep the object around. The list comprehension mentioned above stores all the objects in a list, after which they can be accessed at will via indexing. > what I want to do is have, say 5 users in a game, so I'd have to spawn > 5 objects. I can't do that because I have'nt hardcoded any object > names for them. > > or does it somehow work? how would I address them if they all have the > name 'u'? users = [user() for i in range(n)] # use: users[0], users[1], etc -- Hans Nowak (zephyrfalcon at gmail dot com) http://4.flowsnake.org/ From shahvishang at gmail.com Fri Jun 13 14:15:21 2008 From: shahvishang at gmail.com (Vishang Shah) Date: Fri, 13 Jun 2008 11:15:21 -0700 (PDT) Subject: Python Socket programming References: <655455.29695.qm@web7907.mail.in.yahoo.com> Message-ID: <3ce3356a-2640-475f-a92d-f66fd56fb585@d19g2000prm.googlegroups.com> there is this good link for explanation on how sockets work, http://www.tutorialgrub.com/tutorials/Python/Development/Socket-Programming-HOWTO_325.html From secretofmcouple at gmail.com Sat Jun 7 02:29:52 2008 From: secretofmcouple at gmail.com (Happy Married Couple) Date: Fri, 6 Jun 2008 23:29:52 -0700 (PDT) Subject: SECRETS OF THE MOST HAPPY LOVED AND BLISSFUL COUPLES IN THE WORLD Message-ID: <89ac9588-8635-4b42-9332-41ee42cb369f@j1g2000prb.googlegroups.com> You're about to discover the 'magic ingredients' that make some couples live happy and blissful marriages for DECADES and how you can too. Dear Friend, My name is Michael Webb. I DON'T have a doctorate in counseling, marriage studies and I DON'T host a radio call in show? but I DO have what most other relationship "experts? don?t have?a blissful marriage. Which is why hundreds of men and women ask for my relationship advice and have done so for 12 years now. In fact, this may surprise you but my wife Athena and I have never even had a fight in our 17 years of marriage. Yes, it's true. Of course I know ?this sounds bizarre, even impossible but in a moment I'll explain exactly how this was possible. And more importantly, how it's possible for you. You see, I grew up in a family with 6 sisters. And in my lifetime I've seen them abused by the various men in their lives. Even my mother has the scars from two unsuccessful marriages. After witnessing this for too long, I decided be the sort of husband my mom and sisters had dreamed of but never had. I studied relationships for a long time, took good notes on what things blissful couples do differently than those who have the typical relationship full of ups and downs. (By the way, nearly all "relationship" books focus on what couples are doing wrong. I'll let you know what couples are doing right.) Several years later, I released my first book, The Romantic's Guide, which went on to become a national bestseller. It was released in February 2000 and is already in its 6th printing. From there, things started to go crazy as the media started hounding me for interviews left, right and center. To date, I've published 16 books helping both women and men with almost every imaginable relationships and marriage problem there is. Please visit our website for further details:- http://tubeurl.com/14wfhn From tjreedy at udel.edu Mon Jun 23 02:19:55 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Jun 2008 02:19:55 -0400 Subject: -1/2 In-Reply-To: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> References: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> Message-ID: Serve Lau wrote: > What is the expected result of -1/2 in python? Python 3.0b1 (r30b1:64403M, Jun 19 2008, 14:56:09) [MSC v.1500 32 bit (Intel)] n win32 Type "help", "copyright", "credits" or "license" for more information. >>> -1/2 -0.5 as expected ;-) -1//2 is as Gary Herron specified from the manual, for reasons posted here several times and which should be in the FAQ From gh at ghaering.de Thu Jun 26 07:03:27 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 26 Jun 2008 13:03:27 +0200 Subject: Urllib(1/2) how to open multiple client sockets? In-Reply-To: References: Message-ID: ShashiGowda wrote: > Hey there i made a script to download all images from a web site but > it runs damn slow though I have a lot of bandwidth waiting to be used > please tell me a way to use urllib to open many connections to the > server to download many pics simultaneously.... Any off question > suggestions are also ok... "Simultaneously" means using multiple threads (or processes). You could create worker threads that do the downloading (use the threading module for this) and communicate with them via a queue (use the Queue module for this). For example the main thread would then do the HTML parsing and push the image URLs to the worker threads via the queue. Each worker thread then polls the queue and downloads the images it gets. One issue is how to terminate the multithreaded application. A simple approach is to use a sentinel value to push to the queue to signal the worker threads to quit. Something like "QUIT" will do. Be sure to push at least as many sentinel values as you have worker threads, then. -- Gerhard From mccredie at gmail.com Tue Jun 3 16:20:14 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 3 Jun 2008 13:20:14 -0700 (PDT) Subject: Creating object in function doesn't seem to create a new object. References: <0d321eb1-8bc3-4ae4-893f-9ad137d9eca4@25g2000hsx.googlegroups.com> Message-ID: <9fada70b-8f23-468e-86f1-00d8d43f6b4c@26g2000hsk.googlegroups.com> > I thought that when I wrote fc1 = FlightCondition() in the function it > would create a new FlightCondition object which would be passed back > every time. > Instead it seems to re-reference the old version and continue to add > to it. That is exactly what is happening. You have created a class with two _class_ attributes that are lists. These attributes are attached to the _class_ not the instance that was created. You are simply mutating the list that is attached to the class. You really want to do something like this: class FlightCondition(object): def __init__(self): self.lsf = [0,'Low Speed Flare'] self.vto = [0,'Vertical Take-Off'] Other than that, its hard to tell what you are actually trying to do, but likely get_flight_condition could become a method of the FlightCondition class. Matt From rdm at rcblue.com Wed Jun 4 14:48:24 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 04 Jun 2008 11:48:24 -0700 Subject: Books for programmers In-Reply-To: <32791EDC-1033-4B65-BFB5-DF1CF71EF20D@comhem.se> References: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> <32791EDC-1033-4B65-BFB5-DF1CF71EF20D@comhem.se> Message-ID: <20080604184837.505CB1E4002@bag.python.org> Do not neglect the 2008 book, "Object-Oriented Programming in Python", by Goldwasser and Letscher. Dick Moores From sjmachin at lexicon.net Sat Jun 7 20:01:33 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 7 Jun 2008 17:01:33 -0700 (PDT) Subject: Need help porting Perl function References: <379fb630-5a4c-44e6-920e-3de7acd6bfd4@z24g2000prf.googlegroups.com> <8bb0b0ce-e840-416f-b9c1-4092fd5fa771@56g2000hsm.googlegroups.com> Message-ID: <7248c81b-0ff9-45f5-acb5-63a8b2d41817@f24g2000prh.googlegroups.com> On Jun 8, 8:17 am, eat... at gmail.com wrote: > On Jun 7, 5:56 pm, John Machin wrote: > > > > > On Jun 8, 6:05 am, eat... at gmail.com wrote: > > > > On Jun 7, 2:42 pm, "Daniel Fetchinson" > > > wrote: > > > > > > Hi. I'd like to port a Perl function that does something I don't > > > > > know how to do in Python. (In fact, it may even be something that > > > > > is distinctly un-Pythonic!) > > > > > > The original Perl function takes a reference to an array, removes > > > > > from this array all the elements that satisfy a particular criterion, > > > > > and returns the list consisting of the removed elements. Hence > > > > > this function returns a value *and* has a major side effect, namely > > > > > the target array of the original argument will be modified (this > > > > > is the part I suspect may be un-Pythonic). > > > > > > Can a Python function achieve the same effect? If not, how would > > > > > one code a similar functionality in Python? Basically the problem > > > > > is to split one list into two according to some criterion. > > > > > This function will take a list of integers and modify it in place such > > > > that it removes even integers. The removed integers are returned as a > > > > new list (disclaimer: I'm 100% sure it can be done better, more > > > > optimized, etc, etc): > > > > > def mod( alist ): > > > > old = alist[:] > > > > ret = [ ] > > > > for i in old: > > > > if i % 2 == 0: > > > > ret.append( alist.pop( alist.index( i ) ) ) > > > > > return ret > > > > > x = range(10,20) > > > > > print x > > > > r = mod( x ) > > > > print r > > > > print x > > > > > HTH, > > > > Daniel > > > > -- > > > > Psss, psss, put it down! -http://www.cafepress.com/putitdown > > > > def mod( alist ): > > > return [ alist.pop( alist.index( x ) ) for x in alist if x % 2 == > > > 0 ] > > > > alist = range(10,20) > > > blist = mod( alist ) > > > > print alist > > > print blist > > > > The same thing with list comprehensions. > > > Not the same. The original responder was careful not to iterate over > > the list which he was mutating. > > > >>> def mod(alist): > > > ... return [alist.pop(alist.index(x)) for x in alist if x % 2 == 0] > > ...>>> a = range(10) > > >>> print mod(a), a > > > [0, 2, 4, 6, 8] [1, 3, 5, 7, 9]>>> a = [2,2,2,2,2,2,2,2] > > >>> print mod(a), a > > > [2, 2, 2, 2] [2, 2, 2, 2] > > # should be [2, 2, 2, 2, 2, 2, 2, 2] [] > > Alas, it appears my understanding of list comprehensions is > significantly less comprehensive than I thought =) It's nothing to do with list comprehensions, which are syntactical sugar for traditional loops. You could rewrite your list comprehension in the traditional manner: def mod(alist): ret = [] for x in alist: if x % 2 == 0: ret.append(alist.pop(alist.index(x)) return ret and it would still fail for the same reason: mutating the list over which you are iterating. At the expense of even more time and memory you can do an easy fix: change 'for x in alist' to 'for x in alist[:]' so that you are iterating over a copy. Alternatively, go back to basics: >>> def modr(alist): ... ret = [] ... for i in xrange(len(alist) - 1, -1, -1): ... if alist[i] % 2 == 0: ... ret.append(alist[i]) ... del alist[i] ... return ret ... >>> a = [2,2,2,2,2,2,2,2,2] >>> print modr(a), a [2, 2, 2, 2, 2, 2, 2, 2, 2] [] >>> HTH, John From semanticist at gmail.com Sat Jun 14 01:15:52 2008 From: semanticist at gmail.com (Miles) Date: Sat, 14 Jun 2008 01:15:52 -0400 Subject: struct unpack issue In-Reply-To: <20080614012734.30329619.ioceanio@gmail.com> References: <20080614012734.30329619.ioceanio@gmail.com> Message-ID: On Fri, Jun 13, 2008 at 9:27 PM, Ping Zhao wrote: > However, when I tried to rewrite them in short: > > header = struct.unpack('2s1i', self.__read(src, 6)) > ... > It was weired that the required argument length increased to 8. This is an alignment issue; if you don't specify a structure format character, the struct module acts like the data is laid out in memory as a C compiler would do it. http://en.wikipedia.org/wiki/Data_structure_alignment http://docs.python.org/lib/module-struct.html Specifying little-endian byte order will force the data to be packed (unaligned), and will also make your code more portable: struct.unpack('<2s1i', ...) -Miles From sturlamolden at yahoo.no Tue Jun 3 14:04:54 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 3 Jun 2008 11:04:54 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> Message-ID: <2930ad39-a3ef-49fa-9e37-26ada87f2d95@m44g2000hsc.googlegroups.com> On Jun 2, 12:40 pm, Antoon Pardon wrote: > I think you completed missed the point. > > This is just a proof of concept thing. In a real example there would > of course no Set en Get methods but just methods that in the course > of their execution would access or update the hidden attributes I have to agree with Banks here, you have not provided an example of data hiding. It does not discriminate between attribute access from within and from outside the class. You just assume that the attribute named 'hidden' will be left alone. Also naming it hidden is stupid as it is visible. What you need is a mechanism that will thrown an exception whenever an attribue is accessed from outside the class, but not from inside. The mechanism must also be impossible to override with additional code. If Ada is what you want, Ada is what you should use. From Scott.Daniels at Acm.Org Sun Jun 29 17:40:44 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 29 Jun 2008 14:40:44 -0700 Subject: list extension ? In-Reply-To: References: Message-ID: Stef Mientki wrote: ... (approximately, I PEP-8'ed it a bit) ... > class tGrid_List(list): > def __init__(self, value=[]): > list.__init__(self, value) > # and with this new list component, I can add new attributes on the fly > a = tGrid_list([2, 3]) > a.New_Attribute = 'some text' > > # I'm not allowed to this with the standard list > Can someone explain this different behavior ? Yes, you did not add a __slots__ member, so the object will have a __dict__ attribute. The __slots__ stuff is a storage optimization for frequently used data types (not worth it if you don't plan to have more than several thousand at any one time). Lists (for that matter most Python builtin types) get used a lot, so they have that built in. You can observe that even on the most trivial extensions: class AttributableInt(int): pass class AttributeFreeInt(int): __slots__ = () --Scott David Daniels Scott.Daniels at Acm.Org From gh at ghaering.de Thu Jun 12 11:14:34 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 12 Jun 2008 17:14:34 +0200 Subject: Counting things fast - was Re: Summing a 2D list In-Reply-To: References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> Message-ID: Aidan wrote: > does this work for you? > > users = [1,1,1,2,2,3,4,4,4] > score = [0,1,5,3,1,2,3,3,2] > > d = dict() > > for u,s in zip(users,score): > if d.has_key(u): > d[u] += s > else: > d[u] = s > > for key in d.keys(): > print 'user: %d\nscore: %d\n' % (key,d[key]) I've recently had the very same problem and needed to optimize for the best solution. I've tried quite a few, including: 1) using a dictionary with a default value d = collections.defaultdict(lambda: 0) d[key] += value 2) Trying out if avoiding object allocation is worth the effort. Using Cython: cdef class Counter: cdef int _counter def __init__(self): self._counter = 0 def inc(self): self._counter += 1 def __int__(self): return self._counter def __iadd__(self, operand): self._counter += 1 return self And no, this was *not* faster than the final solution. This counter class, which is basically a mutable int, is exactly as fast as just using this one (final solution) - tada! counter = {} try: counter[key] += 1 except KeyError: counter[key] = 1 Using psyco makes this a bit faster still. psyco can't optimize defaultdict or my custom Counter class, though. -- Gerhard From norseman at hughes.net Wed Jun 25 17:00:41 2008 From: norseman at hughes.net (norseman) Date: Wed, 25 Jun 2008 14:00:41 -0700 Subject: reading from list with paths In-Reply-To: <6c1ed580-259a-4df2-b389-ecf38296a138@25g2000hsx.googlegroups.com> References: <6c1ed580-259a-4df2-b389-ecf38296a138@25g2000hsx.googlegroups.com> Message-ID: <4862B1F9.7030501@hughes.net> antar2 wrote: > Hello, > > I would like to read and print files, of which the complete filepaths > are > mentioned in another textfile. In this textfile (list.txt) are for > example the following paths: > > /data/chorec/chorec-nieuw/s01/S01C001M1/S01C001M1_1LG_f01.TextGrid > /data/chorec/chorec-nieuw/s01/S01C001M1/ > S01C001M1_1LGPseudo_f01.TextGrid > /data/chorec/chorec-nieuw/s01/S01C001M1/S01C001M1_AVI1_f01.TextGrid > > I know how to open and read one file in my current directory, > but after trying to find this out my self, I give up... > > I already got one answer for this question, but it did not work > > Thanks a lot > > Antar2 > > -- > http://mail.python.org/mailman/listinfo/python-list > > > --------------------------------- I think what you want is more like: contents of a file named printthem.py ..... import os p = open('list.txt') for vpath in p: for f in os.listdir(vpath): print '\n\tContents of:',vpath+'/'+f f = open(vpath+'/'+f) print f.read() f.close() print '\n\t\t\t\tEND OF FILE\x0C' p.close() print "All Done. Is there any paper left?" ..... usage: python printthem.py >/dev/lp0 Unix python printthem.py > prn: Microsoft On Microsoft use '\\' in place of '/' following each vpath above The \x0C is Ctrl-L aka: ff or FormFeed norseman From siona at chiark.greenend.org.uk Tue Jun 17 06:02:19 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 17 Jun 2008 11:02:19 +0100 (BST) Subject: 'string'.strip(chars)-like function that removes from the middle? References: <48569B9E.6030206@admailinc.com> <200806161839.13647.omer@no-log.org> Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: >Terry Reedy wrote: >> >>> 'abcde'.translate(str.maketrans('','','bcd')) >> 'ae' >You should mention that you are using Python 3.0 ;) >The 2.5 equivalent would be > >>>> u"abcde".translate(dict.fromkeys(map(ord, u"bcd"))) >u'ae' Only if you're using Unicode: >>> 'abcde'.translate(string.maketrans('',''), 'bcd') 'ae' >>> sys.version_info (2, 4, 4, 'final', 0) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From cokofreedom at gmail.com Fri Jun 6 03:03:00 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Fri, 6 Jun 2008 00:03:00 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> <4847d203$0$32733$426a74cc@news.free.fr> <87lk1jzgri.fsf@mulj.homelinux.net> <39a7805f-6590-4505-bfa2-0735090d553b@t12g2000prg.googlegroups.com> Message-ID: Someone asked about Java; class FieldTest { public String publicString = "Foobar"; private String privateString = "Hello, World!"; } import java.lang.reflect.Field; public class Test4 { public static void main(String args[]) { final Field fields[] = FieldTest.class.getDeclaredFields(); for (int i = 0; i < fields.length; ++i) { System.out.println("Field: " + fields[i]); } } } OUTPUT >>>> Field: public java.lang.String FieldTest.publicString Field: private java.lang.String FieldTest.privateString And to edit it; import java.lang.reflect.Field; public class Test7 { public static void main(String args[]) throws Exception { final Field fields[] = FieldTest.class.getDeclaredFields(); for (int i = 0; i < fields.length; ++i) { if ("privateString".equals(fields[i].getName())) { FieldTest fieldTest = new FieldTest(); Field f = fields[i]; f.setAccessible(true); System.out.println(f.get(fieldTest)); f.set(fieldTest, "Modified Field"); System.out.println(f.get(fieldTest)); break; } } } } OUTPUT >>>> Hello, World! Modified Field Enjoy. From kenobi at gmail.com Tue Jun 3 09:30:06 2008 From: kenobi at gmail.com (Rick Kwan) Date: Tue, 3 Jun 2008 06:30:06 -0700 (PDT) Subject: Books for programmers References: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> Message-ID: <4a32fae8-c8d0-40a5-a6bd-b55f534d2d36@m73g2000hsh.googlegroups.com> On Jun 3, 12:22 am, V wrote: > I'm a C++, Java and C programmer, and I'm searching for a (preferably > printed) book that teaches me the "Python idioms", i.e. the "Python > way" of doing something. > > Ideally, I'm searching for a book like "Effective C++" or "Effective > Java", that does not lose time teaching what is a class, or a > function, or a loop, but that enters into details and describes not > only the "how", but also the "why". I like "Core Python Programming", 2nd ed., by Wesley Chun. After a couple of years of reasonably intense learn-on-my-own Python via "Learning Python" by Mark Lutz, and other resources, I was shocked how much I didn't know about Python when I picked up Chun's book. It's pretty thick (1100 pages?) and covers a lot of basic stuff, but that can be skimmed pretty quickly. Two large reasons it is so thick: (1) lots of annotated examples; (2) pretty thorough tables on language features, some of which I didn't pick up going through docs.python.com. (Full disclosure: I joined a group of Pythonistas and got to review the 2nd edition book before it went to press; so a few of my corrections made it into print. But really, I was blown away by how much I picked up in the process.) From george.sakkis at gmail.com Thu Jun 5 11:38:26 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 5 Jun 2008 08:38:26 -0700 (PDT) Subject: Tuples part 2 References: <6d3e6d40-63a6-40d1-8ea4-5ddf40238d8d@m44g2000hsc.googlegroups.com> <99bc30fb-532a-4c4f-9f5e-e7a18c28d2a5@z72g2000hsb.googlegroups.com> <0ecaaa47-3ad4-4f67-9d48-94d5d1951bc6@y21g2000hsf.googlegroups.com> Message-ID: On Jun 5, 11:21 am, Ivan Illarionov wrote: > On 5 ???, 18:56, Ivan Illarionov wrote: > > > > > On 5 ???, 18:19, "victor.hera... at gmail.com" > > wrote: > > > > On Jun 5, 3:49 pm, Ivan Illarionov wrote: > > > > > On 5 ???, 01:57, "victor.hera... at gmail.com" > > > > wrote: > > > > > > Hi Everyone, > > > > > > i have another question. What if i wanted to make n tuples, each with > > > > > a list of coordinates. For example : > > > > > > coords = list() > > > > > for h in xrange(1,11,1): > > > > > for i in xrange(1, 5, 1) : > > > > > for j in xrange(1, 5, 1) : > > > > > for k in xrange(1,2,1) : > > > > > coords.append((i,j,k)) > > > > > lista+str(h)= tuple coords > > > > > print tuple(coords) > > > > > > so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do > > > > > it the way i show you above but it is not working properly. I wish you > > > > > could help me with that. Thanks again, > > > > >>> from itertools import repeat, izip > > > > >>> coords = tuple((i,j,k) for i in xrange(1,5) for j in xrange(1,5) for k in xrange(1,2)) > > > > >>> locals().update(("tuple%s" % i, coord) for i, coord in izip(xrange(1,11), repeat(coords))) > > > > >>> tuple1 > > > > > ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (2, 1, 1), (2, 2, 1), (2, > > > > 3, 1), (2 > > > > , 4, 1), (3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1), (4, 1, 1), (4, 2, > > > > 1), (4, 3 > > > > , 1), (4, 4, 1)) > > > > > Does this help? > > > > > But I don't understand why you need this? > > > > > Ivan > > > > Hi, > > > > What i need is, for example: > > > > tuple 1=((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)) > > > > tuple 2=((2, 1, 1), (2, 2, 1), (2, 3, 1), (2, 4, 1)) > > > > tuple 3=((3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1)) > > > > and so on. Please help me and sorry for not taking the time to post my > > > questions properly. > > > > Victor > > > Or even so: > > > locals().update(("tuple_%s" % i, tuple((i,j,k) for j in range(1,5) for > > k in range(1,2))) for i in range(1,5)) > > > Ivan > > Tried to make it readable: > > def iter_coords(i): > for j in xrange(1,5): > for k in xrange(1,2): > yield i, j, k > > def iter_vars(): > for i in xrange(1, 5): > yield "tuple_%s" % i, tuple(iter_coords(i)) > > locals().update(dict(iter_vars())) locals().update() works by accident here because it's in global scope; it doesn't work within a function. Use a proper data structure, like a dict or a list, and access each tuple list as 'tuples[n]' instead of 'tuple_n'. George From ctgaff at runbox.com Tue Jun 24 04:36:51 2008 From: ctgaff at runbox.com (Corey G.) Date: Tue, 24 Jun 2008 03:36:51 -0500 Subject: Python 3000 vs Perl 6 In-Reply-To: References: Message-ID: What I meant, in terms of dealing with accurate or non-accurate rumors is with speed, yes. There are plenty of comparisons where Perl is 4-15x faster then Python for 'some' operations regarding regular expressions, etc. For me personally, this means absolutely nothing because if I spend 50x more time comprehending spaghetti, obfuscated Perl code it's irrelevant. The main concern (my concern) is whether or not Perl 6 is more like Java with pre-compiled byte code (did I say that right) and whether or not individuals without the ability to see past the surface will begin to migrate towards Perl 6 for its seemingly faster capabilities. With Perl 6 taking 10+ years, if/when it actually gets released, will it be technically ahead of Python 3000? Is Parrot worth the extra wait the Perl 6 project is enduring? My own answer would be a resounding no, but I am curious as to what others think. :) -Thanks! On Jun 24, 2008, at 2:52 AM, cokofreedom at gmail.com wrote: > On Jun 24, 8:20 am, "Corey G." wrote: >> If Perl 6 ever does get on its feet and get released, how does it >> compare to Python 3000? Is Perl 6 more like Java now with Parrot? I >> just want to make sure that Python is staying competitive. >> >> If this is the wrong mailing list, just let me know. Thanks! > > Do you mean in terms of speed (parrot is a JIT?). I believe Python 3k > will (when out of beta) will have a speed similar to what it has > currently in 2.5, possibly with speed ups in some locations. But > competitive-wise I think the point is Python 3k tries to remove warts > from the Python Language to make it even more friendly to readers and > writers alike. In that way it should/will stay competitive. > > However towards overall usage, the general advice is to stay with the > 2.x series for now, trying to ensure your code style is moving towards > the Py3k style, and then make the jump to the 3.x series when it is > finialised. > > Another point, is Perl 6 ever going to get released :P > -- > http://mail.python.org/mailman/listinfo/python-list > From maric at aristote.info Mon Jun 16 13:07:28 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 16 Jun 2008 19:07:28 +0200 Subject: 'string'.strip(chars)-like function that removes from the middle? In-Reply-To: <48569B9E.6030206@admailinc.com> References: <48569B9E.6030206@admailinc.com> Message-ID: <200806161907.29636.maric@aristote.info> Le Monday 16 June 2008 18:58:06 Ethan Furman, vous avez ?crit?: > The strip() method of strings works from both ends towards the middle. > Is there a simple, built-in way to remove several characters from a > string no matter their location? (besides .replace() ;) > > For example: > .strip --> 'www.example.com'.strip('cmowz.') > 'example' > .??? --> --- 'www.example.com'.strip('cmowz.') > 'exaple' As Larry Bates said the python way is to use str.join, but I'd do it with a genexp for memory saving, and a set to get O(1) test of presence. to_remove = set('chars') ''.join(e for in string_ if e not in to_remove) Note that this one will hardly be defeated by other idioms in python (even regexp). Using a genexp is free and a good practice, using a set, as it introduce one more step, can be considered as premature optimisation and the one liner : ''.join(e for in string_ if e not in 'chars') may be preferred. -- _____________ Maric Michaud From pavlovevidence at gmail.com Wed Jun 4 07:11:26 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 4 Jun 2008 04:11:26 -0700 (PDT) Subject: Best way to modify code without breaking stuff. References: Message-ID: <71db4569-85df-43c9-89ff-1f047d8f2359@c58g2000hsc.googlegroups.com> On Jun 4, 3:44 am, Ivan Illarionov wrote: > On Wed, 04 Jun 2008 00:25:19 -0700, Jesse Aldridge wrote: > > I've got a module that I use regularly. I want to make some extensive > > changes to this module but I want all of the programs that depend on the > > module to keep working while I'm making my changes. What's the best way > > to accomplish this? > > Version control system. > > http://en.wikipedia.org/wiki/List_of_revision_control_software > > Make your module a versioned repository. > Make your changes in different place, then commit them. That doesn't seem like a good solution for the OP's particular problem. To do it in a "different place", as you say, he'd have to check out a new working copy, which might be a bit of overkill depending on the size of the project. It could also be problematic to have separate working copies; there could be programs outside the project that are configured to use a certain location, for instance. One thing you could do with some version control systems is to switch the particular version for the module in question between different branches depending on whether you're using the tools or changing the model. (Subversion can do this, but I'm not sure if it's for individual files or only directories.) Carl Banks From omer at no-log.org Mon Jun 30 11:16:47 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Mon, 30 Jun 2008 17:16:47 +0200 Subject: regex help In-Reply-To: <12af01c8dac1$1dc54530$a501a8c0@office.ipglobal.net> References: <12af01c8dac1$1dc54530$a501a8c0@office.ipglobal.net> Message-ID: <200806301716.47247.omer@no-log.org> Le Monday 30 June 2008 16:53:54 Support Desk, vous avez ?crit?: > Hello, > I am working on a web-app, that querys long distance numbers from a > database of call logs. I am trying to put together a regex that matches any > number that does not start with the following. Basically any number that > does'nt start with: > > > > 281 > > 713 > > 832 > > > > or > > > > 1281 > > 1713 > > 1832 > > > > > > is long distance any, help would be appreciated. sounds like str.startswith() is enough for your needs: if not number.startswith(('281', '713', '832', ...)) : ... -- C?dric Lucantis From kyosohma at gmail.com Tue Jun 10 20:50:52 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 10 Jun 2008 17:50:52 -0700 (PDT) Subject: Instructions on how to build py2exe 0.6.8 (or an installer would be nice, too!) References: <5426baaf-2ba6-41b0-a0ec-1070429b5195@x35g2000hsb.googlegroups.com> <7f3360e4-8a12-45cf-99fa-6172cb5a1aaa@a1g2000hsb.googlegroups.com> <5cde3ec8-2e8d-4c1e-bee9-1ee51f649cd8@d45g2000hsc.googlegroups.com> <9af1adfb-5bce-48e8-b17f-4d838f788b90@d77g2000hsb.googlegroups.com> Message-ID: <16697d7e-4888-4733-b40e-b935f9a44966@x35g2000hsb.googlegroups.com> Evan, > > > I finally figured out how to check out the code. I'm at work now, > > where I only have VS2008 installed so I'll have to wait until I get > > home this evening to try compiling it. I'll let you know if I have any > > luck. > > > --------------------- > > Mike > > > Python Extension Building Network: ? ? > > Thanks, Mike. Hopefully you'll have more luck than I've had : ) > > Evan I got it compiled. They are up on my website: http://pythonlibrary.org/python_modules.htm I tested it on one of my simple programs and it ran. I used the 2.5 version for that test. However, it should be noted that I haven't been able to get the tests from CVS to run. The Traceback doesn't appear to be py2exe related though. I'll post the issue to their group and see if they have any idea why that would be. In the meantime, feel free to give it a try. At worst you'll have to delete the compiled binary and the py2exe folder. Mike From larry.bates at websafe.com` Tue Jun 10 21:51:03 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 10 Jun 2008 20:51:03 -0500 Subject: Dynamic HTML from Python Script In-Reply-To: <484f151c$0$5009$607ed4bc@cv.net> References: <484f151c$0$5009$607ed4bc@cv.net> Message-ID: asdf wrote: > I have a python script whose output i want to dynamically display > on a webpage which will be hosted using Apache. How do I do that? > > > thanks Take a look at Django. It may be overkill for this first project but any time you spend learning it should be paid back in future projects. -Larry From ivan.illarionov at gmail.com Wed Jun 4 10:13:55 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 4 Jun 2008 14:13:55 +0000 (UTC) Subject: Trying to extend Python with C: undefined reference to `Py_BuildValue' References: <045458d3-771b-459d-b5ef-21d8f3c08659@2g2000hsn.googlegroups.com> Message-ID: On Wed, 04 Jun 2008 05:57:20 -0700, spectrumdt wrote: > Hello. > > I am trying to extend Python with some C code. I made a trivial > "Hello World" program in C that I am trying to wrap in "boilerplate" for > inclusion in a Python program. But I can't compile the C code. The C > compiler cannot find the required function `Py_BuildValue'. > > My C code looks like this: > > > > #include "/usr/include/python2.5/Python.h" > > /* Python wrapper for 'main'. */ > static PyObject* mpi_main() { > int res = main(); > PyObject* retval = (PyObject*)Py_BuildValue("i",res); > } > > /* Main. A 'Hello World' function. */ int main() { > printf ("Hello, World. I am a C function.\n"); > } > > > > And my error message looks like this: > > > > [ore at localhost Opgave03]$ gcc ctest.c /tmp/ccH46bs8.o: In function > `mpi_main': ctest.c:(.text+0x1d): undefined reference to > `Py_BuildValue' collect2: ld returned 1 exit status > [ore at localhost Opgave03]$ > > > > I searched the newsgroup and found this thread: > > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/ c6d70e02a6bc9528/87b836f369bd0042?lnk=gst&q=undefined+reference+to+% 60Py_BuildValue%27#87b836f369bd0042 > > It recommended that I add the option "-Wl,--export-dynamic" when > calling gcc. That makes no difference. The thread also has some more > stuff that I don't quite understand. > > Can anyone help? I am including Python.h, so why does it not find > Py_BuildValue? > > Thanks in advance. Hi! Your C code contains too many errors. I'm lazy to comment them all. Here's my take on the trivial "Hello world" in Python C API: 1. create 'hello.c' file with the following content: #include PyObject* hello(PyObject* self) { printf("Hello world!\n"); Py_RETURN_NONE; } static PyMethodDef functions[] = { {"hello", (PyCFunction)hello, METH_NOARGS}, {NULL, NULL, 0, NULL}, }; DL_EXPORT(void) init_hello(void) { Py_InitModule("_hello", functions); } 2. create 'buildme.py' file with this content: import os import sys from distutils.core import Extension, setup os.chdir(os.path.dirname(os.path.abspath(__file__))) sys.argv = [sys.argv[0], 'build_ext', '-i'] setup(ext_modules = [Extension('_hello', ["hello.c"])]) 3. run "python buildme.py" That's all. >>> from _hello import hello >>> hello() Hello world! -- Ivan From marcoberi at gmail.com Mon Jun 23 12:23:49 2008 From: marcoberi at gmail.com (Marcob) Date: Mon, 23 Jun 2008 09:23:49 -0700 (PDT) Subject: Find class attributes creation order References: Message-ID: On 23 Giu, 18:08, C?dric Lucantis wrote: > Le Monday 23 June 2008 17:53:07 Marcob, vous avez ?crit?: > > > Let's see these simple classes: > > > ? ? class base_foo() > > ? ? ? ? ?pass > > > ? ? class foo(base_foo): > > ? ? ? ? ?a=1 > > ? ? ? ? ?b={} > > ? ? ? ? ?c="zz" > > > I would like to find class foo attributes creation order. > > Using __metaclass__ is not of help because special method __new__ > > receive attrs as a dictionary and so the order isn't preserved. Any > > other idea? > > I don't really understand what you want, but __new__ may accept any kind of > attributes, this is your choice. You can use named params or a vararg list > (which will preserve params order). Ok, I'll try to make myself clearer. > But in your example you're only using class attributes, so __new__ is not > involved and they are just created once for all in the order you write them: > a, b, c. Yes, this is true but if another piece of code define class foo (and consequently a, b, c) and I would like to find how many class attributes are defined and their order, how can I do this? It's easy to find how many attributes there are: using __dict__ or dir() or whatever. But to find their order isn't so easy. Besides that I can do whatever I want with class base_foo but I can't touch class foo. Ciao. Marco. From arnodel at googlemail.com Mon Jun 2 00:36:02 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 02 Jun 2008 05:36:02 +0100 Subject: php vs python References: Message-ID: "Joel Koltner" writes: > There's potentially a large difference between a "good" speaker of > English/German/etc. vs. "eloquent." > > I'd tend to agree with Jerry that if you can write "good" code in > one language, you can in pretty much any other as well... but that > doesn't imply you're necessarily "eloquent" in any languages. :-) > Eloquence is nice, but eradicating "bad" code in this world is about > a million times more important than attempting to move people from > "good" code to "eloquent" code. This is wrong, because if you know well one language only, you tend to think that the principles that underpin it are universal. So you will try to shoehorn these principles into any other language you use. It's only when you have become reasonably proficient in a number of conceptually different languages that you start to build a picture of what "a programming language" is. I understand that there are some sane practices that are useful to know when programming in any language, but it is wrong to say that the skill of programming can be reduced to that, the rest being syntax. There is (hopefully!) a design behind the syntax, you have to understand it to use the language well. You may be great at building Turing machines. That doesn't make you a master of crafting lambda-expressions. > To be Pythonic here, "eloquent" code would perhaps often have clear, > clean list comprehensions used when "good" code would use a "for" > loop but still be easy to follow as well and perfectly acceptable in > the vast majority of cases. I find that eloquent Python speakers often tend to write a for loop when mere good ones will try to stick a list comprehension in! Regards -- Arnaud From reckoner at gmail.com Mon Jun 9 18:30:32 2008 From: reckoner at gmail.com (Reckoner) Date: Mon, 9 Jun 2008 15:30:32 -0700 (PDT) Subject: access variables from one Python session to another on the same machine? Message-ID: <6ea6b084-3897-43f9-b8e0-dff52b47f1a0@w1g2000prd.googlegroups.com> Suppose I have two different command windows going on the same machine, each running their own Python interpreters. Is it possible to access the variables in one of the interpreter- sessions from the other? It turns out I have limited control over one of the sessions (i.e. cannot control all the code that is run from there), but complete control over the other. I get the feeling this has been asked before, but I'm not sure how to pose the question in such a way that it would show up on a search. It's confusing. Thanks. From dullrich at sprynet.com Mon Jun 30 16:09:45 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Mon, 30 Jun 2008 15:09:45 -0500 Subject: Do I need "self" and "other"? References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> Message-ID: In article <68566b52-100d-40ee-a0c6-bde20df9ecd4 at a70g2000hsh.googlegroups.com>, Kurda Yon wrote: > Hi, > > I found one example which defines the addition of two vectors as a > method of a class. It looks like that: > > class Vector: > def __add__(self, other): > data = [] > for j in range(len(self.data)): > data.append(self.data[j] + other.data[j]) > return Vector(data) > > In this example one uses "self" and "other". Does one really need to > use this words? And, if yes, why? I have replaced "self" by "x" and > "other" by "y" and everything looks OK. Is it really OK or I can have > some problem in some cases? What everyone else has said: yes and no. Having said that, it seems to me like this is exactly the sort of situation where 'x' and 'y' make a lot of sense - self means that this is the object on which the method was invoked, and here that seems irrelevant: If you want to calculate x + y you use x.data and y.data... Otoh, I once saw a library (someone's Python arbitrary-precision reals package) where he used x and y, and sure enough I was confused. Otooh, I was't confused by it for long, and I quickly decided that it actually made _that_ code look like it made more sense. > Thank you! -- David C. Ullrich From george.sakkis at gmail.com Tue Jun 3 22:02:03 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 3 Jun 2008 19:02:03 -0700 (PDT) Subject: ANN: equivalence 0.2 Message-ID: <2de2caf8-7c98-41da-afa8-1332143ebaff@j22g2000hsf.googlegroups.com> Equivalence v0.2 has been released. Also the project is now hosted at http://code.google.com/p/pyquivalence/ (the name 'equivalence' was already taken but the module is still called equivalence). Changes ======= - The internals were largely rewritten, but the API remained effectively intact. - A new `equivalence(**kwds)` factory function is now the preferred way to create an equivalence. Two kwds supported for now, `key` and `bidirectional`. - Now uses the union-find algorithm on disjoint-set forests; improves the linear worst-case time to practically constant amortized time for the basic operations. - Modular redesign; the original Equivalence class has been broken down into subclasses, each trading off more features with extra overhead: - The base Equivalence class is a vanilla disjoint-sets forest; it doesn't support keys and partition() is slow, but the rest operations are faster. - KeyEquivalence adds implicit (key-based) equivalence. - BidirectionalEquivalence provides fast partition() at the cost of higher memory overhead and slowing down slightly the rest operations. - KeyBidirectionalEquivalence combines the two previous. - Added more tests and updated docs. About ===== *equivalence* is a Python module for building equivalence relations: partitionings of objects into sets that maintain the equivalence relation properties (reflexivity, symmetry, transitivity). Two objects are considered equivalent either explicitly, after being merged, or implicitly, through a key function. From cwitts at gmail.com Sat Jun 21 16:52:48 2008 From: cwitts at gmail.com (Chris) Date: Sat, 21 Jun 2008 13:52:48 -0700 (PDT) Subject: Getting column names from a cursor using ODBC module? References: Message-ID: <4fe11953-15a9-4363-819f-b54b4f05941c@y38g2000hsy.googlegroups.com> On Jun 21, 3:58?pm, dana... at yahoo.com wrote: > Is there any way to retrieve column names from a cursor using the ODBC > module? Or must I, in advance, create a dictionary of column position > and column names for a particular table before I can access column > values by column names? I'd prefer sticking with the ODBC module for > now because it comes standard in Python. > > I'm using Python 2.4 at the moment. > > Thanks. You should be able to do column_names = [d[0] for d in cursor.description] From punitha.d24 at gmail.com Sun Jun 8 03:49:47 2008 From: punitha.d24 at gmail.com (punitha.d24 at gmail.com) Date: Sun, 8 Jun 2008 00:49:47 -0700 (PDT) Subject: online money Message-ID: online money online business money is very important http://worldlangs.blogspot.com/ From p.f.moore at gmail.com Thu Jun 19 04:43:25 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Thu, 19 Jun 2008 09:43:25 +0100 Subject: [Python-3000] RELEASED Python 2.6b1 and 3.0b1 In-Reply-To: <1972109D-735D-4485-82F4-9BC8F2984967@python.org> References: <1972109D-735D-4485-82F4-9BC8F2984967@python.org> Message-ID: <79990c6b0806190143n58e51a22ubafd3fe343291dfb@mail.gmail.com> On 19/06/2008, Barry Warsaw wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On behalf of the Python development team and the Python community, I am > happy to announce the first beta releases of Python 2.6 and Python 3.0. Any ETA for Windows builds? The web pages still point to the alphas. (I'd like to see the Windows builds more closely integrated with the releases now we're in beta stage...) Paul. From mikalzet_togli at libero.it Sun Jun 1 08:15:31 2008 From: mikalzet_togli at libero.it (Taekyon) Date: Sun, 01 Jun 2008 14:15:31 +0200 Subject: Merging ordered lists References: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> Message-ID: etal wrote: > Speed actually isn't a problem yet; it might matter some day, but for > now it's just an issue of conceptual aesthetics. Any suggestions? Looks as if set does it for you. -- Taekyon From rw.segaar at xs4all.nl Mon Jun 16 15:10:58 2008 From: rw.segaar at xs4all.nl (Robert) Date: Mon, 16 Jun 2008 21:10:58 +0200 Subject: py2exe 0.6.8 released References: Message-ID: <4856bac5$0$12058$e4fe514c@dreader20.news.xs4all.nl> Being new on on Python (but otherwise experienced programmer this message triggered me to do the install. It looks like a nice way to do a comprehensive check of your system. When running one of the py2exe samples, located in C:\Python25\Lib\site-packages\py2exe\samples\singlefile\gui I got the following error when running the resulting executable: C:\Python25\Lib\site-packages\py2exe\samples\singlefile\gui\dist\test_wx.exe\zipextimporter.py:82: DeprecationWarning: The wxPython compatibility package is no longer automatically generated or actively maintained. Please switch to the wx package as soon as possible. Traceback (most recent call last): File "test_wx.py", line 1, in File "zipextimporter.pyo", line 82, in load_module File "wxPython\__init__.pyo", line 15, in File "zipextimporter.pyo", line 82, in load_module File "wxPython\_wx.pyo", line 8, in File "zipextimporter.pyo", line 82, in load_module File "wxPython\_misc.pyo", line 456, in AttributeError: 'module' object has no attribute 'DateTime_GetNumberOfDaysinYear' I know of course the real error must be on the wx part of it all. I only have: - a python 2.5.2 install(msi) - a "wxPython2.8-win32-unicode-2.8.7.1-py25.exe" install - a "py2exe-0.6.8.win32-py2.5.exe"install. I have deleted C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wxPython because there indications that this is not needed, but other problems emerged. Any clues how to proceed next? Robert From johnjsal at gmailNOSPAM.com Thu Jun 5 23:42:07 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Thu, 05 Jun 2008 23:42:07 -0400 Subject: Do this as a list comprehension? Message-ID: <4848b213$0$25711$607ed4bc@cv.net> Is it possible to write a list comprehension for this so as to produce a list of two-item tuples? base_scores = range(8, 19) score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] print zip(base_scores, score_costs) I can't think of how the structure of the list comprehension would work in this case, because it seems to require iteration over two separate sequences to produce each item in the tuple. zip seems to work fine anyway, but my immediate instinct was to try a list comprehension (until I couldn't figure out how!). And I wasn't sure if list comps were capable of doing everything a zip could do. Thanks. From rileyrgdev at gmail.com Wed Jun 25 09:24:56 2008 From: rileyrgdev at gmail.com (Richard G Riley) Date: Wed, 25 Jun 2008 15:24:56 +0200 Subject: IDE on the level of Eclipse or DEVc++? References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> <486214ae$0$9742$426a34cc@news.free.fr> <87ej6lq02c.fsf@benfinney.id.au> Message-ID: Jorge Godoy writes: > cokofreedom at gmail.com wrote: > >> How is emacs on a windows platform? > > Except for Windows using _emacs instead of .emacs, it was the same I had on Linux, last time I tried it... :-) > > There are packages for Windows that have a lot of things pre-packaged > to make it feel more like a Windows application, including keyboard > shortcuts. More specifically : cua-mode From larry.bates at websafe.com` Wed Jun 11 09:49:24 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 11 Jun 2008 08:49:24 -0500 Subject: Producer-consumer threading problem In-Reply-To: References: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> Message-ID: George Sakkis wrote: > On Jun 10, 11:47 pm, Larry Bates wrote: >> I had a little trouble understanding what exact problem it is that you are >> trying to solve but I'm pretty sure that you can do it with one of two methods: > > Ok, let me try again with a different example: I want to do what can > be easily done with 2.5 Queues using Queue.task_done()/Queue.join() > (see example at http://docs.python.org/lib/QueueObjects.html), but > instead of having to first put all items and then wait until all are > done, get each item as soon as it is done. > >> 1) Write the producer as a generator using yield method that yields a result >> every time it is called (something like os.walk does). I guess you could yield >> None if there wasn't anything to consume to prevent blocking. > > Actually the way items are generated is not part of the problem; it > can be abstracted away as an arbitrary iterable input. As with all > iterables, "there are no more items" is communicated simply by a > StopIteration. > >> 2) Usw somethink like Twisted insted that uses callbacks instead to handle >> multiple asynchronous calls to produce. You could have callbacks that don't do >> anything if there is nothing to consume (sort of null objects I guess). > > Twisted is interesting and very powerful but requires a different way > of thinking about the problem and designing a solution. More to the > point, callbacks often provide a less flexible and simple API than an > iterator that yields results (consumed items). For example, say that > you want to store the results to a dictionary. Using callbacks, you > would have to explicitly synchronize each access to the dictionary > since they may fire independently. OTOH an iterator by definition > yields items sequentially, so the client doesn't have to bother with > synchronization. Note that with "client" I mean the user of an API/ > framework/library; the implementation of the library itself may of > course use callbacks under the hood (e.g. to put incoming results to a > Queue) but expose the API as a simple iterator. > > George If you use a queue and the producer/collector are running in different threads you don't have to wait for "to first put all items and then wait until all are done". Producer can push items on the queue and while the collector asynchronously pops them off. I'm virtually certain that I read on this forum that dictionary access is atomic if that helps. -Larry From mdw at distorted.org.uk Tue Jun 17 11:25:02 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Tue, 17 Jun 2008 15:25:02 +0000 (UTC) Subject: 2Q's: How to autocreate instance of class;How to check for membership in a class References: <48571086$0$5010$607ed4bc@cv.net> Message-ID: asdf wrote: (Presumably nothing to do with the Common Lisp system-definition utility.) > So for example if I know that var1=jsmith. Can I somehow do > var1=User(). Something like this might work. class User (object): def __init__(me, name): me.name = name class Users (object): def __getattr__(me, name): try: return object.__getattr__(me, name) except AttributeError: u = me.__dict__[name] = User(name) return u >>> users = Users() >>> alice = users.alice >>> alice.name 'alice' >>> alice is users.alice True Not very nice, though, and not particularly good at defending against typos. > My second question is how can I check if object is a member of a class. > so let's say I create a=User(), b=User()... The built-in isinstance function seems an obvious choice. -- [mdw] From dickinsm at gmail.com Tue Jun 24 04:38:53 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 24 Jun 2008 01:38:53 -0700 (PDT) Subject: binary representation of an integer References: <14e14b5e-ce39-414a-a450-7c81baaabc3a@79g2000hsk.googlegroups.com> Message-ID: On Jun 24, 9:03?am, eliben wrote: > What would be the quickest way to do this ? I think that for dec2bin > conversion, using hex() and then looping with a hex->bin lookup table > would be probably much faster than the general baseconvert from the > recipe. I suspect you're right, but it would be easy to find out: just code up the hex->bin method and use the timeit module to do some timings. Don't forget to strip the trailing 'L' from hex(n) if n is a long. If you're prepared to wait for Python 2.6, or work with the beta version, then the conversion is already there: Macintosh-3:trunk dickinsm$ ./python.exe Python 2.6b1+ (trunk:64489, Jun 23 2008, 21:10:40) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> bin(13) '0b1101' Interestingly, unlike hex and oct, bin doesn't add a trailing 'L' for longs: >>> bin(13L) '0b1101' I wonder whether this is a bug... Mark From http Wed Jun 4 07:21:46 2008 From: http (Paul Rubin) Date: 04 Jun 2008 04:21:46 -0700 Subject: Best way to modify code without breaking stuff. References: Message-ID: <7xod6htph1.fsf@ruckus.brouhaha.com> Jesse Aldridge writes: > I've got a module that I use regularly. I want to make some extensive > changes to this module but I want all of the programs that depend on > the module to keep working while I'm making my changes. What's the > best way to accomplish this? Do you mean you want to hot-patch a running program? The short answer is: don't. From python.leojay at gmail.com Fri Jun 13 03:02:48 2008 From: python.leojay at gmail.com (Leo Jay) Date: Fri, 13 Jun 2008 15:02:48 +0800 Subject: why can i still able to reproduce the SimpleHTTPServer bug which is said fixed 3 years ago? Message-ID: <4e307e0f0806130002u6795c55ejce02b71753df33ae@mail.gmail.com> http://bugs.python.org/issue1097597 in my python 2.5.2, i still find these code in SimpleHTTPServer.py, is that deliberate? ctype = self.guess_type(path) if ctype.startswith('text/'): mode = 'r' else: mode = 'rb' try: f = open(path, mode) except IOError: self.send_error(404, "File not found") return None self.send_response(200) self.send_header("Content-type", ctype) fs = os.fstat(f.fileno()) self.send_header("Content-Length", str(fs[6])) # <-- obviously, this is not the same with len(f.read()) in windows. -- Best Regards, Leo Jay From subhabrata.iisc at hotmail.com Fri Jun 27 03:51:53 2008 From: subhabrata.iisc at hotmail.com (subhabrata.iisc at hotmail.com) Date: Fri, 27 Jun 2008 00:51:53 -0700 (PDT) Subject: Question on List Message-ID: <7f03fa3f-c8fd-45a8-b4a5-d7c66982aa4a@q27g2000prf.googlegroups.com> Dear All, I am trying to write the following code: def try1(n): a1="God Godess Borother Sister Family" a2=a1.split() a3=raw_input("PRINT A WORD") a4=a1.find(a3) print a4 a5=[] if a4>0: a5=a2.index(a3) a6=a5+1 a7=a2[a6] print "The new word is" print a7 a8=a5.append(a7) print a5 elif a4<0: a11=a3 print "The word is not availiable in String" print a11 a6=a5.append(a11) print a5 else: print "Error" Now, my question is I like to see a5 or the empty list as appended with elements. Results I am getting is a5 giving single value like ['God'],['Godess']... but I like to see it as ['God','Godess'...] etc. Am I going wrong? Do I have to rethink it in some other way? If any one can kindly let me know. Best Regards, Subhabrata. From david at hlacik.eu Wed Jun 4 18:27:32 2008 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Thu, 5 Jun 2008 00:27:32 +0200 Subject: no module named py In-Reply-To: References: Message-ID: most important method inside news class is newsauth which takes username, password and will return 1 if ldap authentification was OK. actually inn will call method authenticate which will call self.newsauth and here comes the problem .. i ve got instead of call self.newsauth error no module named py : from authenticate : try: syslog('notice', "result %s" % self.newsauth('boss','bbbb')) except Exception, msg: syslog('notice', "error %s, %s, %s" % (type(msg),msg.args,msg)) On Thu, Jun 5, 2008 at 12:26 AM, David Hl??ik wrote: > Hello, what this beautifull mesage which is messing me whole day means : > > *python: error , ('No module named py',), No module named > py* > > as a result of class pdg.py which is called from nnrpd_auth.py. > > To be detailed ... news server inn is calling that when doing > autentification , it calls nnrpd_auth.py where instance of my class is > hooked into inn , when authentification begins it calls method > authenticate(arguments) from pdg. > > I will provide as many information as needed to solve this mistery, becouse > i really need to solve it. > Thanks! > > > #!/usr/bin/env python > > import ldap > from nnrpd import syslog > class news: > > server = 'ldap://dev01.net.hlacik.eu' > user_dn = 'cn=pdg,ou=Operators,o=Polarion' > user_pw = 'Pdg1' > > connectcodes = { 'READPOST':200, > 'READ':201, > 'AUTHNEEDED':480, > 'PERMDENIED':502 > } > > authcodes = { 'ALLOWED':281, > 'DENIED':502 > } > > def newsauth(self,match_username,match_password): > base_dn = 'ou=Users,o=Polarion' > filter = "(uid=" + match_username + ")" > attrs = ['userPassword'] > > try : > l = ldap.initialize(self.server) > l.bind_s(self.user_dn, self.user_pw) > raw_res = l.search_s( base_dn, ldap.SCOPE_SUBTREE, > filter, attrs ) > l.unbind() > except ldap.SERVER_DOWN: > print "Error, server down" > return 2 > except ldap.INVALID_CREDENTIALS: > print "Error, invalid credentials" > return 2 > except ldap.LDAPError, e: > print "Error, %s" % e > for results in raw_res: > (cn,search) = results > for password in search["userPassword"]: > if password == match_password: return 1 > > return 0 > > > def authenticate(self, attributes): > > # just for debugging purposes > syslog('notice', 'nnrpd_auth authenticate() invoked: > hostname %s, ipaddress > %s, interface %s, user %s' % (\ > attributes['hostname'], \ > attributes['ipaddress'], \ > attributes['interface'], \ > attributes['user'])) > > try: > syslog('notice', "result %s" % > self.newsauth('boss','bbbb')) > except Exception, msg: > syslog('notice', "error %s, %s, %s" % > (type(msg),msg.args,msg)) > # do username passworld authentication > #if self.newsauth(attributes['user'], > str(attributes['pass'])): > # syslog('notice', 'authentication by username > succeeded') > # return ( self.authcodes['ALLOWED'], 'No error' ) > #else: > # syslog('notice', 'authentication by username failed') > # return ( self.authcodes['DENIED'], 'Access Denied!') > > ------------------- > > nnrpd_auth_py : > > # > # Sample authentication and authorization class. It defines all methods > known > # to nnrpd. > # > # Import functions exposed by nnrpd. This import must succeed, or nothing > # will work! > from nnrpd import * > from pdg import * > > myauth = news() > > # ...and try to hook up on nnrpd. This would make auth object methods > visible > # to nnrpd. > try: > set_auth_hook(myauth) > syslog('notice', "authentication module successfully hooked into > nnrpd") > except Exception, errmsg: > syslog('error', "Cannot obtain nnrpd hook for authentication method: > %s" % errmsg[0]) -------------- next part -------------- An HTML attachment was scrubbed... URL: From matthieu.brucher at gmail.com Thu Jun 5 17:26:42 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Thu, 5 Jun 2008 23:26:42 +0200 Subject: How to make py2.5 distutil to use VC2005? In-Reply-To: References: Message-ID: 2008/6/4 ?? : > Howdy, > This problem have puzzled me for a long time. I usually use > python2.5 in Windows, while VC2005 is installed. > However python25.lib is compiled by VC2003. When I use disutil to > build some C extensions, it complaints that > there is no VC2003. > Well, IMO, the format of binary files generated by VC2003 and > VC2005 is compatible in most cases. What > should I do to workaround this error? I mean, disable distutil > complaints and use VC2005 to build C extensions. > I have google-ed some discussion related on this topic. It seems that > it's real possible! > Hi, I have the same issue that you have. If you only want to create some extensions to optimize some pieces of your code, try to build them with SCons or cmake. It will work provided you don't use usual C structures (FILE, ...) Matthieu -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -------------- next part -------------- An HTML attachment was scrubbed... URL: From apardon at forel.vub.ac.be Mon Jun 2 06:37:35 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 2 Jun 2008 10:37:35 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> Message-ID: On 2008-06-02, Duncan Booth wrote: > Antoon Pardon wrote: > >> If you really need it, you can do data hiding in python. It just >> requires a bit more work. > >> --- $ python >> Python 2.5.2 (r252:60911, Apr 17 2008, 13:15:05) >> [GCC 4.2.3 (Debian 4.2.3-3)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> From Hide import Foo >>>>> var = Foo() >>>>> var.GetX() >> 0 >>>>> var.SetX(5) >>>>> var.GetX() >> 5 >>>>> var.x >> Traceback (most recent call last): >> File "", line 1, in >> AttributeError: 'Foo' object has no attribute 'x' >>>>> var.hidden.x >> Traceback (most recent call last): >> File "", line 1, in >> AttributeError: 'Foo' object has no attribute 'hidden' >> > > That sort of hiding isn't any more secure than the 'hiding' you get in C++. So? >>>> var.GetX.func_closure[0].cell_contents.x > 5 > > All you've done is force the user who wants to bypass it to use a longer > expression, and if that's your criterion for 'hiding' then just use two > leading underscores. That you can find a lock pick to get at an object doesn't contradict that the object is locked away. I think the intention of not having these variables accesable to the application programmer is much stronger expressed than with two leading underscores. Even if the current implementation of the language makes it relatively easy to get at the information if you really want to. -- Antoon Pardon From nicola.musatti at gmail.com Tue Jun 3 11:08:56 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Tue, 3 Jun 2008 08:08:56 -0700 (PDT) Subject: Code correctness, and testing strategies References: Message-ID: On Jun 3, 12:35 am, ja... at cd.chalmers.se (Jacob Hallen) wrote: > In article , > > David wrote: [...] > >That's why you have human testing & QA. Unit tests can help, but they > >are a poor substitute. If the customer is happy with the first > >version, you can improve it, fix bugs, and add more unit tests later. > > The most important aspect of usnit testing is actually that it makes the code testable. > This may sound lik an oxymoron but it is actually a really important property. Testable > code has to have a level of modularity as well as simplicity and clarity in its > interfaces that you will not achieve in code that lacks automated unit tests. I don't agree. To me the most important aspect of unit testing is that it is automated. That is, the time you spend writing new tests you reap each time you run your test suite. The fact that writing automated tests has a beneficial effect on the modularity of your code is a pleasant though hard to measure side effect. Automation should also be the most convincing argument for the OP. The most evident liability of the approach he described is the need to re- instrument his code all over again each time. Writing an equivalent set of automated tests is likely to take him more, but the time taken to write each test is time he doesn't need to spend anymore. [...] > Another aspect that you are raising is the use of human testing and QA. I agree that > these are important, but every bug they discover is a failure of the developers and > their tests. Our testers can sail through a testbed in 30 minutes if there are no bugs. > Every single bug adds 30-60 minutes of testers time in order to pinpoint the bug > and supply the developers with enough information to locate and fix it. Add some > 10 minutes to testing time on the next testbed to verify that the bug is actually > fixed. In my end of the world, tester time is not cheaper than developer time. It > is also a scarcer resource than developer time. Moreover, hand performed testing takes the same amount of time each time it is performed and doesn't enjoy the incremental aspect of automated testing. Cheers, Nicola Musatti From george.sakkis at gmail.com Thu Jun 12 15:14:50 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 12 Jun 2008 12:14:50 -0700 (PDT) Subject: Simple and safe evaluator References: <80b23a5a-8613-4232-8954-7f7e4181322e@k37g2000hsf.googlegroups.com> Message-ID: <63a81194-182f-4d31-b149-6249fc3443a0@25g2000hsx.googlegroups.com> On Jun 12, 1:51 pm, bvdp wrote: > Matimus wrote: > > On Jun 11, 9:16 pm, George Sakkis wrote: > >> On Jun 11, 8:15 pm, bvdp wrote: > > >>> Matimus wrote: > >>>> The solution I posted should work and is safe. It may not seem very > >>>> readable, but it is using Pythons internal parser to parse the passed > >>>> in string into an abstract symbol tree (rather than code). Normally > >>>> Python would just use the ast internally to create code. Instead I've > >>>> written the code to do that. By avoiding anything but simple operators > >>>> and literals it is guaranteed safe. > >>> Just wondering ... how safe would: > >>> eval(s, {"__builtins__":None}, {} ) > >>> be? From my testing it seems that it parses out numbers properly (int > >>> and float) and does simple math like +, -, **, etc. It doesn't do > >>> functions like int(), sin(), etc ... but that is fine for my puposes. > >>> Just playing a bit, it seems to give the same results as your code using > >>> ast does. I may be missing something! > >> Probably you do; within a couple of minutes I came up with this: > > >>>>> s = """ > >> ... (t for t in 42 .__class__.__base__.__subclasses__() > >> ... if t.__name__ == 'file').next()('/etc/passwd') > >> ... """>>> eval(s, {"__builtins__":None}, {} ) > > >> Traceback (most recent call last): > >> File "", line 1, in > >> File "", line 3, in > >> IOError: file() constructor not accessible in restricted mode > > >> Not an exploit yet but I wouldn't be surprised if there is one. Unless > >> you fully trust your users, an ast-based approach is your best bet. > > >> George > > > You can get access to any new-style class that has been loaded. This > > exploit works on my machine (Windows XP). > > > [code] > > # This assumes that ctypes was loaded, but keep in mind any classes > > # that have been loaded are potentially accessible. > > > import ctypes > > > s = """ > > ( > > t for t in 42 .__class__.__base__.__subclasses__() > > if t.__name__ == 'LibraryLoader' > > ).next()( > > ( > > t for t in 42 .__class__.__base__.__subclasses__() > > if t.__name__ == 'CDLL' > > ).next() > > ).msvcrt.system('dir') # replace 'dir' with something nasty > > """ > > > eval(s, {"__builtins__":None}, {}) > > [/code] > > > Matt > > Yes, this is probably a good point. But, I don't see this as an exploit > in my program. Again, I could be wrong ... certainly not the first time > that has happened :) > > In my case, the only way a user can use eval() is via my own parsing > which restricts this to a limited usage. So, the code setting up the > eval() exploit has to be entered via the "safe" eval to start with. So, > IF the code you present can be installed from within my program's > scripts ... then yes there can be a problem. But for the life of me I > don't see how this is possible. In my program we're just looking at > single lines in a script and doing commands based on the text. > Setting/evaluating macros is one "command" and I just want a method to > do something like "Set X 25 * 2" and passing the "25 * 2" string to > python works. If the user creates a script with "Set X os.system('rm > *')" and I used a clean eval() then we could have a meltdown ... but if > we stick with the eval(s, {"__builtins__":None}, {}) I don't see how the > malicious script could do the class modifications you suggest. > > I suppose that someone could modify my program code and then cause my > eval() to fail (be unsafe). But, if we count on program modifications to > be doorways to exploits then we might as well just pull the plug. You probably missed the point in the posted examples. A malicious user doesn't need to modify your program code to have access to far more than you would hope, just devise an appropriate string s and pass it to your "safe" eval. Here's a simpler example to help you see the back doors that open. So you might think that eval(s, {"__builtins__":None}, {}) doesn't provide access to the `file` type. At first it looks so: >>> eval('file', {"__builtins__":None}, {}) NameError: name 'file' is not defined >>> eval('open', {"__builtins__":None}, {}) NameError: name 'open' is not defined "Ok, I am safe from users messing with files since they can't even access the file type" you reassure yourself. Then someone comes in and passes to your "safe" eval this string: >>> s = "(t for t in (42).__class__.__base__.__subclasses__() if t.__name__ == 'file').next()" >>> eval(s, {"__builtins__":None}, {}) Oops. Fortunately the file() constructor has apparently some extra logic that prevents it from being used in restricted mode, but that doesn't change the fact that file *is* available in restricted mode; you just can't spell it "file". 25 builtin types are currently available in restricted mode -- without any explicit import -- and this number has been increasing over the years: $ python2.3 -c 'print eval("(42).__class__.__base__.__subclasses__().__len__()", {"__builtins__":None}, {})' 13 $ python2.4 -c 'print eval("(42).__class__.__base__.__subclasses__().__len__()", {"__builtins__":None}, {})' 17 $ python2.5 -c 'print eval("(42).__class__.__base__.__subclasses__().__len__()", {"__builtins__":None}, {})' 25 $ python2.6a1 -c 'print eval("(42).__class__.__base__.__subclasses__().__len__()", {"__builtins__":None}, {})' 32 Regards, George From M8R-yfto6h at mailinator.com Fri Jun 6 23:36:26 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Fri, 6 Jun 2008 20:36:26 -0700 Subject: ctypes help References: Message-ID: "gianluca" wrote in message news:e1836378-5a00-43f5-b672-2e3a4191f960 at m73g2000hsh.googlegroups.com... > hy, > I've a huge problem with ctypes. I've compiled my C library and I'd > like use it in python with ctype. One function need to pass a pointer > to typed ( like this: typedef int value_type). In python I can access > to that funtion but arise an exception because python don't know my > value_type typedef. > > Please I need help, could anybody help me? > > Gianluca Let's see if I understand you correctly. You have a typedef, and a function that is passed a pointer to that typedef. Below is a short Windows DLL, compiled with "cl /LD example.c" typedef int value_type; __declspec(dllexport) void function(value_type* x) { *x *= 2; } And here is some python code to call it: >>> from ctypes import * >>> value_type = c_int # declares a type "value_type" >>> as a ctypes integer >>> value=value_type(5) # create an instance of value_type >>> function=cdll.example.function # look up the function and declare >>> return type and arguments >>> function.restype=None >>> function.argtypes=[POINTER(value_type)] >>> function(pointer(value)) # call the function with a pointer >>> to the instance >>> value c_long(10) Hope that helps. -Mark From gabriel.rossetti at arimaz.com Tue Jun 10 08:44:13 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Tue, 10 Jun 2008 14:44:13 +0200 Subject: h2py.py bug? Message-ID: <484E771D.1050404@arimaz.com> Hello everyone, I wanted to use the h2py.py script (Tools/scripts/h2py.py) and it didn't like char litterals : Skipping: PC_ERROR = ord() where my *.h file contained : #define PC_ERROR '0' I searched the web and found a post with the same error : http://mail.python.org/pipermail/python-list/2005-September/340608.html but it got no replies, I tried the fix and it works. I have the following questions: 1) Why did it not get any attention, is something wrong with it? 2) If nothing is wrong, did the fix not get applied because a bug report wasn't filed? 3) Isn't turning a char literal into the ordinal value not contrary to what a C programmer had in mind when he/she defined it? I mean if you define a char literal then in python you would have used a string value : #define PC_ERROR '0' would become : PC_ERROR = '0' in python, and if you intended to use the char type for an 8 bit numerical value you would have done : #define PC_ERROR 0x30 where 0x30 is the '0' ascii hex value, so shouldn'it the line in the diff (see the post) be : body = p_char.sub("'\\1'", body) instead of : body = p_char.sub("ord('\\1')", body) ? Thank you, Gabriel From mensanator at aol.com Mon Jun 2 18:15:48 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 2 Jun 2008 15:15:48 -0700 (PDT) Subject: Formatting Output References: <6e94b4dc-5920-447e-9971-96ec6a48b9ce@c58g2000hsc.googlegroups.com> <6ea2e85a-d00c-4228-98be-431205fceb7b@34g2000hsf.googlegroups.com> Message-ID: On Jun 2, 2:43?pm, Doug Morse wrote: > On Mon, 2 Jun 2008 12:42:12 -0700 (PDT), Mensanator wrote: > > ?On Jun 2, 3:38?am, Chris wrote: > > > On Jun 2, 9:34?am, "victor.hera... at gmail.com" > > > > wrote: > > > > Hi, > > > > > i am building a little script and i want to output a series of columns > > > > more or less like this: > > > > > 1 ?5 ?6 > > > > 2 ?2 ?8 > > > > 2 ?9 ?5 > > ... > > I have a related question: > > Does Python have (or can emulate) the formatted output capability found in > Perl? > > For example, all I have to do to get nicely formatted (i.e., aligned) output > is provide values for special STDOUT variables (i.e., STDOUT_TOP, STDOUT, > STDOUT_BOTTOM, etc.), exemplified by: > > ? format STDOUT_TOP = > ? ---------------------------------------------------------------------------?--- > ? ~ > ? . > > ? format STDOUT = > ? @<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<< > ? $res->{'full_name'}, ?$res->{'phone_1'}, ? ? ? ? $res->{'phone_1_type'} > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $res->{'address_1a'}, ? ? ? ? ? ? ? ?$res->{'address_2a'} > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $res->{'address_1b'}, ? ? ? ? ? ? ? ?$res->{'address_2b'} > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $res->{'address_1c'}, ? ? ? ? ? ? ? ?$res->{'address_2c'} > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $city_1 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?$city_2 > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $res->{'email_1'}, ? ? ? ? ? ? ? ? ? $res->{'email_2'} > ? ---------------------------------------------------------------------------?--- > ? ~ > ? . > > Then, all I have to do is populate my $res object/hash as desired -- in this > example simple the results of a SQL query -- and lastly just call the "write" > function: > > ? write; > > and Perl will produce very nicely formatted results. ?This is useful not only > for producing human readable output, but also fixed-column-width data files, > etc. ?I'd love to learn the Pythonistic way of doing the same thing. > > Thanks! > Doug I didn't know you could do that in perl. Too bad I quit using it when I switched to Python. OTOH, I can do similar formatting directly in SQL. In Access, I create a query with this SQL: SELECT "------------------------------------------------------------" & Chr(10) & Format$(SampleEventCode,"!@@@@@@@@@@@@@@@@") & Format$ (SampleEventDescr,"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") & Chr(10) & Format$(EventSortOrder,"!@@@@@@@@@@@@@@@@") & Format$("From: " & Format$(DateFrom,"YYYY/MM/ DD"),"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") & Chr(10) & Format$(SampleEventReportLabel,"!@@@@@@@@@@@@@@@@") & Format$("To: " & Format$(DateTo,"YYYY/MM/ DD"),"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") AS Expr1 FROM tblSampleEvent; Then I simply call it from Python. (I could call with the SQL code instead of invoking the Access query, but the OBDC interface can't process this particular SQL statement, tries to put brackets around the format templates, so best render unto Access the things that belong to Access.) # code import dbi import odbc con = odbc.odbc("BPWR") cursor = con.cursor() cursor.execute(""" SELECT * FROM SQLFormatTest; """) results = cursor.fetchall() for i in results: for j in i: print j # /code which prints ------------------------------------------------------------ 2000Q1 First Quarter of 2000 2000100 From: 2000/01/01 1st-Qtr 2000 To: 2000/03/31 ------------------------------------------------------------ 2000Q2 Second Quarter of 2000 2000200 From: 2000/04/01 2nd-Qtr 2000 To: 2000/06/30 ------------------------------------------------------------ 2000Q3 Third Quarter of 2000 2000300 From: 2000/07/01 3rd-Qtr 2000 To: 2000/09/30 ------------------------------------------------------------ 2000Q4 Fourth Quarter of 2000 2000400 From: 2000/10/01 4th-Qtr 2000 To: 2000/12/31 ------------------------------------------------------------ 2000Q1LF Low Flow First Quarter of 2000 2000105 From: 2000/01/01 1st-Qtr 2000 To: 2000/03/31 ------------------------------------------------------------ 2000Q2LOD LOD borings Second Quarter of 2000 2000206 From: 2000/04/01 2nd-Qtr 2000 To: 2000/06/30 . . . From apardon at forel.vub.ac.be Thu Jun 5 07:30:44 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 5 Jun 2008 11:30:44 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> <873antn9il.fsf@benfinney.id.au> <6ammujF38poe2U2@mid.uni-berlin.de> <87y75llp5x.fsf@benfinney.id.au> <6an5a7F38poe2U3@mid.uni-berlin.de> <6aok3pF38pu6cU2@mid.uni-berlin.de> <6aq0dnF3892asU2@mid.uni-berlin.de> Message-ID: On 2008-06-05, Marc 'BlackJack' Rintsch wrote: > On Thu, 05 Jun 2008 08:21:41 +0000, Antoon Pardon wrote: > >> On 2008-06-04, Marc 'BlackJack' Rintsch wrote: >>> On Wed, 04 Jun 2008 09:34:58 +0000, Antoon Pardon wrote: >>> >>>> On 2008-06-04, Marc 'BlackJack' Rintsch wrote: >>>> >>>>>>> it makes sense to me to also test if they work as documented. >>>>>> >>>>>> If they affect the behaviour of some public component, that's where >>>>>> the documentation should be. >>>>> >>>>> As I said they are public themselves for someone. >>>> >>>> Isn't that contradictory: "Public for someone" I always >>>> thought "public" meant accessible to virtually anyone. >>>> Not to only someone. >>> >>> For the programmer who writes or uses the private API it isn't really >>> "private", he must document it or know how it works. >> >> How does that make it not private. Private has never meant "accessible >> to noone". And sure he must document it and know how it works. But that >> documentation can remain private, limited to the developers of the >> product. It doesn't have to be publicly documented. > > If the audience is the programmer(s) who implement the "private" API it > is not private but public. Even the "public" API is somewhat "private" to > a user of a program that uses that API. The public is not virtually > anyone here. Depends at which level you look in the system. I think there is a general consensus about on what level to look when we are talking about private and public attributes. You can of course start talking at a whole different level and as such use these words with a meaning different than normally understood. But that will just make it harder for you to get your ideas accross. -- Antoon Pardon From ppearson at nowhere.invalid Thu Jun 26 12:20:01 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: Thu, 26 Jun 2008 11:20:01 -0500 Subject: Freeze problem with Regular Expression References: <6cf614F3f8ocoU1@mid.individual.net> Message-ID: On 25 Jun 2008 15:20:04 GMT, Kirk wrote: > Hi All, > the following regular expression matching seems to enter in a infinite > loop: > > ################ > import re > text = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA) > una ' > re.findall('[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-z]*\s*(?:[0-9] > *[A-Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$', text) > ################# > > No problem with perl with the same expression: > > ################# > $s = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA) una > '; > $s =~ /[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-z]*\s*(?:[0-9]*[A- > Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$/; > print $1; > ################# > > I've python 2.5.2 on Ubuntu 8.04. > any idea? If it will help some smarter person identify the problem, it can be simplified to this: re.findall('[^X]*((?:0*X+0*)+\s*a*\s*(?:0*X+0*\s*)*)([^X]*)$', "XXXXXXXXXXXXXXXXX (X" ) This doesn't actually hang, it just takes a long time. The time taken increases quickly as the chain of X's gets longer. HTH -- To email me, substitute nowhere->spamcop, invalid->net. From sjmachin at lexicon.net Thu Jun 26 20:12:45 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 26 Jun 2008 17:12:45 -0700 (PDT) Subject: Need help capturing output of re.search References: <771ef68a-d976-4f61-a3cc-7ed56fddc756@k37g2000hsf.googlegroups.com> <9757288e-0b48-46ee-8fd0-0adf36bbd710@p39g2000prm.googlegroups.com> <5fd345b7-6b32-4d45-8c55-662684adf5e9@34g2000hsf.googlegroups.com> Message-ID: <8e0883f9-f36d-4d62-a1a4-4cd66163a1cc@s21g2000prm.googlegroups.com> On Jun 27, 10:01 am, joemacbusin... at yahoo.com wrote: > >You may like to read this:http://www.amk.ca/python/howto/regex/ > > This is a good resource. Thank you. > Someone else pointed out that I needed to change the > > if reCheck == "None": > > to > > if reCheck == None: # removed the "s "Somebody else" should indeed remain anonymous if they told you that. Use if reCheck is None: or even better: if not reCheck: It's not obvious from your response if you got these points: (1) re.match, not re.search (2) filename.startswith does your job simply and more understandably From simon at brunningonline.net Fri Jun 13 02:56:15 2008 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 13 Jun 2008 07:56:15 +0100 Subject: e-value In-Reply-To: References: Message-ID: <8c7f10c60806122356k4809191iaaf96b855b1f23c1@mail.gmail.com> On Fri, Jun 13, 2008 at 7:45 AM, Beema shafreen wrote: > ... gi, seq, e_value = line.strip().split('\t') At this point, e_value contains a string value. You'll need to convert it to a float before you can meaningfully compare it. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From geoff.bache at jeppesen.com Wed Jun 25 08:01:14 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Wed, 25 Jun 2008 05:01:14 -0700 (PDT) Subject: Windows process ownership trouble Message-ID: <3fcf363f-3685-4b7b-8ba5-1ffc32e58af7@m44g2000hsc.googlegroups.com> Am currently being very confused over the following code on Windows import subprocess, os file = open("filename", "w") try: proc = subprocess.Popen("nosuchprogram", stdout=file) except OSError: file.close() os.remove("filename") This produces the following exception: Traceback (most recent call last): File "C:\processown.py", line 10, in os.remove("filename") WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'filename' How can it be in use by another process? The process didn't even start, right? Would appreciate some help: is this a Python bug, or a Windows bug, or just me being confused...? From antonxx at gmx.de Fri Jun 13 04:23:41 2008 From: antonxx at gmx.de (anton) Date: Fri, 13 Jun 2008 08:23:41 +0000 (UTC) Subject: using re module to find References: <5aeb32bd-923f-4b98-952b-06097ac8479d@v1g2000pra.googlegroups.com> Message-ID: John Machin lexicon.net> writes: > > On Jun 12, 7:11 pm, anton wrote: > > Hi, > > > > I want to replace all occourences of " by \" in a string. > > > > But I want to leave all occourences of \" as they are. > > > > The following should happen: > > > > this I want " while I dont want this \" ... cut text off > What you want is: > > >> import re > >> text = r'frob this " avoid this \", OK?' > >>> text > 'frob this " avoid this \\", OK?' > >> re.sub(r'(? frob this \\" avoid this \\", OK?' > >> > > HTH, > John > -- > http://mail.python.org/mailman/listinfo/python-list > > First.. thanks John. The whole problem is discussed in http://docs.python.org/dev/howto/regex.html#the-backslash-plague in the section "The Backslash Plague" Unfortunately this is *NOT* mentioned in the standard python documentation of the re module. Another thing which will always remain strange to me, is that even if in the python doc of raw string: http://docs.python.org/ref/strings.html its written: "Specifically, a raw string cannot end in a single backslash" s=r"\\" # works fine s=r"\" # works not (as stated) But both ENDS IN A SINGLE BACKSLASH ! The main thing which is hard to understand is: If a raw string is a string which ignores backslashes, then it should ignore them in all circumstances, or where could be the problem here (python parser somewhere??). Bye Anton From sjmachin at lexicon.net Thu Jun 19 19:14:40 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 19 Jun 2008 16:14:40 -0700 (PDT) Subject: Why no output from xml.dom.ext.PrettyPrint? References: Message-ID: <19999864-b381-41b5-90fa-7e3cc3996d65@w8g2000prd.googlegroups.com> On Jun 20, 7:17 am, kj wrote: > OK, the following should work but doesn't, and I can't figure out > why: > > >>> from xml.marshal.generic import dumps > >>> dumps( ( 1, 2.0, 'foo', [3,4,5] ) ) > > '12.0foo345' > > >>> from xml.dom.ext import PrettyPrint > >>> PrettyPrint( dumps( ( 1, 2.0, 'foo', [3,4,5] ) ) ) > >>> import sys > >>> PrettyPrint( dumps( ( 1, 2.0, 'foo', [3,4,5] ) ), sys.stdout ) > > Why am I seeing no output from PrettyPrint? > You need to ask whoever you got your xml package from. In standard- issue Python 2.5.2, there is an xml package with xml.dom, but it contains no xml.dom.ext nor an xml.marshal. From hongyuan1306 at gmail.com Tue Jun 10 05:28:11 2008 From: hongyuan1306 at gmail.com (Yuan HOng) Date: Tue, 10 Jun 2008 17:28:11 +0800 Subject: Py2exe and name space package Message-ID: <91320d220806100228h771c4edn3ae88b26920029ad@mail.gmail.com> Hi, I used to freeze my application into Windows executibles using py2exe. Lately I started using several zope packages in my application, like zope.interface. Now the freezed program can't run properly. Like the following example shows: My setup.py file: from distutils.core import setup import py2exe setup(name='test', zipfile=None, console=[ { 'script': 'main.py', } ]) The main.py test code: from zope.interface import Interface print Interface During the freezing process, the following warning is shown: *** copy dlls *** copying c:\Python25\lib\site-packages\py2exe-0.6.6-py2.5-win32.egg\py2exe\run.exe -> C:\temp\dist\main.exe The following modules appear to be missing ['pkg_resources', 'zope.interface'] Running main.exe gives me an import Error. C:\temp\dist>main.exe Traceback (most recent call last): File "main.py", line 1, in ImportError: No module named interface What should I do to make py2exe recognize and include zope.interface in the binary distribution? Thanks. -- Hong Yuan ????????? ??????????? http://www.homemaster.cn From bkasterm at gmail.com Mon Jun 16 06:34:06 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Mon, 16 Jun 2008 03:34:06 -0700 (PDT) Subject: String Concatenation O(n^2) (was: Re: Explaining Implementing a Binary Search Tree.) References: Message-ID: Summary: can't verify big O claim, how to properly time this? On Jun 15, 2:34 pm, "Terry Reedy" wrote: > "Bart Kastermans" wrote in message > > news:ae91857d-ea63-4204-9fc3-251049adee98 at k13g2000hse.googlegroups.com... > |I wrote a binary search tree in python, explaining as I was doing it > | how and why I did it. I am very interested in receiving comments on > | the code, process, and anything else that will improve my coding or > | writing. > | > | I wrote this all up in my blog at: > | > |http://kasterma.wordpress.com/2008/06/15/implementing-a-binary-search... > | > | The code of the class has been copied below, but the description of > | the process (mostly an attempt at approaching test driving development > | for as far as I understand the term) has not been copied. > | > | Any and all comments are appreciated. > | > | Best, > | Bart > | > | *********** python code ************************ > | > | > | import re > | > | class BSTree: > | def __init__ (self, value = None): > | self.value = value > | self.left = None > | self.right = None > > There are two possible approaches. > 1. Define 1 tree class that is also used for subtrees -- what you did. > Complication: self.value of root node can be none, so you constantly > have to check self.value for None even though only possible for root node. > 2. Define tree class and node class. This had other complications, but > removes that above and makes str easier. tree.str = '(' str(rootnode) ')' > and node.str= self.value '(' str(self.left) ')' '(' str(self.right) ')'. > > If use '' instead of None, no conditionals are needed. (This might apply > partly to your version as well.) Or define class NullTree with a singleton > instance with no attributes and a str method returning '' and an inOrder > method yielding nothing. This would also eliminate the condifionals in the > inOrder method. Not sure what is best. With a good test suite, it is easy > to make sure alternative implementations 'work' before testing for speed. Thanks for the idea. I would expect the separation to lead to somewhat more code, but all the "checking the root" code would be separated out in the tree class. The node class would be very smooth. I'll try this when I have some time (today I spend my "alloted" programming time on what is below). (also the comment about inOrder returning a generator was because I tried to figure it out, failed, and then got enough by doing it without yield. I forgot to bring my comment in line with my code. A generator would certainly be nicer, and I'll work at understanding your suggestion for it.) > > | def __str__ (self): > > string appending is an O(n**2) operations. The usual idiom, applied here, > would be slist = ['('], slist.append(str(self.value)), .... return > ''.join(slist). In other words, collect list of pieces and join at end. This is interesting. I had never attempted to verify a big O statement before, and decided that it would be worth trying. So I wrote some code to collect data, and I can't find that it goes quadratic. I have the graph at http://kasterma.wordpress.com/2008/06/16/complexity-of-string-concatenation/ It looks piecewise linear to me. The code I used to collect the data is as follows: ************************************************************************* import time NUMBER = 100 # number of strings to concatenate at given length JUMP = 500 # jump (and start length) of length of strings END = 100001 # longest length string considered def randomString (length): """ returns a random string of letters from {a,b,c,d} of length """ string = "" for i in range (0,length): string += choice ("abcd") return string def randomStrings (number, length): """ returns an array of number random strings all of length """ array = [] for i in range (0, number): array.append (randomString (length)) return array TimingData = [] for length in range (JUMP, END, JUMP): array1 = randomStrings (NUMBER, length) array2 = randomStrings (NUMBER, length) starttime = time.clock () for i in range (0, NUMBER): string = array1 [i] + array2 [i] endtime = time.clock () print "length", length, "done" TimingData.append ([length, 1000* (endtime-starttime)]) # to get a better looking graph multiply by 1000 sagefile = open ('stringConcatGraph.sage', "w") sagefile.write ("points =" + str (TimingData) + "\n") sagefile.write ("graph = line (points)\n") sagefile.write ("graph.show ()\n") sagefile.close () From dullrich at sprynet.com Mon Jun 30 15:43:45 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Mon, 30 Jun 2008 14:43:45 -0500 Subject: ask for a RE pattern to match TABLE in html References: <6a4f17690806260653i136681bdsabe0f6bb1dfab67b@mail.gmail.com> <62f752f3-d840-42de-a414-0d56d15d7c5a@w4g2000prd.googlegroups.com> <50285840-7601-41be-aa3d-865f46fe85c6@56g2000hsm.googlegroups.com> Message-ID: In article <50285840-7601-41be-aa3d-865f46fe85c6 at 56g2000hsm.googlegroups.com>, Dan wrote: > On Jun 27, 1:32 pm, "David C. Ullrich" wrote: > > In article > > <62f752f3-d840-42de-a414-0d56d15d7... at w4g2000prd.googlegroups.com>, > > Jonathan Gardner wrote: > > > > > On Jun 26, 3:22 pm, MRAB wrote: > > > > Try something like: > > > > > > re.compile(r'.*?', re.DOTALL) > > > > > So you would pick up strings like "
    foo > > td>
    "? I doubt that is what oyster wants. > > > > I asked a question recently - nobody answered, I think > > because they assumed it was just a rhetorical question: > > > > (i) It's true, isn't it, that it's impossible for the > > formal CS notion of "regular expression" to correctly > > parse nested open/close delimiters? > > Yes. For the proof, you want to look at the pumping lemma found in > your favorite Theory of Computation textbook. Ah, thanks. Don't have a favorite text, not having any at all. But wikipedia works - what I found at http://en.wikipedia.org/wiki/Pumping_lemma_for_regular_languages was pretty clear. (Yes, it's exactly that \1, \2 stuff that convinced me I really don't understand what one can do with a Python regex.) > > > > (ii) The regexes in languages like Python and Perl include > > features that are not part of the formal CS notion of > > "regular expression". Do they include something that > > does allow parsing nested delimiters properly? > > So, I think most of the extensions fall into syntactic sugar > (certainly all the character classes \b \s \w, etc). The ability to > look at input without consuming it is more than syntactic sugar, but > my intuition is that it could be pretty easily modeled by a > nondeterministic finite state machine, which is of equivalent power to > REs. The only thing I can really think of that is completely non- > regular is the \1 \2, etc syntax to match previously match strings > exactly. But since you can't to an arbitrary number of them, I don't > think its actually context free. (I'm not prepared to give a proof > either way). Needless to say that even if you could, it would be > highly impractical to match parentheses using those. > > So, yeah, to match arbitrary nested delimiters, you need a real > context free parser. > > > > > -- > > David C. Ullrich > > > -Dan -- David C. Ullrich From xng at xs4all.nl Wed Jun 18 11:57:47 2008 From: xng at xs4all.nl (Martin P. Hellwig) Date: Wed, 18 Jun 2008 17:57:47 +0200 Subject: Looking for lots of words in lots of files In-Reply-To: References: Message-ID: <485930cf$0$11744$e4fe514c@dreader19.news.xs4all.nl> Kris Kennaway wrote: > > If you can't use an indexer, and performance matters, evaluate using > grep and a shell script. Seriously. > > grep is a couple of orders of magnitude faster at pattern matching > strings in files (and especially regexps) than python is. Even if you > are invoking grep multiple times it is still likely to be faster than a > "maximally efficient" single pass over the file in python. This > realization was disappointing to me :) > > Kris Adding to this: Then again, there is nothing wrong with wrapping grep from python and revert to a pure python 'solution' if the system has no grep. Reinventing the wheel is usually only practical if the existing ones aren't round :-) -- mph From fetchinson at googlemail.com Tue Jun 3 13:10:38 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Tue, 3 Jun 2008 10:10:38 -0700 Subject: Keep a script running in the background In-Reply-To: <210b7fc6-ed52-461d-8b53-455e247d7a29@e39g2000hsf.googlegroups.com> References: <210b7fc6-ed52-461d-8b53-455e247d7a29@e39g2000hsf.googlegroups.com> Message-ID: > I need a script to keep running in the background after it's loaded > some data. It will make this data available to the main program in the > form of a dictionary, but I don't want to reload the calculated data > every time the user needs it via the main program. > > I won't be working with an UI, hope that can be made easily in Python > somehow. I'm not sure I understand exactly what you want but you might find these daemonize examples useful from the cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From Joshua.R.English at gmail.com Mon Jun 23 15:18:15 2008 From: Joshua.R.English at gmail.com (Josh English) Date: Mon, 23 Jun 2008 12:18:15 -0700 (PDT) Subject: learning unit testing in python References: Message-ID: <41389b77-423c-4ec8-9eb0-6b9a0e025939@l28g2000prd.googlegroups.com> A good starting point is Mark Pilgrim's Dive Into Python. http://www.diveintopython.org/unit_testing/index.html Josh On Jun 23, 7:55 am, Alex wrote: > Hi all. > > I'd like learn some basic unit testing with python. > I red some articles about different testing framework like unittest or > nose, but I'm a bit confused: what is the best choice? I'm not a > professional developer (I'm a SEO) but I belive that unit testing is a > good and pragmatic way to produce working software, so I'd like to > find something really simple ad straightforward because I don't have > to manage big programming projects. > > Thanks in advance, > > Alex From kyrie at uh.cu Thu Jun 12 08:33:33 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Thu, 12 Jun 2008 08:33:33 -0400 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> <484e3526$0$30894$426a74cc@news.free.fr> <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> <783c55ec-a294-4600-91d9-4a0d78632c49@t12g2000prg.googlegroups.com> <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> <484f880c$0$6412$426a74cc@news.free.fr> Message-ID: <1213274013.4851179d0a274@comuh.uh.cu> Quoting Dennis Lee Bieber : > On Wed, 11 Jun 2008 21:54:33 -0700 (PDT), Michele Simionato > declaimed the following in > comp.lang.python: > > > > > It looks like in French (as in Italian) *experimented* has the > > meaning of "tried and tested on the field" when applied to a > > person. > > > > > Fascinating Spanish also. I translate "experimentado" to "experienced", perhaps because I had seen it before, but I never imagined that "experimented" would be wrong. Fascinating x2 -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie From jzakiya at gmail.com Fri Jun 13 13:38:36 2008 From: jzakiya at gmail.com (jzakiya) Date: Fri, 13 Jun 2008 10:38:36 -0700 (PDT) Subject: Ultimate Prime Sieve -- Sieve Of Zakiya (SoZ) References: <5ebb27cd-e938-4f06-9aad-4ea056b851a9@c65g2000hsa.googlegroups.com> Message-ID: <1a768188-bbb8-4f0e-919a-76ac6bc0a336@p25g2000hsf.googlegroups.com> On Jun 13, 1:12?pm, jzakiya wrote: > This is to announce the release of my paper "Ultimate Prime Sieve -- > Sieve of Zakiiya (SoZ)" in which I show and explain the development of > a class of Number Theory Sieves to generate prime numbers. ? I used > Ruby 1.9.0-1 as my development environment on a P4 2.8 Ghz laptop. > > You can get the pdf of my paper and Ruby and Python source from here: > > http://www.4shared.com/dir/7467736/97bd7b71/sharing.html > > Below is a sample of one of the simple prime generators. I did a > Python version of this in my paper (see Python source too). ?The Ruby > version below is the minimum array size version, while the Python has > array of size N (I made no attempt to optimize its implementation, > it's to show the method). > > class Integer > ? ?def primesP3a > ? ? ? # all prime candidates > 3 are of form ?6*k+1 and 6*k+5 > ? ? ? # initialize sieve array with only these candidate values > ? ? ? # where sieve contains the odd integers representatives > ? ? ? # convert integers to array indices/vals by ?i = (n-3)>>1 = > (n>>1)-1 > ? ? ? n1, n2 = -1, 1; ?lndx= (self-1) >>1; ?sieve = [] > ? ? ? while n2 < lndx > ? ? ? ? ?n1 +=3; ? n2 += 3; ? sieve[n1] = n1; ?sieve[n2] = n2 > ? ? ? end > ? ? ? #now initialize sieve array with (odd) primes < 6, resize array > ? ? ? sieve[0] =0; ?sieve[1]=1; ?sieve=sieve[0..lndx-1] > > ? ? ? 5.step(Math.sqrt(self).to_i, 2) do |i| > ? ? ? ? ?next unless sieve[(i>>1) - 1] > ? ? ? ? ?# p5= 5*i, ?k = 6*i, ?p7 = 7*i > ? ? ? ? ?# p1 = (5*i-3)>>1; ?p2 = (7*i-3)>>1; ?k = (6*i)>>1 > ? ? ? ? ?i6 = 6*i; ?p1 = (i6-i-3)>>1; ?p2 = (i6+i-3)>>1; ?k = i6>>1 > ? ? ? ? ?while p1 < lndx > ? ? ? ? ? ? ?sieve[p1] = nil; ?sieve[p2] = nil; ?p1 += k; ?p2 += k > ? ? ? ? ?end > ? ? ? end > ? ? ? return [2] if self < 3 > ? ? ? [2]+([nil]+sieve).compact!.map {|i| (i<<1) +3 } > ? ?end > end > > def primesP3(val): > ? ? # all prime candidates > 3 are of form ?6*k+(1,5) > ? ? # initialize sieve array with only these candidate values > ? ? n1, n2 = 1, 5 > ? ? sieve = [False]*(val+6) > ? ? while ?n2 < val: > ? ? ? ? n1 += 6; ? n2 += 6; ?sieve[n1] = n1; ? sieve[n2] = n2 > ? ? # now load sieve with seed primes 3 < pi < 6, in this case just 5 > ? ? sieve[5] = 5 > > ? ? for i in range( 5, int(ceil(sqrt(val))), 2) : > ? ? ? ?if not sieve[i]: ?continue > ? ? ? ?# ?p1= 5*i, ?k = 6*i, ?p2 = 7*i, > ? ? ? ?p1 = 5*i; ?k = p1+i; ?p2 = k+i > ? ? ? ?while p2 <= val: > ? ? ? ? ? sieve[p1] = False; ?sieve[p2] = False; ?p1 += k; ?p2 += k > ? ? ? ?if p1 <= val: ?sieve[p1] = False > > ? ? primes = [2,3] > ? ? if val < 3 : return [2] > ? ? primes.extend( i for i in range(5, val+(val&1), 2) ?if sieve[i] ) > > ? ? return primes > > Now to generate an array of the primes up to some N just do: > > Ruby: ? ?10000001.primesP3a > Python: primesP3a(10000001) > > The paper presents benchmarks with Ruby 1.9.0-1 (YARV). ?I would love > to see my various prime generators benchmarked with optimized > implementations in other languages. ?I'm hoping Python gurus will do > better than I, though the methodology is very very simple, since all I > do is additions, multiplications, and array reads/writes. > > Have fun with the code. ?;-) > CORRECTION: http://cr.yp.to/primegen.html NOT "primesgen" Jabari Zakiya From timr at probo.com Sat Jun 28 00:30:50 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 28 Jun 2008 04:30:50 GMT Subject: Mako vs. Cheetah? References: <4862f57c$0$11621$607ed4bc@cv.net> <4863bf9c$0$14081$c3e8da3@news.astraweb.com> Message-ID: "John Salerno" wrote: > >Is it correct to say that Mako allows you to embed Python code within HTML, >whereas Cheetah requires a certain amount of "tweaking" of Python code so >that it isn't really code you could just run independently in the >interpreter? > >I'm getting that impression from what I see so far. What gives you that impression? I'm just curious. Other than the special characters used, my impression is that the two are far more similar than they are different. As I posted on one of the mailing lists this week, the most important criteria in your choice of a templating system really is personal preference. Personally, I really like Cheetah. I find it simple and intuitive, with a minimum of syntax interference. However, many people believe it violates the "separation of presentation and computation" rule too much, and that's just fine. Others really like the TAL scheme in Zope. For my taste, TAL just requires too much non-essential syntax; it interferes with the reading of the page. So, the folks who like TAL can go ahead and be productive with TAL, and I'll keep on being productive with Cheetah. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bearophileHUGS at lycos.com Mon Jun 23 09:46:04 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 23 Jun 2008 06:46:04 -0700 (PDT) Subject: Sending arrays of a structure as an argument via ctypes References: Message-ID: <6307e79b-be4e-410a-9d84-6200dafc5e1c@k37g2000hsf.googlegroups.com> Knut Saua Mathiesen: > Any help? :p My faster suggestion is to try ShedSkin, it may help you produce a fast enough extension. If ShedSkin doesn't compile it, its author (Mark) may be quite willing to help. bye, bearophile From paddy3118 at googlemail.com Fri Jun 13 00:42:44 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 12 Jun 2008 21:42:44 -0700 (PDT) Subject: Mapping None. Why? References: <6bdbtuF3aqe92U1@mid.uni-berlin.de> <6bddafF3b1u2tU1@mid.uni-berlin.de> Message-ID: On Jun 12, 8:55 pm, "Diez B. Roggisch" wrote: > > And the OP's question was about map not being conforming to the > definition on wikipedia - which I don't think it's not. It is not > defined what map is to do with None (or NULL or nil or... ) as argument. > > Diez Oh no! Sorry to give that impression. I don't think that map should be like what Wikipedia says, I was just looking for another example of an implementation that might mention the behaviour. I just want to know the thoughts behind this behaviour in the Python map. - Paddy. From kirk at daycos.com Wed Jun 18 10:48:57 2008 From: kirk at daycos.com (Kirk Strauser) Date: Wed, 18 Jun 2008 09:48:57 -0500 Subject: question relateding to parsing dbf files. References: Message-ID: <87wskm6bom.fsf@internal.daycos.com> At 2008-06-18T12:50:20Z, "Krishnakant Mane" writes: > hello all. > I need to parse some dbf files through python. > the reason being that I have to migrate some old data from dbf files > to postgresql. > all that I need to know is if some one has got a working code sample > using dbfpy. > I found this module suitable for my work but can't figure out how to use it. > else, if there is any other module, please recommend so. > happy hacking. > Krishnakant. Does it have to by in Python? I host this project, written in C++: http://honeypot.net/project/xbasetopg . If that's too complicated, I've written a replacement in straight C but I haven't published it yet. I use these programs to sync our legacy FoxPro database to our new PostgreSQL servers on an hourly basis. Syncing 4GB of data tables about 10 minutes. -- Kirk Strauser The Day Companies From gherron at islandtraining.com Thu Jun 5 20:17:07 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 05 Jun 2008 17:17:07 -0700 Subject: Newb question: underscore In-Reply-To: References: Message-ID: <48488203.8080105@islandtraining.com> Skye wrote: > What is this doing? > > print >> fd, _(__doc__) > > > I'm guessing line-splitting __doc__ into a list, but what's that > leading underscore do? > It's calling a function with a single argument, like sqrt(x), except the function is named _ and the argument is named __doc__. The underscores have no special significance here, but they do make the code hard to read. The first part of the statement directs the print to send the output to a file, named fd, which was presumably opened earlier ... but I don't think that was part of your question. Gary Herron > Thanks! > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Mon Jun 2 23:53:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 03 Jun 2008 00:53:11 -0300 Subject: mmap class has slow "in" operator References: <483F2B61.6050306@FreeBSD.org> Message-ID: En Thu, 29 May 2008 19:17:05 -0300, Kris Kennaway escribi?: > If I do the following: > > def mmap_search(f, string): > fh = file(f) > mm = mmap.mmap(fh.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ) > > return mm.find(string) > > def mmap_is_in(f, string): > fh = file(f) > mm = mmap.mmap(fh.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ) > > return string in mm > > then a sample mmap_search() call on a 50MB file takes 0.18 seconds, but > the mmap_is_in() call takes 6.6 seconds. Is the mmap class missing an > operator and falling back to a slow default implementation? Presumably > I can implement the latter in terms of the former. Looks like you should define the sq_contains member in mmap_as_sequence, and the type should have the Py_TPFLAGS_HAVE_SEQUENCE_IN flag set (all in mmapmodule.c) -- Gabriel Genellina From geoff.bache at jeppesen.com Thu Jun 26 11:25:40 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Thu, 26 Jun 2008 08:25:40 -0700 (PDT) Subject: Windows process ownership trouble References: <3fcf363f-3685-4b7b-8ba5-1ffc32e58af7@m44g2000hsc.googlegroups.com> Message-ID: <990516b7-f7ef-464a-97d0-fd55a0354ab4@y21g2000hsf.googlegroups.com> Thanks Tim, very helpful again. I've now reported this as http://bugs.python.org/issue3210 and implemented your suggested workaround. Regards, Geoff On Jun 25, 9:19 pm, Tim Golden wrote: > geoffbache wrote: > > Am currently being very confused over the following code on Windows > > > import subprocess, os > > > file = open("filename", "w") > > try: > > proc = subprocess.Popen("nosuchprogram", stdout=file) > > except OSError: > > file.close() > > os.remove("filename") > > Forgot to say: slightly awkward, but you can work around > it like this: > > > import os > import subprocess > > f = open ("filename", "w") > try: > proc = subprocess.Popen ("blah", stdout=f) > except OSError: > os.close (f.fileno ()) > > os.remove ("filename") > > > > TJG From woodygar at sky.com Thu Jun 5 09:43:56 2008 From: woodygar at sky.com (garywood) Date: Thu, 5 Jun 2008 14:43:56 +0100 Subject: No subject Message-ID: <000c01c8c712$347dd660$1300a8c0@Home> Hi there. So I have a challenge in the Python book I am using (python programming for the absolute beginner) that tells me to improve an ask_number() function, so that it can be called with a step value, and I havn't been able to find out yet what's meant by a step value, but i'll keep looking of course. I'd just be grateful if someone could illimunate this for me. def ask_number(question, low, high): """Ask for a number within a range.""" response = None while response not in range(low, high): response = int(raw_input(question)) return response Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sun Jun 15 13:52:56 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Jun 2008 19:52:56 +0200 Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> Message-ID: ram.rachum at gmail.com wrote: > I have a physical system set up in which a body is supposed to > accelerate and to get very close to lightspeed, while never really > attaining it. After approx. 680 seconds, Python gets stuck and tells > me the object has passed lightspeed. I put the same equations in > Mathematica, again I get the same mistake around 680 seconds. So I > think, I have a problem with my model! Then I pump up the > WorkingPrecision in Mathematica to about 10. I run the same equations > again, and it works! At least for the first 10,000 seconds, the object > does not pass lightspeed. That the values are possible doesn't mean that you can trust them. > I concluded that I need Python to work at a higher precision. How is WorkingPrecision defined? Python floats have about 16 significant digits in base 10, so at first glance I would guess that you switched to a /lower/ precision. But I've come to agree with Christian that it would be good to show your model to a physics and/or numerical maths expert. Perhaps you can find a way for the errors to cancel out rather than accumulate. Peter From aweraw at gmail.com Tue Jun 10 20:51:53 2008 From: aweraw at gmail.com (Aidan) Date: Wed, 11 Jun 2008 10:51:53 +1000 Subject: Dynamic HTML from Python Script In-Reply-To: <484f151c$0$5009$607ed4bc@cv.net> References: <484f151c$0$5009$607ed4bc@cv.net> Message-ID: <484f21aa$1@dnews.tpgi.com.au> asdf wrote: > I have a python script whose output i want to dynamically display > on a webpage which will be hosted using Apache. How do I do that? > > > thanks Well, there's a few ways you could approach it. You could create a cgi program from your script - this is probably the solution you're looking for. You could have the script run periodically and create a static html file in the webroot... this would be acceptable, maybe preferable, if the output from your script doesn't change frequently. There's also more advanced ways you can make python code run in a web-service. Cherrypy comes to mind, as well as the myriad python MVC frameworks. From leechat2001 at gmail.com Mon Jun 30 16:11:59 2008 From: leechat2001 at gmail.com (leechat2001 at gmail.com) Date: Mon, 30 Jun 2008 13:11:59 -0700 (PDT) Subject: URLLIb2 problem Message-ID: <156e077b-1305-476c-885f-0b798f4ce699@s21g2000prm.googlegroups.com> I am trying to write somecode of this kind :) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) opener.addheaders = [('User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14'), ('Accept','text/xml,application/xml,application/xhtml+xml,text/ html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'),('Accept- Language','en-us,en;q=0.5'),('Accept-Encoding','gzip,deflate'), ('Accept-Charset','ISO-8859-1,utf-8;q=0.7,*;q=0.7'),('Keep- Alive','300'),('Connection','keep-alive'),('Content-Type','application/ x-www-form-urlencoded')] urllib2.install_opener(opener) fu = urllib2.urlopen('http://www.google.com') print fu.read() I am not able to open any webpage as the content is junk characters.something like below..what could be the problem????????????? if I don't install the 'opener' I get everything properly ?]?s?H? ?T? ?Cj2????x:&? ?c???????~J ?????I??w???????ZB??q?? ?T9?R???????????4 ?7?????V??.i??"?????????W>? ??y?=vm??)?????6??y???????9????l????>?????????(?g[??? L?S??????????e???????GcS??w s????/??G??|???9??F`??????*?????BV,????????o??pzn??;?y9?4 ???f????z8???b?n??K}|? From sir.heyhey at gmail.com Tue Jun 3 10:12:53 2008 From: sir.heyhey at gmail.com (Ivan Velev) Date: Tue, 3 Jun 2008 07:12:53 -0700 (PDT) Subject: need help with timezone conversion (unexpected side effect of time.mktime ??) Message-ID: Hello, Minimal example below - it gives me different output if I comment / uncomment the extra time.mktime call - note that this call is not related in any way to main logic flow. When "problematicStamp = ..." is commented I get gmtStamp: 1130634600.0 when I uncomment that line I get gmtStamp: 1130631000.0 I have tried this on a couple of Linux machines and it was reproducible everyewhere. One of those machines has the following Python version (If needed I can provide more details) > Python 2.5 (r25:51908, Mar 26 2007, 23:34:03) Any idea what' happening there ? Ivan --------------- import time, os # to see the difference, uncomment this line # problematicStamp = time.mktime((2004, 10, 30, 4, 10, 0, 6, 303, -1)) os.putenv("TZ", "Europe/Sofia") time.tzset() gmtStamp = time.mktime((2005, 10, 30, 3, 10, 0, 6, 303, -1)) print "gmtStamp:", gmtStamp From kyrie at uh.cu Sun Jun 29 01:11:45 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Sun, 29 Jun 2008 01:11:45 -0400 Subject: Why is recursion so slow? In-Reply-To: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> Message-ID: <1214716305.4867199171034@comuh.uh.cu> Quoting slix : > Recursion is awesome for writing some functions, like searching trees > etc but wow how can it be THAT much slower for computing fibonacci- > numbers? The problem is not with 'recursion' itself, but with the algorithm: > def fibr(nbr): > if nbr > 1: > return fibr(nbr-1) + fibr(nbr-2) > if nbr == 1: > return 1 > if nbr == 0: > return 0 If you trace, say, fibr(5), you'll find that your code needs to compute fibr(4) and fibr(3), and to compute fibr(4), it needs to compute fibr(3) and fibr(2). As you can see, fibr(3), and it whole subtree, is computed twice. That is enough to make it an exponential algorithm, and thus, untractable. Luckily, the iterative form is pretty readable and efficient. If you must insist on recursion (say, perhaps the problem you are solving cannot be solved iteratively with ease), I'd suggest you to take a look at 'dynamic programming', or (easier but not necesarily better), the 'memoize' disgn pattern. > is the recursive definition counting fib 1 to fib x-1 for every x? Yes - that's what the algorithm says. (Well, actually, the algorithm says to count more than once, hence the exponential behaviour). The memoize patter could help in this case. > is > that what lazy evaluation in functional languages avoids thus making > recursive versions much faster? Not exactly... Functional languages are (or should be) optimized for recursion, but if the algorithm you write is still exponential, it will still take a long time. > is recursive fibonacci in haskell as fast as an imperative solution in > a procedural language? > [...] > i found a version in Clojure that is superfast: I've seen the haskell implementation (quite impressive). I don't know Clojure (is it a dialect of Lisp?), but that code seems similar to the haskell one. If you look closely, there is no recursion on that code (no function calls). The haskell code works by defining a list "fib" as "the list that starts with 0,1, and from there, each element is the sum of the element on 'fib' plus the element on 'tail fib'). The lazy evaluation there means that you can define a list based on itself, but there is no recursive function call. Cheers, (I'm sleepy... I hope I made some sense) -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie From alex at moreati.org.uk Tue Jun 17 18:15:33 2008 From: alex at moreati.org.uk (moreati) Date: Tue, 17 Jun 2008 15:15:33 -0700 (PDT) Subject: Calling pcre with ctypes Message-ID: <947df973-8bae-4364-bf76-64a9a7d4a51f@s50g2000hsb.googlegroups.com> Recently I discovered the re module doesn't support POSIX character classes: Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> r = re.compile('[:alnum:]+') >>> print r.match('123') None So I thought I'd try out pcre through ctypes, to recreate pcredemo.c in python. The c code is at: http://vcs.pcre.org/viewvc/code/trunk/pcredemo.c?view=markup Partial Python code is below I'm stuck, from what I can tell a c array, such as: int ovector[OVECCOUNT]; translates to ovector = ctypes.c_int * OVECOUNT but when I pass ovector to a function I get the traceback $ python pcredemo.py [a-z] fred Traceback (most recent call last): File "pcredemo.py", line 65, in compiled_re, None, subject, len(subject), 0, 0, ovector, OVECOUNT ctypes.ArgumentError: argument 7: : Don't know how to convert parameter 7 What is the correct way to construct and pass ovector? With thanks, Alex # PCRE through ctypes demonstration program import ctypes import getopt import sys import pcre_const OVECOUNT = 30 # Should be a multiple of 3 pcre = ctypes.cdll.LoadLibrary('libpcre.so') compiled_re = None error = ctypes.c_char_p() pattern = '' subject = '' name_table = ctypes.c_ubyte() erroffset = ctypes.c_int() find_all = 0 namecount = 0 name_entry_size = 0 ovector = ctypes.c_int * OVECOUNT options = 0 # First, sort out the command line. There is only one possible option at # the moment, "-g" to request repeated matching to find all occurrences, # like Perl's /g option. We set the variable find_all to a non-zero value # if the -g option is present. Apart from that, there must be exactly two # arguments. opts, args = getopt.getopt(sys.argv[1:], 'g') for o, v in opts: if o == '-g': find_all = 1 # After the options, we require exactly two arguments, which are the # pattern, and the subject string. if len(args) != 2: print 'Two arguments required: a regex and a subject string' sys.exit(1) pattern = args[0] subject = args[1] subject_length = len(subject) # Now we are going to compile the regular expression pattern, and handle # and errors that are detected. compiled_re = pcre.pcre_compile( pattern, options, ctypes.byref(error), ctypes.byref(erroffset), None ) From circularfunc at yahoo.se Wed Jun 11 18:39:20 2008 From: circularfunc at yahoo.se (cirfu) Date: Wed, 11 Jun 2008 15:39:20 -0700 (PDT) Subject: web2py forum or mailing list? References: Message-ID: web2py > django mailing list: http://groups.google.com/group/web2py From exarkun at divmod.com Mon Jun 23 13:46:12 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 23 Jun 2008 13:46:12 -0400 Subject: Using Python to run SSH commands on a remote server In-Reply-To: <03a078c8$0$3229$c3e8da3@news.astraweb.com> Message-ID: <20080623174612.4714.2084698320.divmod.quotient.12235@ohm> On Mon, 23 Jun 2008 13:30:55 -0400, John Salerno wrote: >Generally speaking, what tools would I use to do this? Is there a built-in >module for it? I looked at the telnetlib module, but the documentation >wasn't really complete enough for me to get a good idea of it. Is Telnet and >SSH even the same thing? Telnet and SSH are different things. There's nothing in the standard library for making an SSH connection (aside from the process control libraries, which let you run an external SSH client in a child process). > >Basically, I want to write a script that will automate the process of making >all .py files on my web server executable (chmod 755, or something similar). There are several third-party SSH libraries, eg Twisted Conch and Paramiko. Jean-Paul From aweraw at gmail.com Thu Jun 12 10:39:49 2008 From: aweraw at gmail.com (Aidan) Date: Fri, 13 Jun 2008 00:39:49 +1000 Subject: Summing a 2D list In-Reply-To: References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <6bcokhF3b2mo7U1@mid.uni-berlin.de> <485131a1$0$11175$c3e8da3@news.astraweb.com> Message-ID: Mark wrote: > John, it's a QuerySet coming from a database in Django. I don't know > enough about the structure of this object to go into detail I'm > afraid. > > Aidan, I got an error trying your suggestion: 'zip argument #2 must > support iteration', I don't know what this means! well, if we can create 2 iterable sequences one which contains the user the other the scores, it should work the error means that the second argument to the zip function was not an iterable, such as a list tuple or string can you show me the lines you're using to retrieve the data sets from the database? then i might be able to tell you how to build the 2 lists you need. > Thanks to all who have answered! Sorry I'm not being very specific! From hwcowan at hotmail.com Mon Jun 23 12:10:47 2008 From: hwcowan at hotmail.com (hwcowan at hotmail.com) Date: Mon, 23 Jun 2008 09:10:47 -0700 (PDT) Subject: Using Python and MS-SQL Server Message-ID: <734a9927-a18b-4af6-a717-eaf2631b4836@c58g2000hsc.googlegroups.com> Hello, I have programmed before, but I am new to using Python. I am currently using the ArcGIS software which uses Python as its scripting language for automating tasks. The current script that I am working on requires pulling in some information from a Microsoft SQL Server. I was wondering if anyone could suggest the best way of doing this? I have looked at the different modules that are specific to SQL server, but none of them seem to be active or up to date. If not, could anyone make any suggestions? Or would it be better to go the ODBC route? I am not talking about large amounts of data, so I am not concerned about performance so ODBC would be fine to use as well. Also, being new to Python, I recently read about dictionaries and was wondering if there was a quick way to dump a table into a dictionary? For example, I have a customer list with a customer ID. It would be great to have the ID as the "key" and the name as the "data" (or even better, have a list as the data element containing all the information about the customer). I am sure that this could be done manually, by looping through each record and adding it to the dictionary -- but I was just wondering if something like this has already been done (I don't need to reinvent the wheel here). Thanks so much, Hugh From __peter__ at web.de Sun Jun 1 20:05:19 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 Jun 2008 02:05:19 +0200 Subject: a question about the #prefix of sys.argv References: Message-ID: Aldarion wrote: > for the little script > #egg.py > import sys > for k,v in enumerate(sys.argv): > print k,v > > it ignores ?the part after # on linux > below is the running output on windows and linux. no clue here. This has nothing to do with python, it's the shell that treats the # and everything that follows as a comment. $ ./listargs.py alpha #beta 0 ./listargs.py 1 alpha But you can escape it: $ ./listargs.py alpha \#beta 0 ./listargs.py 1 alpha 2 #beta $ ./listargs.py alpha '#beta' 0 ./listargs.py 1 alpha 2 #beta Peter From yonnym at googlemail.com Wed Jun 11 10:36:00 2008 From: yonnym at googlemail.com (uo) Date: Wed, 11 Jun 2008 07:36:00 -0700 (PDT) Subject: Object Manipulation and Frames Message-ID: <41d99183-665d-43f7-802d-5636506629fe@a1g2000hsb.googlegroups.com> Hello people, I would like to get some advice on the method that i should use to develop a cyber billing wxpython app.I had started but i hit a snag when i realised i could not launch or fiddle with properties of a Frame object within another frame object, what i had intended to do was to first launch a login frame where members would login and after successful authentication , the frame would be hidden and another would be launched for billing...i had a LoginFrame and a BillingFrame but after successful auth i found it hard to switch the BillingFrame.Show(True), can this be done ...and would making use of MDI make it beter? ...and if not could anyone please suggest a better/ workable alternative..Thank you. From musiccomposition at gmail.com Mon Jun 16 22:59:27 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 16 Jun 2008 19:59:27 -0700 (PDT) Subject: Context manager for files vs garbage collection References: <74f25d98-a6a5-4034-b3b7-06a8ca40ce04@e39g2000hsf.googlegroups.com> <4856699b$0$12566$426a74cc@news.free.fr> Message-ID: <2c43384e-5755-4869-ac61-c7bdd207ee30@a1g2000hsb.googlegroups.com> On Jun 16, 8:24 am, Bruno Desthuilliers wrote: > > IIRC (please someone correct me if I'm wrong), proper release of file > resources as soon as the file object gets out of scope is not garanteed > in the language spec and is implementation dependant. Right. Resources are freed in CPython right after they drop out of scope. This is not true in other implementations, so it's best to be explicit. From kris at FreeBSD.org Wed Jun 18 09:39:45 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Wed, 18 Jun 2008 15:39:45 +0200 Subject: ZFS bindings Message-ID: <48591021.1020303@FreeBSD.org> Is anyone aware of python bindings for ZFS? I just want to replicate (or at least wrap) the command line functionality for interacting with snapshots etc. Searches have turned up nothing. Kris From chardish at gmail.com Tue Jun 10 11:04:18 2008 From: chardish at gmail.com (chardish at gmail.com) Date: Tue, 10 Jun 2008 08:04:18 -0700 (PDT) Subject: Instructions on how to build py2exe 0.6.8 (or an installer would be nice, too!) Message-ID: <5426baaf-2ba6-41b0-a0ec-1070429b5195@x35g2000hsb.googlegroups.com> Hello, I'm trying to build an executable with py2exe, but unfortunately the version I have is 0.6.6, which has a rather annoying bug that doesn't let you rename the executable file if you bundle everything in a single executable. It seems fairly unacceptable to tell our customers that they can't rename a file we send them. I hear this problem is fixed in 0.6.8, but unfortunately there's no standalone installer for py2exe 0.6.8 - the most recent version that has an installer is 0.6.6 way back from 2006 (!). Is there a standalone installer for py2exe 0.6.8 anywhere? If not, how do I build it from source? (There's no instructions in the readme - it just says "How to install: download the standalone installer" and doesn't include building instructions.) Cheers, Evan From castironpi at gmail.com Tue Jun 10 20:33:08 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 10 Jun 2008 17:33:08 -0700 (PDT) Subject: Python doesn't understand %userprofile% References: <484f1375_1@news.tm.net.my> Message-ID: On Jun 10, 6:51?pm, TheSaint wrote: > On 00:11, mercoled? 11 giugno 2008 Tim Golden wrote: > > > "%USERPROFILE%/dir/file". > > os.environ('USERPROFILE') should return an info regarding that environment > variable. > I guess that, not yet tried. > -- > Mailsweeper Home :http://it.geocities.com/call_me_not_now/index.html I found: from os import environ r'%(HOMEPATH)s\My Documents\My Pictures\pycon.bmp'% environ But 'os.join' is supposedly more correct. From george.sakkis at gmail.com Sun Jun 15 14:25:04 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 15 Jun 2008 11:25:04 -0700 (PDT) Subject: Removing inheritance (decorator pattern ?) Message-ID: I have a situation where one class can be customized with several orthogonal options. Currently this is implemented with (multiple) inheritance but this leads to combinatorial explosion of subclasses as more orthogonal features are added. Naturally, the decorator pattern [1] comes to mind (not to be confused with the the Python meaning of the term "decorator"). However, there is a twist. In the standard decorator pattern, the decorator accepts the object to be decorated and adds extra functionality or modifies the object's behavior by overriding one or more methods. It does not affect how the object is created, it takes it as is. My multiple inheritance classes though play a double role: not only they override one or more regular methods, but they may override __init__ as well. Here's a toy example: class Joinable(object): def __init__(self, words): self.__words = list(words) def join(self, delim=','): return delim.join(self.__words) class Sorted(Joinable): def __init__(self, words): super(Sorted,self).__init__(sorted(words)) def join(self, delim=','): return '[Sorted] %s' % super(Sorted,self).join(delim) class Reversed(Joinable): def __init__(self, words): super(Reversed,self).__init__(reversed(words)) def join(self, delim=','): return '[Reversed] %s' % super(Reversed,self).join(delim) class SortedReversed(Sorted, Reversed): pass class ReversedSorted(Reversed, Sorted): pass if __name__ == '__main__': words = 'this is a test'.split() print SortedReversed(words).join() print ReversedSorted(words).join() So I'm wondering, is the decorator pattern applicable here ? If yes, how ? If not, is there another way to convert inheritance to delegation ? George [1] http://en.wikipedia.org/wiki/Decorator_pattern From tjreedy at udel.edu Tue Jun 24 15:26:35 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Jun 2008 15:26:35 -0400 Subject: percent string replacement with index In-Reply-To: <7ci7j5-uu7.ln1@satorlaser.homedns.org> References: <7ci7j5-uu7.ln1@satorlaser.homedns.org> Message-ID: Ulrich Eckhardt wrote: > What I'm surprised is that this isn't supported: > > "%(1)s %(2)s" % ("zero", "one", "two") > > i.e. specifying the index in a sequence instead of the key into a map (maybe > I would use [1] instead of (1) though). Further, the key can't be a simple > number it seems, which makes this even more inconvenient to me. > > Can anyone explain this to me? History. See below. > > Also, why isn't the 's' conversion (i.e. to a string) the default? I > personally would like to just write something like this: > > "%1 is not %2" % ("zero", "one", "two") > > or maybe > > "%[1] is not %[2]" % ("zero", "one", "two") In 2.6 (I believe) and 3.0: >>> "{1} is not {2} or {0}. It is just {1}".format("zero", "one", "two") 'one is not two or zero. It is just one' From paul.hankin at gmail.com Sun Jun 22 19:23:34 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sun, 22 Jun 2008 16:23:34 -0700 (PDT) Subject: listcomprehension, add elements? References: <13452c64-ef91-49a2-bb73-7f33c088660e@d45g2000hsc.googlegroups.com> Message-ID: <7dc3d1d6-12d7-4a9e-ac7a-91406610e106@d19g2000prm.googlegroups.com> On Jun 23, 10:32?am, cirfu wrote: > [a+b for a,b in zip(xrange(1,51), xrange(50,0,-1))] > > [51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, > 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, > 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51] > > i want to add all the elemtns a s well. can i do this all in a > listcomprehension? > > i can do this ofc: > reduce(lambda x,y:x+y,[a+b for a,b in zip(xrange(1,51), > xrange(50,0,-1))]) > > but reduce is a functional way of doing it, what is the more pythonic > way of doing this? Use the builtin 'sum' function. sum(a + b for a, b in zip(xrange(1, 51), xrange(50, 0, -1))) -- Paul Hankin From gagsl-py2 at yahoo.com.ar Mon Jun 16 02:20:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 16 Jun 2008 03:20:32 -0300 Subject: os.walk Value Error? References: Message-ID: En Sat, 14 Jun 2008 19:06:16 -0300, escribi?: > I'm using os.walk as follows: > > (basedir, pathnames, files) = os.walk("results", topdown=True) > > and I'm getting the error: > > ValueError: too many values to unpack > >> From my googling, that means: > > This is the standard message when Python tries to unpack a tuple > into fewer variables than are in the tuple. > >> From what I can see of the examples on the python site, I'm using it > correctly. I have commas in my original code, and the "results" > directory exists and is directly under the directory from which my > script is run. Look the examples more carefully again - they don't use an assignment, but another Python statement... -- Gabriel Genellina From xushunttr2 at yahoo.cn Sun Jun 29 08:26:52 2008 From: xushunttr2 at yahoo.cn (jinole) Date: Sun, 29 Jun 2008 05:26:52 -0700 (PDT) Subject: Classical nurses site Message-ID: <82b3df24-8e1a-4153-8158-57a5b3eed716@p25g2000pri.googlegroups.com> Recommended for everyone to an Asian pornographic website?There are many beauty photos and movies.URL: http://www.loioi.com If you need more sites, then contact me. e-mail: aa459ss at live.cn From fuzzyman at gmail.com Mon Jun 23 15:21:11 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 23 Jun 2008 12:21:11 -0700 (PDT) Subject: installed 3.0, rebind winprompt to 2.5? References: <212d2320-0c9e-4744-823b-bf715d4bb9ee@c65g2000hsa.googlegroups.com> Message-ID: On Jun 23, 6:53?pm, cirfu wrote: > i installed python 3.0. now when im laucnhing from the dos prompt in > win vista it searches in python3.0 > > i want to rebind it to 2.5, what do i need to change? Reinstalling 2.5 should work. Michael Foord http://www.ironpythoninaction.com/ From mr.williamchang at gmail.com Wed Jun 18 17:25:04 2008 From: mr.williamchang at gmail.com (MisterWilliam) Date: Wed, 18 Jun 2008 14:25:04 -0700 (PDT) Subject: extra positional arguments before optional parameters syntax Message-ID: I noticed that in PEP 3105, the PEP about turning print to print(), the syntax for print() is defined as follows: def print(*args, sep=' ', end='\n', file=None) Ignoring the fact that print is a reserved keyword in python, this is not valid python because extra positional arguments (*args), cannot come before optional parameters (sep=' ', end='\n', file=None). >>> def f(*args, sep=' ', end='\n', file=None): File "", line 1 def f(*args, sep=' ', end='\n', file=None): ^ SyntaxError: invalid syntax Am I misunderstanding something? Is this type of syntax suppose to be allowed in a future version of Python? (I can't find anything about this through my searching.) This kind of syntax seems useful, especially one wants to overwrite the new function print(). Thanks, William Chang From gh at ghaering.de Sun Jun 8 05:00:21 2008 From: gh at ghaering.de (=?UTF-8?B?R2VyaGFyZCBIw6RyaW5n?=) Date: Sun, 08 Jun 2008 11:00:21 +0200 Subject: SQlite none english char In-Reply-To: References: Message-ID: <6b1ld5F3a4hsvU1@mid.uni-berlin.de> Gandalf wrote: > I works with python 2.5 on windows, And I use sqlite3 > > Now, I have problem searching string in Hebrew in my database > > I have table called "test" with field num and test > firs row i insert "1" and "?????" (that is "Hebrew" in Hebrew) > second row i insert "2" and "English" [...] I recommend you use Unicode strings for all your Python strings in the application. You can then be that things will just work with the sqlite3 module. The problem is that the sqlite3 module doesn't currently check if what you insert into the database is in UTF-8 encoding. But if it isn't, you're likely to run into problems later on. So, let's assume that you've written your Python using a UTF-8 editor, you can then use something like: # coding: utf-8 as the first line in the script. Among others, this will allow you to write Unicode literals in UTF-8, i. e. do something like: data = u"?????". then you can insert this into the database: cur.execute("insert into test(test) values (?)", (data,)) Note that I use the parametrized form of execute() with ? as placeholders. *Always* use this when the SQL statement is not constant, but has parameters of some sort. > [...] > cur.execute("select * from `test` where text like '%"+i+"%' ") > for row in cur: > print row[1] > > but this one print me nothing > instead of ????? This could be two problems. Either (likely) it simply isn't found because you inserted garbage (non-UTF-8 data) or you got a decoding error to UTF-8 executing the select, which the sqlite3 module will currently unfortunately ignore and return a None value instead. Again, use the parametrized form of the execute() statement with Unicode Python strings to avoid any problems. cur.execute("select * from test where text like '%' || ? || '%'", (searchstr,)) !!! Ok, I just found out that you used the + operator in SQL to concatenate strings. Don't, as it will not work (except on maybe MySQL). Use the || operator instead! Note that when you use cur.execute(sql, params), then params is actually a tuple of parameters. In the above examples there was only one parameter, so it was a one-tuple, which is written as (element,). Dont'write it as (element), because Python will not recognize it as a tuple then. Don't hesitate to ask if you need further help. -- Gerhard From sjmachin at lexicon.net Thu Jun 19 19:51:10 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 19 Jun 2008 16:51:10 -0700 (PDT) Subject: Hamming Distance References: <6d9f011f-3c35-4aae-81a6-e0fa47ff7056@a9g2000prl.googlegroups.com> Message-ID: <876fd21a-c53e-4c8b-b431-92a9f94c5faa@x19g2000prg.googlegroups.com> On Jun 20, 9:27 am, godavemon wrote: > I need to calculate the Hamming Distance of two integers. The hamming > distance is the number of bits in two integers that don't match. I > thought there'd be a function in math or scipy but i haven't been able > to find one. This is my function but it seems like there should be a > faster way. I do this computation many times and speed up is > important. > > def hamdist( a, b , bits = 32): > def _hamdist( x, bits): > if bits: > return (x & 1) + _hamdist(x >> 1, bits-1) > return x & 1 > return _hamdist( a ^ b, bits) > > Another alternative would be to convert the XOR to a binary string and Isn't it a "binary string" already? > count the # of 1's. My guess is that counting the 1-bits in (a ^ b) would be hard to beat, and that a recursive function is just not in the race. > > Which would be fastest? Implement both and time them. > Are there better alternatives? I doubt it. BTW one presumes that your integers are non-negative ... HTH Cheers, John From washakie at gmail.com Fri Jun 13 23:45:05 2008 From: washakie at gmail.com (John [H2O]) Date: Fri, 13 Jun 2008 20:45:05 -0700 (PDT) Subject: numpy: handling float('NaN') different in XP vs. Linux Message-ID: <17835502.post@talk.nabble.com> I have a script: from numpy import float OutD=[] v=['3','43','23.4','NaN','43'] OutD.append([float(i) for i in v[1]]) On linux: Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 [john at andLinux analysis]$ python jnk.py [[3.0, 43.0, 23.399999999999999, nan, 43.0]] On XP: Python 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\analysis>C:\Python25\python.exe jnk.py Traceback (most recent call last): File "jnk.py", line 4, in OutD.append([float(i) for i in v]) ValueError: invalid literal for float(): NaN WTF? -- View this message in context: http://www.nabble.com/numpy%3A-handling-float%28%27NaN%27%29-different-in-XP-vs.-Linux-tp17835502p17835502.html Sent from the Python - python-list mailing list archive at Nabble.com. From notnorwegian at yahoo.se Sun Jun 29 00:06:15 2008 From: notnorwegian at yahoo.se (slix) Date: Sat, 28 Jun 2008 21:06:15 -0700 (PDT) Subject: Why is recursion so slow? Message-ID: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> Recursion is awesome for writing some functions, like searching trees etc but wow how can it be THAT much slower for computing fibonacci- numbers? is the recursive definition counting fib 1 to fib x-1 for every x? is that what lazy evaluation in functional languages avoids thus making recursive versions much faster? is recursive fibonacci in haskell as fast as an imperative solution in a procedural language? def fibr(nbr): if nbr > 1: return fibr(nbr-1) + fibr(nbr-2) if nbr == 1: return 1 if nbr == 0: return 0 def fibf(n): sum=0 a=1 b=1 if n<=2: return 1 for i in range(3,n+1): sum=a+b a=b b=sum return sum i found a version in Clojure that is superfast: (def fib-seq (concat [0 1] ((fn rfib [a b] (lazy-cons (+ a b) (rfib b (+ a b)))) 0 1))) (defn fibx [x] (last (take (+ x 1) fib-seq))) (fibx 12000) is delivered instantly. is it using lazy evaluation? From omer at no-log.org Mon Jun 16 12:39:13 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Mon, 16 Jun 2008 18:39:13 +0200 Subject: 'string'.strip(chars)-like function that removes from the middle? In-Reply-To: <48569B9E.6030206@admailinc.com> References: <48569B9E.6030206@admailinc.com> Message-ID: <200806161839.13647.omer@no-log.org> Hi, > Greetings. > > The strip() method of strings works from both ends towards the middle. > Is there a simple, built-in way to remove several characters from a > string no matter their location? (besides .replace() ;) > > For example: > .strip --> 'www.example.com'.strip('cmowz.') > 'example' > .??? --> --- 'www.example.com'.strip('cmowz.') > 'exaple' > -- I don't see any string method to do that, but you can use a regexp : >>> re.sub('[cmowz.]', '', 'www.example.com') 'exaple' -- C?dric Lucantis From ivan.illarionov at gmail.com Fri Jun 6 12:01:33 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Fri, 6 Jun 2008 16:01:33 +0000 (UTC) Subject: Image Processing (batch) References: <6akqd5F37rofnU1@mid.individual.net> Message-ID: On Thu, 05 Jun 2008 07:10:56 +0000, Tim Roberts wrote: > Thomas Guettler wrote: >> >>I tried PIL for image batch processing. But somehow I don't like it >> - Font-Selection: You need to give the name of the font file. - >> Drawing on an image needs a different object that pasting and saving. >> - The handbook is from Dec. 2006. I don't want to dissapoint you but PIL font handling sucks terribly. > I have repeatedly seen the attitude in your last point, and I simply do > not understand it. What on Earth is wrong with having a product that > actually becomes stable? > > We all complain about Microsoft's feature bloat, rolling out unnecessary > new releases of their products year after year with features that no one > really needs. But when an open source product FAILS to produce a new > release every six weeks, we start seeing posts questioning whether the > product is still viable or has become abandonware. I think if you really TRY to create your own project you'll understand what's going on here. >From near 10 open source projects that I've started only 1 is living today. > Once a product does the job it was designed to do, IT'S DONE. Because there's no such thing as "do the job you where designed to do" Example: designed for image manipulation. No matter how many features you've already implemented there's always something more to do. > Personally, I think PIL is a great solution for batch processing, but > the beauty of the open source world is that the ARE alternatives. Yes, it's open source, and everybody will win if you'll extend PIL to do what you want. Really, I do have some working snippets of code that do handle fonts nicely with PIL images, read and parse OpenType tables, but I can't publish it because it's optimized for my private needs like only two languages: Russian and English. I had to rewrite PIL's FreeType layer from scratch to do what I want. You can do the same. Ivan From phillip.oldham at gmail.com Fri Jun 13 19:40:05 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Fri, 13 Jun 2008 16:40:05 -0700 (PDT) Subject: Making HEAD/PUT/DELETE requests with urllib2? Message-ID: In my attempt to learn python in a weekend, I've fallen foul at line 10 of my second scripting attempt. Basically I'm writing a simple spider, but currently I'm unable to find any documentation on making HEAD requests using the urllib2 library to test whether a file exists on a remote webserver. I've checked the docs on urllib2 from docs.python.org, and unless I'm missing something there doesn't seem to be a way to do *any* request other than a GET and POST. Surely this can't be correct? If so, we're all going to have a hell of a time creating RESTful web apps. Any help on the matter would be greatly appreciated. From hyugaricdeau at gmail.com Mon Jun 16 09:28:47 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Mon, 16 Jun 2008 06:28:47 -0700 (PDT) Subject: Iterate creating variables? References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> Message-ID: On Jun 13, 11:34 am, "Reedick, Andrew" wrote: > > -----Original Message----- > > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- > > list-bounces+jr9445=att.... at python.org] On Behalf Of tda... at gmail.com > > Sent: Friday, June 13, 2008 11:11 AM > > To: python-l... at python.org > > Subject: Iterate creating variables? > > > I have twenty-five checkboxes I need to create (don't ask): > > > self.checkbox1 = ... > > self.checkbox2 = ... > > . > > . > > . > > self.checkbox25 = ... > > > Right now, my code has 25 lines in it, one for each checkbox, since > > these are all variables. > > > Is there a way to write a loop so that I can have fewer lines of code > > but still keep the variables? > > > I've tried: > > > for o in xrange(25): > > self.checkbox[o] = ... > > > which didn't work, and > > > for o in xrange(25): > > self.checkbox[''%d'%(o)] = ... > > > which also didn't work. > > > Both give the error message: "Attribute error: Main.App has no > > attribute "checkbox"", which clearly indicates that I'm not keeping > > the "variability" aspect I want. > > > Is there a way? > > > I appreciate any and all answers! > > Either store the checkboxes in an array or hash/dictionary. If that's > not practical, then > You can use strings to build the code and use eval to execute the string > as code. Ex: > > for i in range(10): > code = "%d + %d" % (i, i) > print eval(code) Don't do this. You want for idx in range(10): setattr(self, 'checkbox_%i' % idx) From dstromberglists at gmail.com Fri Jun 13 12:41:46 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Fri, 13 Jun 2008 16:41:46 GMT Subject: Automatically restarting system calls? Message-ID: I wrote a script(1) replacement in python (http://stromberg.dnsalias.org/ ~dstromberg/pypty/), but I'm encountering a problem in it. I think I know the solution to the problem, but I'd've thought python was high level enough that this solution isn't required, so I wanted to inquire about it here. Specifically, the program has a signal handler for window size changes. And if the window is resized during an os.write() (for example), I get a python exception about needing to restart the system call. In C, I know you're supposed to wrap your system calls with while loops until you don't get an ERESTART, but does one really need to wrap all of one's os.write()'s (for example) with such while loops in python? Thanks! From sk8in_zombi at yahoo.com.au Sun Jun 29 16:16:07 2008 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Sun, 29 Jun 2008 13:16:07 -0700 (PDT) Subject: UnboundLocalError problems Message-ID: <637159.47140.qm@web54507.mail.re2.yahoo.com> Hi, I am writing a small script that changes my pidgin status to away when I lock my screen.I'm using the DBUS API for pidgin and gnome-screensaver.Here's the code: #!/usr/bin/env python import dbus, gobject from dbus.mainloop.glib import DBusGMainLoop dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SessionBus() obj = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject") purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface") STATUS_AVAILABLE = 2 STATUS_AWAY = 5 ORIG_TYPE = 0 ORIG_MSG = "" def my_func2(IsEnabled): if IsEnabled: ORIG_TYPE,ORIG_MSG = get_current() set_status(STATUS_AWAY,"I'm not at my desk") else: set_status(ORIG_TYPE,ORIG_MSG) def set_status(kind, message): status = purple.PurpleSavedstatusNew("", kind) purple.PurpleSavedstatusSetMessage(status, message) purple.PurpleSavedstatusActivate(status) def get_current(): typ = purple.PurpleSavedstatusGetType(purple.PurpleSavedstatusGetCurrent()) current = purple.PurpleSavedstatusGetCurrent() msg = purple.PurpleSavedstatusGetMessage(dbus.Int32(current)) return typ,msg bus.add_signal_receiver(my_func2, dbus_interface="org.gnome.ScreenSaver", signal_name="SessionIdleChanged") loop = gobject.MainLoop() loop.run() When I run it,it errors out at : set_status(ORIG_TYPE,ORIG_MSG) giving the error "UnboundLocalError: local variable 'ORIG_TYPE' referenced before assignment" .This happens Aren't ORIG_TYPE and ORIG_MSG global variables? Where am I going wrong?Everything works fine if I set the arguments manually to the set_status function. Regards, SZ Get the name you always wanted with the new y7mail email address. www.yahoo7.com.au/mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From mccredie at gmail.com Wed Jun 11 20:05:22 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 11 Jun 2008 17:05:22 -0700 (PDT) Subject: Simple and safe evaluator References: Message-ID: On Jun 11, 4:38 pm, bvdp wrote: > I'm finding my quest for a safe eval() quite frustrating :) > > Any comments on this: Just forget about getting python to do this and, > instead, grab my set of values (from a user supplied text file) and call > an external program like 'bc' to do the dirty work. I think that this > would avoid someone from embedding os.system("rm ...") in what I thought > would be a math expression and having it maybe do damage? Perhaps I'm > getting too paranoid in my old age. > > I guess this would slow things down a bit, but that is not a big > concern. Bigger concern would be that I'm not sure if 'bc' or whatever > is guaranteed to be on other platforms than *nix. And if I want to be > really paranoid, I could worry that someone had planted a bad 'bc' on > the target. The solution I posted should work and is safe. It may not seem very readable, but it is using Pythons internal parser to parse the passed in string into an abstract symbol tree (rather than code). Normally Python would just use the ast internally to create code. Instead I've written the code to do that. By avoiding anything but simple operators and literals it is guaranteed safe. If you only want numbers you can even remove a bunch of code: [code] import _ast class SafeEvalError(Exception): pass class UnsafeCode(SafeEvalError): pass def num_eval(text): "similar to eval, but only works on numerical values." ast = compile(text, "", 'eval', _ast.PyCF_ONLY_AST) return _traverse(ast.body) def _traverse(ast): if isinstance(ast, _ast.Num): return ast.n elif isinstance(ast, _ast.Expr): return _traverse(ast.value) elif isinstance(ast, _ast.BinOp): if isinstance(ast.op, _ast.Add): return _traverse(ast.left) + _traverse(ast.right) elif isinstance(ast.op, _ast.Sub): return _traverse(ast.left) - _traverse(ast.right) elif isinstance(ast.op, _ast.Div): return _traverse(ast.left) / _traverse(ast.right) elif isinstance(ast.op, _ast.FloorDiv): return _traverse(ast.left) // _traverse(ast.right) elif isinstance(ast.op, _ast.Mod): return _traverse(ast.left) % _traverse(ast.right) elif isinstance(ast.op, _ast.Mult): return _traverse(ast.left) * _traverse(ast.right) elif isinstance(ast.op, _ast.Pow): return _traverse(ast.left) ** _traverse(ast.right) elif isinstance(ast.op, _ast.BitAnd): return _traverse(ast.left) & _traverse(ast.right) elif isinstance(ast.op, _ast.BitOr): return _traverse(ast.left) | _traverse(ast.right) elif isinstance(ast.op, _ast.BitXor): return _traverse(ast.left) ^ _traverse(ast.right) elif isinstance(ast.op, _ast.LShift): return _traverse(ast.left) << _traverse(ast.right) elif isinstance(ast.op, _ast.RShift): return _traverse(ast.left) >> _traverse(ast.right) elif isinstance(ast, _ast.UnaryOp): if isinstance(ast.op, _ast.Invert): return ~_traverse(ast.operand) elif isinstance(ast.op, _ast.USub): return -_traverse(ast.operand) elif isinstance(ast.op, _ast.UAdd): return +_traverse(ast.operand) raise UnsafeCode() [/code] To use: print num_eval("1 + 44 / 3") From jaraco at jaraco.com Thu Jun 12 20:16:52 2008 From: jaraco at jaraco.com (Jason R. Coombs) Date: Thu, 12 Jun 2008 17:16:52 -0700 (PDT) Subject: Wording suggestion for documentation (Data Model) Message-ID: <512da201-973f-4737-a5de-1efa48d84394@8g2000hse.googlegroups.com> #!python """ In the documentation for __del__ (under Python Language Reference/Data Model), the following warning is indicated: Warning [Caveat in 2.6]: Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead. ... That statement appears, however, to be incorrect. Perhaps the warning should be re-worded to say "When __del__() methods are invoked, exceptions that occur during the execution of such methods must be caught and handled within the scope of the __del__() method call. Otherwise unhandled exceptions will be ignored except for a warning printed to sys.stderr instead." For example, """ class X(object): def __del__(self): print 'deleting', self try: raise Exception, "OMG!" except: print 'caught exception, np' print 'made it past the exception' x = X() del x print 'x has been deleted, now what?' """ All this prints something like: deleting <__main__.X object at 0x01BB1A50> caught exception, np made it past the exception x has been deleted, now what? """ # - Jason R. Coombs From __peter__ at web.de Mon Jun 30 06:06:53 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 30 Jun 2008 12:06:53 +0200 Subject: Getting sorting order References: <7cb9ebb7-e722-41e1-bdf2-693954a21b92@j22g2000hsf.googlegroups.com> Message-ID: leodp wrote: > >> Or provide a better explanation and an example. Do you mean something >> like this? >> > > Hi Peter, > a small example: > > master=[1,4,3,2] > slave1=['d','c','b','a'] > slave2=[1,2,3,4] > > master.sort() # this is ok, but does not return infos on how the list > was sorted > slave1.sort(key=_maybe_something_here_referring_to_master_) > slave2.sort(key=_maybe_something_here_referring_to_master_) > > Then I should get: > master=[1,2,3,4] > slave1=['d','a','b','c'] > slave2=[1,4,3,2] > > > Hope it is more clear now. > Thanks, leodp You need a helper list (called master_index in the example below): >>> master=[1,4,3,2] >>> slave1=['d','c','b','a'] >>> slave2=[1,2,3,4] >>> master_index = range(len(master)) >>> master_index.sort(key=master.__getitem__) >>> master[:] = [master[i] for i in master_index] >>> slave1[:] = [slave1[i] for i in master_index] >>> slave2[:] = [slave2[i] for i in master_index] >>> master [1, 2, 3, 4] >>> slave1 ['d', 'a', 'b', 'c'] >>> slave2 [1, 4, 3, 2] If you don't care about list object identity you can use master = [...] instead of master[:] = [...] etc. Peter From martin at v.loewis.de Sun Jun 15 12:47:16 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 15 Jun 2008 18:47:16 +0200 Subject: Making wxPython a standard module? In-Reply-To: <0bb2d727-4bd8-4baf-be34-716daec1ddff@d1g2000hsg.googlegroups.com> References: <48512f69$0$11262$c3e8da3@news.astraweb.com> <0bb2d727-4bd8-4baf-be34-716daec1ddff@d1g2000hsg.googlegroups.com> Message-ID: <48554794.3050203@v.loewis.de> > I know there must be at least a few very solid answers to this, but, > just to hear it from the Pythonistas: Why can't there be several GUI > toolkits on the standard library? Why do you think there can't be several GUI toolkits in the standard library? There is nothing that prohibits such a thing per se. See my other message on why wxPython isn't part of the standard library: it hasn't been contributed, yet. Regards, Martin From phillip.oldham at gmail.com Fri Jun 13 22:25:50 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Fri, 13 Jun 2008 19:25:50 -0700 (PDT) Subject: Best way to make a number of tests against an object('s attributes) with absence of switch statement? Message-ID: <15aaceb5-2f9c-4891-98c2-fe7ac3e19f1c@k37g2000hsf.googlegroups.com> What would be the optimal/pythonic way to subject an object to a number of tests (based on the object's attributes) and redirect program flow? Say I had the following: pets[0] = {'name': 'fluffy', 'species': 'cat', 'size': 'small'} pets[1] = {'name': 'bruno', 'species': 'snake', 'size': 'small'} pets[2] = {'name': 'rex', 'species': 'dog', 'size': 'large'} What I'd like to do is loop through 'pets', and test each object. Some of the tests I'd like to perform are: Is the size 'small' and species not 'dog'? Is the species 'cat' and name 'fluffy'? Is the species not 'dog' or 'cat'? In PHP I'd use a switch statement similar to the following: foreach( $pets as $pet) { switch(true) { case ( $pet['size'] === 'small' && $pet['species'] !== 'dog' ): // do something break; // etc... } } Now, I understand from a bit of googling that python doesn't have a switch statement, and because of this people rely on python's polymorphism. Thats great, but I've yet to come across a decent example which make a "click". Any thoughts on how to proceed? From jaywgraves at gmail.com Fri Jun 6 16:35:40 2008 From: jaywgraves at gmail.com (jay graves) Date: Fri, 6 Jun 2008 13:35:40 -0700 (PDT) Subject: File-writing not working in Windows? References: <80a7b951-591b-41a2-b76c-f97d75db0dad@25g2000hsx.googlegroups.com> <08442be2-13c0-44fc-add4-4907c1202f96@r66g2000hsg.googlegroups.com> <300fece5-da15-4323-9b3a-f49b90d9c74b@34g2000hsh.googlegroups.com> <1f2ddd19-bfd5-4d6b-984b-42e382704215@d1g2000hsg.googlegroups.com> <225a6635-256f-4dd1-b470-58de72d10345@p25g2000hsf.googlegroups.com> Message-ID: <1aa4ebfa-272c-439c-ba18-3e358fce268c@25g2000hsx.googlegroups.com> On Jun 6, 3:19 pm, tda... at gmail.com wrote: > This did not make a difference in my script. However, I did what you > suggested, and tried the simple script it Windows, and it works as it > should. > (It's really annoying because it works on the Mac and Linux! (I just > tested my script on the Mac as well.) It only doesn't work on > Windows, though clearly the file processing I am doing SHOULD work.) Is there a global exception handler somewhere in your code that could be eating an error that only happens on windows? (something weird like file permissions.) I'm really at a loss. Sorry. ... Jay From bearophileHUGS at lycos.com Wed Jun 4 19:37:08 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 4 Jun 2008 16:37:08 -0700 (PDT) Subject: Tuples part 2 References: Message-ID: <295215b0-83b4-46a7-ac94-ed94be57ccad@27g2000hsf.googlegroups.com> victor.hera... at gmail.com: Do you mean something like this? (notice the many formatting differences, use a formatting similar to this one in your code) coords = [] for i in xrange(1, 5): for j in xrange(1, 5): for k in xrange(1, 2): coords.append( (i, j, k) ) coords *= 10 print coords Bye, bearophile From sjmachin at lexicon.net Wed Jun 4 10:59:38 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 05 Jun 2008 00:59:38 +1000 Subject: Zipfile module errors In-Reply-To: <07ba0098-e073-46b9-8240-4915c4b5ad4d@c65g2000hsa.googlegroups.com> References: <1bea3f60-5866-4ecb-a2a2-51f7130f03c8@y21g2000hsf.googlegroups.com> <8a2a1e8d-cde2-45f4-9329-407e0c2980c8@l28g2000prd.googlegroups.com> <07ba0098-e073-46b9-8240-4915c4b5ad4d@c65g2000hsa.googlegroups.com> Message-ID: <4846ADDA.3@lexicon.net> jwesonga wrote: > I've added the line to the script, added a zipped file into the > folder. I've made sure the file exists. The error is now this: Please get some clues: (1) Don't reply off-list unless specifically invited. (2) Don't top-post. (3) Do read and try to understand *all* of each reply that you get ... e.g. """ P.S. Printing the contents of filelist immediately after it's been created might be a good idea. You say "pick the zipped files" but the only condition I see is a test using os.path.isdir. """ (4) Do read and try to understand the output from your own script, e.g. > > [jwesonga at web38 processor_files]$ python2.4 processor3.py > trying to unzip '/home/jwesonga/received/log.txt' whose size is 752 > bytes Doesn't that tell you anything? Like you are trying to unzip your own logfile?? > Traceback (most recent call last): > File "processor3.py", line 125, in ? > unzip(infolder) > File "processor3.py", line 54, in unzip > zfile = zipfile.ZipFile(one,'r') > File "/usr/lib/python2.4/zipfile.py", line 210, in __init__ > self._GetContents() > File "/usr/lib/python2.4/zipfile.py", line 230, in _GetContents > self._RealGetContents() > File "/usr/lib/python2.4/zipfile.py", line 242, in _RealGetContents > raise BadZipfile, "File is not a zip file" > zipfile.BadZipfile: File is not a zip file > > This is strange because I can see the zipped file inside the folder / > home/jwesonga/received what could be the problem? > > On Jun 4, 2:45 pm, John Machin wrote: >> On Jun 4, 8:06 pm, jwesonga wrote: >> >>> Hi, >>> I have a python script that supposed to go through a folder, pick the >>> zipped files, unzip them and process the data inside. I'm not sure >>> where i'm going wrong with this script because it all seems correct: >> Nothing is ever as it seems. Let's try to work backwards from the >> error message ... and we don't need your magnificent script, just the >> traceback will do for now, so: >> >> [ big snip] >> >> >> >>> The error I keep getting is: >>> Traceback (most recent call last): >>> File "processor3.py", line 124, in ? >>> unzip(infolder) >>> File "processor3.py", line 53, in unzip >> The error says that you are trying to seek 22 bytes backwards from the >> end of a file that you presume is a zip file, and this is deemed to be >> invalid. Hypotheses: (1) zipfile.py is buggy (2) your file is less >> than 22 bytes long. Let's park hypothesis 1 for the moment. Insert the >> following code before the call to zipfile.ZipFile: >> >> print "trying to unzip %r whose size is %d bytes" \ >> % (one, os.stat(one).st_size) >> >> and tell us your conclusions. >> >>> zfile = zipfile.ZipFile(one,'r') >>> File "/usr/lib/python2.4/zipfile.py", line 210, in __init__ >>> self._GetContents() >>> File "/usr/lib/python2.4/zipfile.py", line 230, in _GetContents >>> self._RealGetContents() >>> File "/usr/lib/python2.4/zipfile.py", line 240, in _RealGetContents >>> endrec = _EndRecData(fp) >>> File "/usr/lib/python2.4/zipfile.py", line 83, in _EndRecData >>> fpin.seek(-22, 2) # Assume no archive comment. >>> IOError: [Errno 22] Invalid argument >> P.S. Printing the contents of filelist immediately after it's been >> created might be a good idea. You say "pick the zipped files" but the >> only condition I see is a test using os.path.isdir. >> >> HTH, >> John > > > > > From johnjsal at gmailNOSPAM.com Sun Jun 8 22:40:39 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sun, 08 Jun 2008 22:40:39 -0400 Subject: Do this as a list comprehension? In-Reply-To: References: <4848b213$0$25711$607ed4bc@cv.net><484ad07b$0$25721$607ed4bc@cv.net> <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> Message-ID: <484c9830$0$5009$607ed4bc@cv.net> Mensanator wrote: > On Jun 8, 3:19?am, "Terry Reedy" wrote: >> "Mensanator" wrote in message >> >> news:8d7c0912-422f-4480-a034-078f9dbcae24 at 2g2000hsn.googlegroups.com... >> | On Jun 7, 6:43?pm, "Terry Reedy" wrote: >> | > zip(range(9,2000000000), iterable) >> | >> | Oh, dear. You didn't actually try this, did you? >> >> Works fine in Py3, which is what I use now. > > You really ARE cruel to the newbies, aren't you? > > Don't you think it would have been appropriate > to attach a large red label: WARNING! PY3! Heh heh, don't worry. Every time I see a range function, I immediately think "creates a list". Not sure how I got into that habit, but it happens every time! :) From sjmachin at lexicon.net Wed Jun 25 19:03:52 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 25 Jun 2008 16:03:52 -0700 (PDT) Subject: struct.pack behavior References: Message-ID: On Jun 26, 9:00 am, "Steven Clark" wrote: > Can anyone explain to me why > struct.pack('HB',1,2) gives 3 bytes, whereas struct.pack('BH',1,2) > gives 4 bytes? > Alignment -- read the manual. From tnleeuw at gmail.com Wed Jun 11 05:22:27 2008 From: tnleeuw at gmail.com (Tim van der Leeuw) Date: Wed, 11 Jun 2008 11:22:27 +0200 Subject: Python regex question Message-ID: Hi, I'm trying to create a regular expression for matching some particular XML strings. I want to extract the contents of a particular XML tag, only if it follows one tag, but not follows another tag. Complicating this, is that there can be any number of other tags in between. So basically, my regular expression should have 3 parts: - first match - any random text, that should not contain string '.*?(?P\d+)' (hopefully without typos) Here '' is my first match, and '(?P\d+)' is my second match. In this expression, I want to change the generic '.*?', which matches everything, with something that matches every string that does not include the substring ' From bsagert at gmail.com Mon Jun 16 17:56:39 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Mon, 16 Jun 2008 14:56:39 -0700 (PDT) Subject: Please explain Python "__whatever__" construct. Message-ID: <02c8f509-2889-433b-a548-62ead677bd19@p39g2000prm.googlegroups.com> After a couple of weeks studying Python, I already have a few useful scripts, including one that downloads 1500 Yahoo stock quotes in 6 seconds. However, many things are puzzling to me. I keep on seeing things like "__main__" in scripts. A more obscure example would be "__add__" used in string concatenation. For example, I can use "Hello "+"world (or just "Hello" "world") to join those two words. But I can also use "Hello ".__add__("world"). When and why would I ever use "__main__" or the many other "__whatever__" constructs? From swapna.nitw at gmail.com Mon Jun 23 07:57:03 2008 From: swapna.nitw at gmail.com (swapna mudavath) Date: Mon, 23 Jun 2008 17:27:03 +0530 Subject: xml to mysql (vice versa ) too Message-ID: Hi, I need to write a python script to store data which is in XML to MYSQL and even vice versa.... what should be the approach? i am able to establish a connection,create tables and insert data ..... but how to read an xml file and store in MYSQL.... my XML structure is like . .... ... can somebody please help me......i am really confused!!!!!! thanks in advance :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From metalkeys404 at gmail.com Fri Jun 27 21:12:23 2008 From: metalkeys404 at gmail.com (Ampedesign) Date: Fri, 27 Jun 2008 18:12:23 -0700 (PDT) Subject: lxml and links Message-ID: I'm trying to extract all the links on a page with lxml. Ideally, I would like it to return me a list of hrefs of each link on the page, in a list. How would I go about doing this? From madhav.bnk at gmail.com Fri Jun 27 04:23:07 2008 From: madhav.bnk at gmail.com (madhav) Date: Fri, 27 Jun 2008 01:23:07 -0700 (PDT) Subject: Email Bounce Detection References: Message-ID: <164ab83d-311b-40ce-a112-c8a8cb9d077d@t12g2000prg.googlegroups.com> On Jun 27, 12:34?pm, Maric Michaud wrote: > Le Friday 27 June 2008 09:03:15 madhav, vous avez ?crit?: > > > Hello everybody, I need a mechanism to detect email bounces. I tried > > browsing through smtplib implementation and found not helpful in this > > case. Actually it is said in the documentation that if a mail is sent > > to say: "somerandomn... at randomorg.com", then "_send()" in the > > SMTPConnection class returns 550(Unknown recceipient). I checked the > > same but its not returning 550 and return 250(receipient ok). > > This is not the same scenario, the SMTP server that will respond 550 is the MX > for the domain, if you send your mails using an outgoing SMTP server, it > can't know in advance the list of remote adressesbut will bounce your message > when receiving the 550 from the remote MX. > > > Later, I tried getting the smtp error code from the mail body of a > > bounced msg. the "Message" class doesnot have any error code attribute > > by default. We need to get it from the mailbody(by regex ing), which i > > think is not a valid solution, as "550" can occur anywhere in the body > > of any message otherthan the bounced msg also. > > Please help me regarding this. > > Thanks in advance. > > Bounces are multipart messages easily parsed with the email package of the > stdlib (dont' use regexes here). > > Abounce message is of type : > > Content-Type: multipart/report; > ? report-type=delivery-status; ? > > a delivery-status imply that one of the subpart of the message is a > message/delivery-status with all needed infos set in the headers. This one is > taken from a real example : > > Content-Description: Delivery report > Content-Type: message/delivery-status > > Reporting-MTA: dns; aristote.info > X-Postfix-Queue-ID: 1D07D1409FF > X-Postfix-Sender: rfc822; ma... at aristote.info > Arrival-Date: Fri, 27 Jun 2008 09:10:14 +0200 (CEST) > > Final-Recipient: rfc822; unknownadr... at nerim.net > Original-Recipient: rfc822;unknownadr... at nerim.net > Action: failed > Status: 5.0.0 > Remote-MTA: dns; tyrande.nerim.net > Diagnostic-Code: smtp; 550 : Recipient address > rejected: > ? ? User unknown in local recipient table > > So, for example : > > >>>[48]: import email > >>>[49]: bounce = email.message_from_string(open('ex.eml').read()) > >>>[50]: bounce.get_content_type() > > ...[50]: 'multipart/report' > > >>>[51]: > >>>[52]: for i in bounce.get_payload() : > > ? ?....: ? ?if i.get_content_type() == 'message/delivery-status' : > ? ?....: ? ? ? ? print i.get_payload()[1]['status'] > ? ?....: > ? ?....: > 5.0.0 > > -- > _____________ > > Maric Michaud Thankyou somuch Maric. Will try the approach you have mentioned. :) From rhamph at gmail.com Wed Jun 11 15:41:27 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Wed, 11 Jun 2008 12:41:27 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <6e6df35e-e641-44d9-9f56-c0732306eec2@q27g2000prf.googlegroups.com> <13db98b5-ed2e-45ef-97ec-ad3caeeed10e@j1g2000prb.googlegroups.com> <074caf4a-de1e-4290-b688-30148786952c@z72g2000hsb.googlegroups.com> <776fd3e3-7c2e-45b1-8196-7cde93e72da3@w1g2000prd.googlegroups.com> <98d541c3-e974-4a8c-961c-2a59f6bf32ea@v26g2000prm.googlegroups.com> <4beb7bc4-61ae-4c61-b182-270ec1dd06cf@25g2000hsx.googlegroups.com> Message-ID: <30a1ac0c-a8a3-418c-a40b-4859d13c81c5@x19g2000prg.googlegroups.com> On Jun 11, 1:17 pm, Fuzzyman wrote: > On Jun 11, 6:49 pm, Rhamphoryncus wrote: > > On Jun 11, 7:56 am, Fuzzyman wrote: > > > On Jun 11, 6:56 am, Rhamphoryncus wrote: > > > > I'm not saying it can't be made to work in your specific case - it > > > > likely does work well for you. I'm saying it can't work *in > > > > general*. Stretching it out for general use turns those little cracks > > > > into massive canyons. A language needs a general mechanism that does > > > > work - such as a polite cancellation API. > > > > Neither *works in general* - polite cancellation *doesn't* work for > > > our us. That's my point - you probably want *both* for different use > > > cases. :-) > > > Yeah, but mine's less icky. ;) > > But requires more code. :-) Both require significant support from the implementation, and you're not the one volunteering to write it (I am). Besides, they're complementary, so we should have both anyway. The question is how best to fit them together. > > I think the ideal for you would be a separate process. I'd also > > suggest a restricted VM only in a thread, but that probably wouldn't > > work for those long-running .NET APIs. Now, if those long- > > running .NET APIs did polite cancellation, then you could combine that > > with a restricted VM to get what you need. > > No - we need to pull a large object graph *out* of the calculation > (with no guarantee that it is even serializable) and the overhead for > marshalling that puts using multiple processes out of the running. Ouch. So if it fails you want it isolated and killed, but if it succeeds you want to share it with the rest of the program. > What we *want* is what we've got! And it works very well... None of > the problems you predict. :-) Which points to an unknown mechanism protecting the vulnerable code, such as using a different language. I think we've run out of material to discuss. We're about 80% in agreement, with a 20% disagreement on philosophy. From arslanburney at gmail.com Fri Jun 13 06:11:31 2008 From: arslanburney at gmail.com (arslanburney at gmail.com) Date: Fri, 13 Jun 2008 03:11:31 -0700 (PDT) Subject: Plotting Graphs + Bestfit lines References: <1a919a2b-6430-4e2e-a190-2e00e43a6138@25g2000hsx.googlegroups.com> <022d382b-0b7b-4757-855a-f07019791fcc@d45g2000hsc.googlegroups.com> <05e67e40-db9c-4d85-94c1-f0e31dd5da38@27g2000hsf.googlegroups.com> Message-ID: Got the problem solved finally. Missed out theses two lines: plot1 = Gnuplot.PlotItems.Data(original, title="Original") plot2 = Gnuplot.PlotItems.Data(expected, title="Expected") plot3 = Gnuplot.PlotItems.Data(actual, title="Acutal") plot4 = Gnuplot.PlotItems.Func('%f * x+%f'%(bf1[0],bf1[1]), title = "Expected Best Fit") plot5 = Gnuplot.PlotItems.Func('%f * x+%f'%(bf2[0],bf2[1]), title = "Actual Best Fit") The last 2 ones.... thnx nyways From george.sakkis at gmail.com Tue Jun 10 23:33:44 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 10 Jun 2008 20:33:44 -0700 (PDT) Subject: Producer-consumer threading problem Message-ID: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> I'd like some feedback on a solution to a variant of the producer- consumer problem. My first few attempts turned out to deadlock occasionally; this one seems to be deadlock-free so far but I can't tell if it's provably correct, and if so, whether it can be simplified. The generic producer-consumer situation with unlimited buffer capacity is illustrated at http://docs.python.org/lib/condition-objects.html. That approach assumes that the producer will keep producing items indefinitely, otherwise the consumer ends up waiting forever. The extension to the problem I am considering requires the consumer to be notified not only when there is a new produced item, but also when there is not going to be a new item so that it stops waiting. More specifically, I want a generator (or iterator class) with the following generic signature: def iter_consumed(items, produce, consume): '''Return an iterator over the consumed items. :param items: An iterable of objects to be `produce`()d and `consume`()d. :param produce: A callable `f(item)` that produces a single item; the return value is ignored. What "produce" exactly means is application- specific. :param consume: A callable `f()` that consumes a previously produced item and returns the consumed item. What "consume" exactly means is application-specific. The only assumption is that if `produce` is called `N` times, then the next `N` calls to `consume` will (eventually, though not necessarily immediatelly) return, i.e they will not block indefinitely. ''' One straightforward approach would be to serialize the problem: first produce all `N` items and then call consume() exactly N times. Although this makes the solution trivial, there are at least two shortcomings. First, the client may have to wait too long for the first item to arrive. Second, each call to produce() typically requires resources for the produced task, so the maximum resource requirement can be arbitrarily high as `N` increases. Therefore produce() and consume() should run concurrently, with the invariant that the calls to consume are no more than the calls to produce. Also, after `N` calls to produce and consume, neither should be left waiting. I pasted my current solution at http://codepad.org/FXF2SWmg. Any feedback, especially if it has to do with proving or disproving its correctness, will be appreciated. George From alexnbryan at gmail.com Sun Jun 29 12:50:16 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sun, 29 Jun 2008 09:50:16 -0700 (PDT) Subject: using urllib2 In-Reply-To: <25d97d35-6d28-43ef-9e54-d8ae7a03bc8f@b1g2000hsg.googlegroups.com> References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> <25d97d35-6d28-43ef-9e54-d8ae7a03bc8f@b1g2000hsg.googlegroups.com> Message-ID: <18182864.post@talk.nabble.com> No I figured it out. I guess I never knew that you aren't supposed to split a url like "http://www.goo\ gle.com" But I did and it gave me all those errors. Anyway, I had a question. On the original code you had this for loop: for tabs in soup.findAll('table', {'class': 'luna-Ent'}): yield tabs.findAll('td')[-1].contents[-1].string I hate to be a pain, but I was looking at the BeautifulSoup docs, and found the findAll thing. But I want to know why you put "for tabs," also why you need the "'table', {'class': 'luna-Ent'}):" Like why the curly braces and whatnot? Jeff McNeil-2 wrote: > > On Jun 27, 10:26?pm, Alexnb wrote: >> Okay, so I copied your code(and just so you know I am on a mac right now >> and >> i am using pydev in eclipse), and I got these errors, any idea what is >> up? >> >> Traceback (most recent call last): >> ? File >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", >> line 14, in >> ? ? print list(get_defs("cheese")) >> ? File >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", >> line 9, in get_defs >> ? ? dictionary.reference.com/search?q=%s' % term)) >> ? File >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib.py", >> line 82, in urlopen >> ? ? return opener.open(url) >> ? File >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib.py", >> line 190, in open >> ? ? return getattr(self, name)(url) >> ? File >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib.py", >> line 325, in open_http >> ? ? h.endheaders() >> ? File >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/httplib.py", >> line 856, in endheaders >> ? ? self._send_output() >> ? File >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/httplib.py", >> line 728, in _send_output >> ? ? self.send(msg) >> ? File >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/httplib.py", >> line 695, in send >> ? ? self.connect() >> ? File >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/httplib.py", >> line 663, in connect >> ? ? socket.SOCK_STREAM): >> IOError: [Errno socket error] (8, 'nodename nor servname provided, or not >> known') >> >> Sorry if it is hard to read. >> >> >> >> Jeff McNeil-2 wrote: >> >> > Well, what about pulling that data out using Beautiful soup? If you >> > know the table name and whatnot, try something like this: >> >> > #!/usr/bin/python >> >> > import urllib >> > from BeautifulSoup import BeautifulSoup >> >> > def get_defs(term): >> > ? ? soup = BeautifulSoup(urllib.urlopen('http:// >> > dictionary.reference.com/search?q=%s' % term)) >> >> > ? ? for tabs in soup.findAll('table', {'class': 'luna-Ent'}): >> > ? ? ? ? yield tabs.findAll('td')[-1].contents[-1].string >> >> > print list(get_defs("frog")) >> >> > jeff at martian:~$ python test.py >> > [u'any tailless, stout-bodied amphibian of the order Anura, including >> > the smooth, moist-skinned frog species that live in a damp or >> > semiaquatic habitat and the warty, drier-skinned toad species that are >> > mostly terrestrial as adults. ', u' ', u' ', u'a French person or a >> > person of French descent. ', u'a small holder made of heavy material, >> > placed in a bowl or vase to hold flower stems in position. ', u'a >> > recessed panel on one of the larger faces of a brick or the like. ', >> > u' ', u'to hunt and catch frogs. ', u'French or Frenchlike. ', u'an >> > ornamental fastening for the front of a coat, consisting of a button >> > and a loop through which it passes. ', u'a sheath suspended from a >> > belt and supporting a scabbard. ', u'a device at the intersection of >> > two tracks to permit the wheels and flanges on one track to cross or >> > branch from the other. ', u'a triangular mass of elastic, horny >> > substance in the middle of the sole of the foot of a horse or related >> > animal. '] >> >> > HTH, >> >> > Jeff >> >> > On Jun 27, 7:28?pm, Alexnb wrote: >> >> I have read that multiple times. It is hard to understand but it did >> help >> >> a >> >> little. But I found a bit of a work-around for now which is not what I >> >> ultimately want. However, even when I can get to the page I want lets >> >> say, >> >> "Http://dictionary.reference.com/browse/cheese", I look on firebug, >> and >> >> extension and see the definition in javascript, >> >> >> >> >> >> >> >> >> >> >> >> >> >> Jeff McNeil-2 wrote: >> >> >> > the problem being that if I use code like this to get the html of >> that > >> >> > page in python: >> >> >> > response = urllib2.urlopen("the webiste....") >> >> > html = response.read() >> >> > print html >> >> >> > then, I get a bunch of stuff, but it doesn't show me the code with >> the >> >> > table that the definition is in. So I am asking how do I access this >> >> > javascript. Also, if someone could point me to a better reference >> than >> >> the >> >> > last one, because that really doesn't tell me much, whether it be a >> >> book >> >> > or anything. >> >> >> > I stumbled across this a while back: >> >> >http://www.voidspace.org.uk/python/articles/urllib2.shtml. >> >> > It covers quite a bit. The urllib2 module is pretty straightforward >> >> > once you've used it a few times. ?Some of the class naming and >> whatnot >> >> > takes a bit of getting used to (I found that to be the most >> confusing >> >> > bit). >> >> >> > On Jun 27, 1:41 pm, Alexnb wrote: >> >> >> Okay, I tried to follow that, and it is kinda hard. But since you >> >> >> obviously >> >> >> know what you are doing, where did you learn this? Or where can I >> >> learn >> >> >> this? >> >> >> >> Maric Michaud wrote: >> >> >> >> > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit : >> >> >> >> I have never used the urllib or the urllib2. I really have >> looked >> >> >> online >> >> >> >> for help on this issue, and mailing lists, but I can't figure >> out >> >> my >> >> >> >> problem because people haven't been helping me, which is why I >> am >> >> >> here! >> >> >> >> :]. >> >> >> >> Okay, so basically I want to be able to submit a word to >> >> >> dictionary.com >> >> >> >> and >> >> >> >> then get the definitions. However, to start off learning >> urllib2, I >> >> >> just >> >> >> >> want to do a simple google search. Before you get mad, what I >> have >> >> >> found >> >> >> >> on >> >> >> >> urllib2 hasn't helped me. Anyway, How would you go about doing >> >> this. >> >> >> No, >> >> >> >> I >> >> >> >> did not post the html, but I mean if you want, right click on >> your >> >> >> >> browser >> >> >> >> and hit view source of the google homepage. Basically what I >> want >> >> to >> >> >> know >> >> >> >> is how to submit the values(the search term) and then search for >> >> that >> >> >> >> value. Heres what I know: >> >> >> >> >> import urllib2 >> >> >> >> response = urllib2.urlopen("http://www.google.com/") >> >> >> >> html = response.read() >> >> >> >> print html >> >> >> >> >> Now I know that all this does is print the source, but thats >> about >> >> all >> >> >> I >> >> >> >> know. I know it may be a lot to ask to have someone show/help >> me, >> >> but >> >> >> I >> >> >> >> really would appreciate it. >> >> >> >> > This example is for google, of course using pygoogle is easier in >> >> this >> >> >> > case, >> >> >> > but this is a valid example for the general case : >> >> >> >> >>>>[207]: import urllib, urllib2 >> >> >> >> > You need to trick the server with an imaginary User-Agent. >> >> >> >> >>>>[208]: def google_search(terms) : >> >> >> > ? ? return >> >> >> urllib2.urlopen(urllib2.Request("http://www.google.com/search?" >> >> >> > + >> >> >> > urllib.urlencode({'hl':'fr', 'q':terms}), >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? >> >> ?headers={'User-Agent':'MyNav >> >> >> > 1.0 >> >> >> > (compatible; MSIE 6.0; Linux'}) >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ).read() >> >> >> > ? ?.....: >> >> >> >> >>>>[212]: res = google_search("python & co") >> >> >> >> > Now you got the whole html response, you'll have to parse it to >> >> recover >> >> >> > datas, >> >> >> > a quick & dirty try on google response page : >> >> >> >> >>>>[213]: import re >> >> >> >> >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

    > >> >> class=r>.*?

    ', >> >> >> > res) ] >> >> >> > ...[229]: >> >> >> > ['Python Gallery', >> >> >> > ?'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des >> Monty >> >> >> ...', >> >> >> > ?'Re: os x, panther, python & co: msg#00041', >> >> >> > ?'Re: os x, panther, python & co: msg#00040', >> >> >> > ?'Cardiff Web Site Design, Professional web site design services >> >> ...', >> >> >> > ?'Python Properties', >> >> >> > ?'Frees < Programs < Python < Bin-Co', >> >> >> > ?'Torb: an interface between Tcl and CORBA', >> >> >> > ?'Royal Python Morphs', >> >> >> > ?'Python & Co'] >> >> >> >> > -- >> >> >> > _____________ >> >> >> >> > Maric Michaud >> >> >> > -- >> >> >> >http://mail.python.org/mailman/listinfo/python-list >> >> >> >> -- >> >> >> View this message in >> >> >> >> context:http://www.nabble.com/using-urllib2-tp18150669p18160312.html >> >> >> Sent from the Python - python-list mailing list archive at >> Nabble.com. >> >> >> > -- >> >> >http://mail.python.org/mailman/listinfo/python-list >> >> >> -- >> >> View this message in >> >> context:http://www.nabble.com/using-urllib2-tp18150669p18165634.html >> >> Sent from the Python - python-list mailing list archive at Nabble.com. >> >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> -- >> View this message in >> context:http://www.nabble.com/using-urllib2-tp18150669p18166785.html >> Sent from the Python - python-list mailing list archive at Nabble.com. > > I tried it on a Mac after reading your reply and I had no issues. Are > you certain you copied it correctly? > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/using-urllib2-tp18150669p18182864.html Sent from the Python - python-list mailing list archive at Nabble.com. From Lie.1296 at gmail.com Sun Jun 29 05:53:40 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 29 Jun 2008 02:53:40 -0700 (PDT) Subject: help debugging noob code - converting binary data to images... References: <56955a42-155c-4c37-9bf6-5a99cadb5c79@l42g2000hsc.googlegroups.com> Message-ID: On Jun 29, 4:47?pm, Lie wrote: > On Jun 29, 11:18?am, la... at portcommodore.com wrote: > > > > > Ok I'm a Python noob, been doing OK so far, working on a data > > conversion program and want to create some character image files from > > an 8-bit ROM file. > > > Creating the image I've got down, I open the file and use TK to draw > > the images... but > > > 1) ?It does not seem to end (running in IDLE), I have to kill the > > process to retry it seems tkinter does not close(?) > > > 2) Once I added the Image module open won't open my binary file > > (complains its not an image file, which is isnt.) ?I am sure I need to > > prefix open with something but I can't seem to find an example of how > > to word it, > > > Below is the code (if it is lousy its because I've mainly been > > borrowing by examples as I go...) Any suggestions are gretly > > appreciated. > > > #!/usr/local/bin/python > > > from Tkinter import * > > from string import * > > from Image import * > > DON'T DO THAT... > > You're importing everything to the current namespace and this corrupts > the current namespace, specifically the 'open' function inside > Image.open would shadow the built-in 'open' function. > > use: > import Tkinter > import string > import Image > > There are use cases where doing 'from blah import *' is useful, such > as importing constants, but in general try to avoid importing > everything to current namespace. > > > root = Tk() > > root.title('Canvas') > > If you used 'import Tkinter', you'd have to change that code to: > root = Tkinter.Tk() > > > #open commodore Cset rom > > cset ?= open("chargen","r") > > Because you shadowed the built-in 'open' with the 'from Image import > *', this would call Image.open instead of the built-in open. > > > canvas = Canvas(width=16, height=16, bg='white') > > If you used 'import Tkinter', you'd have to change that code to: > canvas = Tkinter.Canvas(...) > > > canvas.pack(expand=YES, fill=BOTH) > > > # character size factor > > size = 2 > > > # read all 512 characters from ROM > > for cchar in range(0, 511, 1): > > You can use this instead: > for cchar in range(511): > > but beware, this creates range with length 511 (so do the original > range), which means you're lacking on space for the last char. > You probably wanted this instead: > for cchar in range(512): > > But again, python can loop directly over string/list/file, etc, so > this might be best: > for char in cset.read(): > > > ? ? #draw line > > ? ? while charline < 8: > > ? ? ? ? position = 0 > > ? ? ? ? x = cset.read(1) > > ? ? ? ? ch = ord(x) > > ? ? ? ? # draw pixels > > ? ? ? ? while position < 8: > > ? ? ? ? ? ? if ch & ( 2 ** position ): > > ? ? ? ? ? ? ? ? xp = 1+(7-position)*size > > ? ? ? ? ? ? ? ? yp = 1+charline*size > > ? ? ? ? ? ? ? ? canvas.create_rectangle(xp,yp,xp+size,yp+size, > > fill='black', width=0) > > ? ? ? ? ? ? position += 1 > > Since you're planning to use Image module (from PIL/Python Imaging > Library) why not use functions from Image instead to create the image. > The format of the file you're using seems to be RAW format (i.e. > simple uncompressed bitmap, without any kinds of header). That means > Image.fromstring() should work. > > > ? ? ? ? charline += 1 > > ? ? #save character image > > ? ? outfile = "/home/mydir/work/char"+zfill(cchar,3)+".png" > > ? ? canvas.save(outfile,"png") > > ? ? #clear canvas for next char... > > ? ? canvas.create_rectangle(1,1,size*8,size*8, fill='white', width=0) > > root.mainloop() > > btw, PIL Handbook is a good tutorial/reference for Python Imaging Library: http://www.pythonware.com/library/pil/handbook/index.htm for info on raw mode: http://www.pythonware.com/library/pil/handbook/decoder.htm From timothywayne.cook at gmail.com Thu Jun 19 14:56:47 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Thu, 19 Jun 2008 15:56:47 -0300 Subject: Python Package Construction Message-ID: <1213901807.2875.95.camel@localhost.localdomain> Hi All, I would like feedback on the proper/best 'Pythonic' approach. This is a rather subjective question. Where is the trade-off between package name lengths and faithfulness to the specifications? [Discussion follows] I am implementing a set of specifications for healthcare IT for Python programmers to be able to develop interoperable healthcare applications. I am using ZCA (aka.Zope3) extensively. My desire is to implement the specs as faithfully as possible for two reasons: 1) teachability - how easy/difficult is it to teach the framework and specifications to new developers? 2) maintainability - which approach, if either, will make it easier to maintain the framework if/when the specifications change? My first pass was to develop a skeleton of the specs using Interfaces from the ZCA approach and then the implementations following the document structure of the specs. The specs are available via SVN at: http://www.openehr.org/svn/specification/TRUNK/publishing/architecture/ It is best to probably use real examples. Following the document structure for packaging AND using the ZCA convention of having a sub-directory for interfaces caused massive circular import issues due to some classes being used in the interface definition of classes inside the same interface file being imported into the implementation file. If that sounds confusing; it is. It was confusing to write too. :-) If anyone has questions I'll try to expand. It is best to probably use specific, real examples. http://www.openehr.org/svn/specification/TRUNK/publishing/architecture/rm/data_types_im.pdf (note class names are converted from the upper case, underscore separated style to CamelCase) The package openehr.rm.datatypes.text defines the implementation class CodePhrase. The associated interface file openehr.rm.datatypes.interfaces.text needed CodePhrase as an attribute type in DvCodedText and TermMapping needs both CodePhrase and DvCodedText. This quickly got out of control. So my solution to solving the circular imports is to take each interface and implementation and put them into one file. Research tells me that this is probably the second mostly popular ZCA approach. So, ICodePhrase and CodePhrase are now in openehr/rm/datatypes/codephrase.py, DvCodeText and IDvCodedText in openehr/rm/datatypes/dvcodedtext.py, etc. But wait, now I don't have a 'text package'. So if codephrase.py and dvcodedtext.py were in openehr/rm/datatypes/text/ that would solve the problem. BUT! Throughout the specs many of the names are VERY long already. Adding another package name that is from 4 - 15 (or more) characters long adds to the length of already long import statements, i.e. (sorry for the email line wraps) from openehr.am.archetype.creferenceobject import ICReferenceObject,CReferenceObject should really be from openehr.am.archetype.constraintmodel.creferenceobject import ICReferenceObject,CReferenceObject Thoughts, opinions and jeers all gratefully accepted. :-) --Tim -- Timothy Cook, MSc Health Informatics Research & Development Services LinkedIn Profile:http://www.linkedin.com/in/timothywaynecook Skype ID == timothy.cook ************************************************************** *You may get my Public GPG key from popular keyservers or * *from this link http://timothywayne.cook.googlepages.com/home* ************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From gagsl-py2 at yahoo.com.ar Mon Jun 2 21:49:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 02 Jun 2008 22:49:47 -0300 Subject: Compare 2 files and discard common lines References: <8d55718c-6881-4844-b8d1-bbe1c5929f46@x35g2000hsb.googlegroups.com> <740c3aec0805291408w40eb3ca1ma07be5c62fe5a63d@mail.gmail.com> Message-ID: 2008/5/29, loial : >> I have a requirement to compare 2 text files and write to a 3rd file >> only those lines that appear in the 2nd file but not in the 1st file. En Thu, 29 May 2008 18:08:28 -0300, BJ?rn Lindqvist escribi?: > Open('3rd','w').writelines(set(open('2nd').readlines())-set(open('1st'))) Is the asymmetry 1st/2nd intentional? I think one could omit .readlines() in 2nd file too. -- Gabriel Genellina From beema.shafreen at gmail.com Sat Jun 14 03:15:47 2008 From: beema.shafreen at gmail.com (Beema shafreen) Date: Sat, 14 Jun 2008 12:45:47 +0530 Subject: sorting a file Message-ID: Hi all, I have a file with three columns i need to sort the file with respect to the third column. How do I do it uisng python. I used Linux command to do this. Sort but i not able to do it ? can any body ssuggest me -- Beema Shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From danb_83 at yahoo.com Fri Jun 20 23:48:47 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Fri, 20 Jun 2008 20:48:47 -0700 (PDT) Subject: Weird local variables behaviors References: Message-ID: <8e8a1d67-4d5f-4b52-a1aa-5a08f9530b75@y21g2000hsf.googlegroups.com> On Jun 20, 7:32?pm, Matt Nordhoff wrote: > Sebastjan Trepca wrote: > > Hey, > > > can someone please explain this behavior: > > > The code: > > > def test1(value=1): > > ? ? def inner(): > > ? ? ? ? print value > > ? ? inner() > > > def test2(value=2): > > ? ? def inner(): > > ? ? ? ? value = value > > ? ? inner() > > > test1() > > test2() > > > [trepca at sauron ~/dev/tests]$ python locals.py > > 1 > > Traceback (most recent call last): > > ? File "locals.py", line 13, in > > ? ? test2() > > ? File "locals.py", line 10, in test2 > > ? ? inner() > > ? File "locals.py", line 9, in inner > > ? ? value = value > > UnboundLocalError: local variable 'value' referenced before assignment > > > Why can't he find the variable in the second case? > > > Thanks, Sebastjan > > Python doesn't like when you read a variable that exists in an outer > scope, then try to assign to it in this scope. > > (When you do "a = b", "b" is processed first. In this case, Python > doesn't find a "value" variable in this scope, so it checks the outer > scope, and does find it. But then when it gets to the "a = " part... > well, I don't know, but it doesn't like it.) In a language like C++, the scope of a variable is determined by the declaration. int x; // A class Example { int x; // B void f() { int x; // C x = 42; // Which x? } }; The "x" referred to in the statement "x = 42;" refers to local variable of Example::f. If line C were removed, then it would refer to the member variable of class Example. And if line B were removed, then it would refer to the global variable. In Python, however, there are no declarations. Therefore, it requires another approach. What it chose was: (1) Explicit "self" for object attributes. (2) A function's local variables are defined as those appearing on the left side of an assignment. Whether the name happens to refer to a global is NOT considered. From mr.edel at gmx.at Tue Jun 3 06:22:58 2008 From: mr.edel at gmx.at (Matt) Date: Tue, 03 Jun 2008 10:22:58 +0000 Subject: ctypes, function pointers and a lot of trouble References: Message-ID: Hello! ouch, I should have seen that c_char... :S Well, I guess I just prove that it's useless to go to work and do some programming while having a headache like I had yesterday... okay well, back to topic: The DLL function seems to accept my parameters now, but unfortunately Python terminates after the DLL gets the result from the "open" callback function (at least its printouts are the last I get before it terminates). So without any kind of error message it's getting more difficult now. Well, since I didn't invest much time into my callback functions I suspect the error must be somewhere in there. This is my code: ------------------------------CODE----------------------------------------- class MemStreamData(Structure): _fields_ = [("mode", c_byte), ("lPos", c_uint), ("dwVisibleSize", c_uint), ("dwBufferSize", c_uint), ("cpBuffer", POINTER(c_char))] class FilStreamData (Structure): _fields_ = [("szFileName", c_char * 30), ("hFile", c_uint)] def pystreamopen (contextH, mode, pErr=0): print "opening..." print contextH print mode print pErr return 0 cstreamopen = CFUNCTYPE(c_uint, c_ushort, c_uint) def pystreamclose (contextH, pErr): print "closing..." return 0 cstreamclose = CFUNCTYPE(c_uint, c_uint) def pystreamread (contextH, pBuf, pBufsize, pErr): print "reading..." return 0 cstreamread = CFUNCTYPE(c_uint, c_void_p, c_uint, c_uint) def pystreamtell (contextH, pErr): print "telling..." return 0 cstreamtell = CFUNCTYPE(c_uint, c_uint) def pystreamseek (contextH, origin, offset, pErr): print "seeking..." return 0 cstreamseek = CFUNCTYPE(c_uint, c_uint, c_uint, c_uint) def pystreamwrite (contextH, origin, offset, pErr): print "writing..." return 0 cstreamwrite = CFUNCTYPE(c_uint, c_void_p, c_uint, c_uint) class cdStream(Structure): _fields_ = [("contextH", POINTER(MemStreamData)), ("open", cstreamopen), ("close", cstreamclose), ("read", cstreamread), ("write", cstreamwrite), ("seek", cstreamseek), ("tell", cstreamtell)] -----------------------------/CODE----------------------------------------- This is the way I create the vars: ------------------------------CODE----------------------------------------- databuf = create_string_buffer(100000) cbuffer=MemStreamData() cbuffer.mode = c_byte(0) cbuffer.lPos = c_uint(0) cbuffer.dwVisibleSize = 100000 cbuffer.dwBufferSize = 100000 cbuffer.cpBuffer = databuf stream = cdStream() stream.contextH = POINTER(MemStreamData)(cbuffer) stream.open = cstreamopen(pystreamopen) stream.close = cstreamclose(pystreamclose) stream.write = cstreamwrite(pystreamwrite) stream.tell = cstreamtell(pystreamtell) stream.read = cstreamread(pystreamread) data = cdStgMedium() data.Type = c_uint(1) # 0...FilStream 1...MemStream data.u.pStream = POINTER(cdStream)(stream) errorcode = cdsdk.CDGetReleasedData(devicehandle, byref(cbfunct), c_uint(0), c_uint(0), byref(datainfo), POINTER(cdStgMedium)(data)) ------------------------------/CODE----------------------------------------- Now I have two problems: 1st: since contextH is not a c_uint (and pErr is a pointer) as I thought earlier, I tried to change my definition of the open function to: cstreamopen = CFUNCTYPE(POINTER(MemStreamData), c_ushort, POINTER(c_uint)) unfortunately that throws an error when I try to: stream.open = cstreamopen(pystreamopen) 2nd: as may saw, I defined "def pystreamopen (contextH, mode, pErr=0)". The pErr variable should be a pointer to a c_uint where my function can tell the DLL that opening the stream went well (or give some errorcode). When I do not define pErr=0 and simply say pErr, I get the following error: Traceback (most recent call last): File "\loewis\25\python\Modules\_ctypes\callbacks.c", line 206, in 'calling callback function' TypeError: pystreamopen() takes exactly 3 arguments (2 given) At first I thought okay, maybe there's no pErr and there's some error in the C-Code, but when I do "def pystreamopen (contextH, mode)" I get the same Error with: TypeError: pystreamopen() takes exactly 3 arguments (2 given) Any ideas? And another question: my callback functions are all defined as void... in C. That means that there shouldn't be anything returned. I tried this by using the pass statement, but got an error that returntype int was expected. Also "return" or "return None" don't work. Why? Puh, long mail again... hope you're so kind again and take the time to help me out. Best regards from Austria, Matt From spoier at gmail.com Mon Jun 9 18:35:56 2008 From: spoier at gmail.com (Skye) Date: Mon, 9 Jun 2008 15:35:56 -0700 (PDT) Subject: Question by someone coming from C... References: Message-ID: <20e41490-ef8f-44de-b1cd-a2f678fdd28b@w5g2000prd.googlegroups.com> Very cool - I'm liking the pythonic way of doing things more and more. The logger namespace/singleton idea makes great sense! I see how the module variables make globals irrelevant, thanks! Skye From info at thegrantinstitute.com Sat Jun 7 00:50:30 2008 From: info at thegrantinstitute.com (Anthony Jones) Date: 06 Jun 2008 21:50:30 -0700 Subject: Professional Grant Proposal Writing Workshop (August 2008: Ann Arbor, Michigan - University of Phoenix Campus) Message-ID: <20080606215029.D038B49E2FD2CAAE@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From roopesh.raj at gmail.com Wed Jun 25 11:11:13 2008 From: roopesh.raj at gmail.com (Roopesh) Date: Wed, 25 Jun 2008 08:11:13 -0700 (PDT) Subject: Problems with file IO in a thread, and shutil Message-ID: Hi, I have a multithreaded application. There are two threads, T1 and T2. Suppose that there are two folders A, B. Thread T1 fetches data from network and creates files in folder A and after creating each file, it moves the file to folder B, using shutil.move(). Thread T2, takes files from folder B and processes it. Note: Only the thread T1 has access to the files in folder A. psuedo code ========= class T1(thread): def run(): self.download() def download(): data = from_network filename = os.path.join ( "A", "file1") f = open ( filename, "w") for d in data: f.write ( d + "\n" ) f.flush() f.close() shutil.move(os.path.join ( "A", "file1"), os.path.join("B", "file1")) class T2(thread): run() process(listdir(os.path.join("B"))) All the files has similar contents. But in some cases(very rare), when thread T1 tries to move the newly created file from folder A to folder B, an exception occurs (on shutil.move()). The exception is WindowsError(32, 'The process cannot access the file because it is being used by another process'). I looked inside the shutil.move. What I found was due to this WindowsError, the usual os.rename() inside shutil.move() fails and the file is copied using copy2(src, dst). Finally os.unlink() also failed. (So though copying occurred, deleting the source file failed) I am not getting why this error comes. Has anyone faced similar situation? Please help me. Thanks and Regards Roopesh From mensanator at aol.com Thu Jun 19 16:47:13 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 19 Jun 2008 13:47:13 -0700 (PDT) Subject: python/ruby question.. References: <3b017f08-2d42-4c65-9003-19ffc606234d@l64g2000hse.googlegroups.com> Message-ID: <7a6d9240-8caa-440b-81c3-1619e507ece4@2g2000hsn.googlegroups.com> On Jun 19, 5:14?am, Matt Nordhoff wrote: > Mensanator wrote: > You're supposed to use the subprocess module. Yeah, I know, but I couldn't get it to work the last time I tried it. > > In this case, something like: > > import subprocess > factor_program = ['factor!', '-d200'] > > ... > > p = subprocess.Popen(factor_program + [n], stdout=subprocess.PIPE) > p.wait() # wait for it to finish; not sure how necessary it is > the_output = p.stdout.readlines() Just like how this doesn't work either: Traceback (most recent call last): File "C:\Program Files\PyGTK\Python\user\factor_timing.py", line 26, in p = subprocess.Popen(factor_program + [the_comp[1]], stdout=subprocess.PIPE) File "C:\Program Files\PyGTK\Python\lib\subprocess.py", line 586, in __init__ errread, errwrite) = self._get_handles(stdin, stdout, stderr) File "C:\Program Files\PyGTK\Python\lib\subprocess.py", line 681, in _get_handles p2cread = self._make_inheritable(p2cread) File "C:\Program Files\PyGTK\Python\lib\subprocess.py", line 722, in _make_inheritable DUPLICATE_SAME_ACCESS) TypeError: an integer is required > > See subprocess's documentation [1], which includes guides on replacing > os.popen* and other functions with it. I have seen it - it's utterly incomprehensible. What do you suppose you did wrong? The complete program (with the deprecated code commented out - which works, BTW): #import os import time import subprocess #factor_program = 'factor! -d200 ' factor_program = ['factor!','-d200'] the_composites = [['COMPOSITE_FACTOR','50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749']] the_primes = [] the_intractables = [] phase = 1 the_times = [] while the_composites: print "="*40 print 'Phase',phase the_comp = the_composites.pop(0) print the_comp print the_times.append(time.time()) # time how long it takes to run factor!.exe #the_output = os.popen(factor_program+the_comp[1]).readlines() # change to subprocess p = subprocess.Popen(factor_program + [the_comp[1]], stdout=subprocess.PIPE) p.wait() the_output = p.stdout.readlines() the_times.append(time.time()) new_factors = [i.split() for i in the_output] for i in new_factors: print i print if len(new_factors) == 1: if new_factors[0][0] == 'PRIME_FACTOR': the_primes.append([new_factors[0][0],long(new_factors[0][1])]) else: the_intractables.append([new_factors[0][0],long(new_factors[0] [1])]) new_factors.pop() while new_factors: j = new_factors.pop(0) if j[0] == 'PRIME_FACTOR': the_primes.append([j[0],long(j[1])]) else: the_composites.append(j) print the_times[phase] - the_times[phase-1],'seconds' phase += 1 print "="*40 print print 'Factoring complete' print the_primes.sort() the_intractables.sort() the_primes.extend(the_intractables) for i in the_primes: print i[0],i[1] print print "="*40 When working, it produces: ## ======================================== ## Phase 1 ## ['COMPOSITE_FACTOR', '50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749'] ## ## ['PRIME_FACTOR', '37'] ## ['PRIME_FACTOR', '43'] ## ['PRIME_FACTOR', '167'] ## ['COMPOSITE_FACTOR', '507787751'] ## ['PRIME_FACTOR', '69847'] ## ['PRIME_FACTOR', '30697'] ## ['PRIME_FACTOR', '89017'] ## ['PRIME_FACTOR', '3478697'] ## ['PRIME_FACTOR', '434593'] ## ['PRIME_FACTOR', '49998841'] ## ['PRIME_FACTOR', '161610704597143'] ## ['PRIME_FACTOR', '14064370273'] ## ['COMPOSITE_FACTOR', '963039394703598565337297'] ## ['PRIME_FACTOR', '11927295803'] ## ## 0.860000133514 seconds ## ======================================== ## Phase 2 ## ['COMPOSITE_FACTOR', '507787751'] ## ## ['PRIME_FACTOR', '29819'] ## ['PRIME_FACTOR', '17029'] ## ## 0.0780000686646 seconds ## ======================================== ## Phase 3 ## ['COMPOSITE_FACTOR', '963039394703598565337297'] ## ## ['PRIME_FACTOR', '518069464441'] ## ['PRIME_FACTOR', '1858900129817'] ## ## 0.0469999313354 seconds ## ======================================== ## ## Factoring complete ## ## PRIME_FACTOR 37 ## PRIME_FACTOR 43 ## PRIME_FACTOR 167 ## PRIME_FACTOR 17029 ## PRIME_FACTOR 29819 ## PRIME_FACTOR 30697 ## PRIME_FACTOR 69847 ## PRIME_FACTOR 89017 ## PRIME_FACTOR 434593 ## PRIME_FACTOR 3478697 ## PRIME_FACTOR 49998841 ## PRIME_FACTOR 11927295803 ## PRIME_FACTOR 14064370273 ## PRIME_FACTOR 518069464441 ## PRIME_FACTOR 1858900129817 ## PRIME_FACTOR 161610704597143 ## ## ======================================== From hall.jeff at gmail.com Mon Jun 23 14:55:35 2008 From: hall.jeff at gmail.com (hall.jeff at gmail.com) Date: Mon, 23 Jun 2008 11:55:35 -0700 (PDT) Subject: socket error: connection refused? References: <51343a50-1891-48be-99ad-3618310dca97@34g2000hsh.googlegroups.com> Message-ID: <5277a799-16b2-4857-81b7-a9cd1bc15b73@t54g2000hsg.googlegroups.com> It's a security conflict. You should be able to run it again and have it work. Our company's cisco does the same thing (even after we approve the app) From Sengly.Heng at gmail.com Wed Jun 11 13:10:32 2008 From: Sengly.Heng at gmail.com (Sengly) Date: Wed, 11 Jun 2008 10:10:32 -0700 (PDT) Subject: Finding a sense of word in a text Message-ID: Dear all, This might be off group but I am looking for a python library that can help me to find a sense of a word in a text and eventually a list of synonyms of that term. I searched the web and found one but it is written in perl (http://www.d.umn.edu/~tpederse/senserelate.html) :( I appreciate any pointers. Thank you before hand. Kind regards, Sengly From vronskij at gmail.com Tue Jun 3 16:56:36 2008 From: vronskij at gmail.com (vronskij at gmail.com) Date: Tue, 3 Jun 2008 13:56:36 -0700 (PDT) Subject: Q about object identity Message-ID: Hello, I am testing object identity. If I do it from the interpreter, I get strange results. >>> print [] is [] False >>> print id([]), id([]) 3083942700 3083942700 Why is that? Isn't this an error? If I test it in a script, all is OK. #!/usr/bin/python a = [] b = [] print a == b print a is b print id(a), id(b) print id(None), id(None) print id(True), id(True) On my computer, I got these results: True False 3083769036 3083793516 135553336 135553336 135526444 135526444 All as expected. jan bodnar From exarkun at divmod.com Sun Jun 15 19:58:59 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 15 Jun 2008 19:58:59 -0400 Subject: The best way to package a Python module? In-Reply-To: <87od629vbb.fsf@benfinney.id.au> Message-ID: <20080615235859.4714.602158763.divmod.quotient.9503@ohm> On Mon, 16 Jun 2008 08:39:52 +1000, Ben Finney wrote: >Jean-Paul Calderone writes: > >> On Mon, 16 Jun 2008 01:37:47 +0900, js wrote: >> >By "package", I meant APT, Ports for BSD, MacPorts, etc. >> >> I don't know about ports or macport, but Debian has recently >> switched to a different policy for python packages which does not >> involve as many Python version specific copies of things. You might >> want to look at "python-central" and stdeb. > >The version-specific copies are still there in the latest Debian >practices. That's a necessary artefact of the per-version >site-packages of Python. > >What has changed is that the tools in common use for Debian packaging >of Python libraries have taken on the role of generating those >per-version copies at install time. > >This means that, for pure-Python libraries, the source package need >only contain a version-independent source and a declaration of which >Python versions it should be installed for. The installation tool will >take care of making the per-version copies in various places. Maybe. I'm no expert on Debian packaging. However, exarkun at boson:~$ ls -l /usr/lib/python2.{4,5}/site-packages/sqlite/main.py lrwxrwxrwx 1 root root 63 2007-12-27 15:29 /usr/lib/python2.4/site-packages/sqlite/main.py -> /usr/share/pycentral/python-sqlite/site-packages/sqlite/main.py lrwxrwxrwx 1 root root 63 2007-12-27 15:29 /usr/lib/python2.5/site-packages/sqlite/main.py -> /usr/share/pycentral/python-sqlite/site-packages/sqlite/main.py exarkun at boson:~$ That doesn't seem to agree with your statement. Am I missing something? Jean-Paul > >-- > \ "Nothing so needs reforming as other people's habits." -- Mark | > `\ Twain, _Pudd'n'head Wilson_ | >_o__) | >Ben Finney >-- >http://mail.python.org/mailman/listinfo/python-list > From cokofreedom at gmail.com Mon Jun 23 11:01:28 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 23 Jun 2008 08:01:28 -0700 (PDT) Subject: String question References: Message-ID: <695fec18-8a3a-48e1-b467-d4957f9065fa@26g2000hsk.googlegroups.com> On Jun 23, 4:45 pm, Andreu wrote: > I want to split a sentence and assign each word to a variable. > In Ruby I can do it as: > > v1,v2,v3,v4,v5 = str1.split > > Which will be the Python equivalent ? Thanks. > > Andrew. Well a straight copy would be... >>> example = "Hello, how are you" >>> v1, v2, v3, v4 = example.split() >>> print v1, v2, v3, v4 Hello, how are you >>> print v1 Hello, However I would make a list of it. >>> v_list = example.split() >>> print v_list ['Hello,', 'how', 'are', 'you'] >>> for word in v_list: print word Hello, how are you That seems to me to be the more pythonic way to do it, since it is dynamic. From bruno.42.desthuilliers at websiteburo.invalid Thu Jun 5 07:53:55 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 05 Jun 2008 13:53:55 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> Message-ID: <4847d39d$0$7614$426a74cc@news.free.fr> Russ P. a ?crit : >(snip) > (answering to Carl Bank) I thought you were saying that encapsulation or so-called "data > hiding" is worthless. As far as I'm concerned, I view encapsulation as very desirable, and data-hidding as totally worthless when applied to Python's object model. > Here's what I think Python should have. I think it should have a > keyword, something like "priv," to identify data or functions as > "private." As I said earlier, "private" for class data or functions > ("methods") could be implemented like "protected" in C++. That means > that derived classes would have access to it, but clients of the class > would not. If the client really needs or wants access, he could be > given a sort of "back door" access similar to the current Python rule > regarding double leading underscores. Thus, the client would have > access, but he would know very well that he is using something that > the original designer did not intend for him to use. > It's just a suggestion. I'm not a language expert, and I realize that > I could be missing something important. Given your very recent discovery of what 'dynamic' *really* means in Python (like, for exemple, dynamically adding / replacing attributes - including methods - on a per-class or per-instance basis), possibly, yes. > I also realize, by the way, that Python allows a client of a class to > define a new class member from completely outside the class > definition. Obviously, that cannot be declared private. Why so ? > But if the > same identifier is already declared private within the class, than the > new definition should not be allowed (because it would defeat the > whole idea of "private" class members). Why so ? Metaprogramming (including monkeypatching) is part of the pythoneer's toolbox, and while it's not something to use without pretty good reasons, it has many times proven to be a real life saver. In languages not allowing it, the solutions to the class of problems easily solved by monkeypatching happens to be at best a kludge, at worst plain unsolvable, at least without too much effort to be even worth it. Your above proposition would arbitrarily make possible and useful things either uselessly complicated or near impossible. From drobinow at gmail.com Tue Jun 10 14:21:42 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Tue, 10 Jun 2008 11:21:42 -0700 (PDT) Subject: Python doesn't understand %userprofile% References: Message-ID: On Jun 10, 2:09 pm, Duncan Booth wrote: > bsag... at gmail.com wrote: > > In xp when I try os.path.getmtime("%userprofile/dir/file%") Python > > bites back with "cannot find the path specified" Since my script has > > to run on machines where the username is unspecified I need a fix. > > Thanks in advance. > >>> os.path.expanduser("~/dir/file") > > 'C:\\Documents and Settings\\Duncan/dir/file' "~" appears to look first at the HOME environment variable. That is not necessarily the same as "USERPROFILE". On my machine it is not. From ark at acm.org Sun Jun 1 11:30:18 2008 From: ark at acm.org (Andrew Koenig) Date: Sun, 01 Jun 2008 15:30:18 GMT Subject: Python's doc problems: sort References: <929d5ce9-9063-4e6c-98aa-89526f89fba3@y18g2000pre.googlegroups.com> Message-ID: wrote in message news:929d5ce9-9063-4e6c-98aa-89526f89fba3 at y18g2000pre.googlegroups.com... > I want to emphasize a point here, as i have done quite emphatically in > the past. The Python documentation, is the world's worst technical > writing. As far as technical writing goes, it is even worse than > Perl's in my opinion. I think that this claim says more about its author than it does about its subject. Welcome to my killfile. From apardon at forel.vub.ac.be Wed Jun 11 06:30:39 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 11 Jun 2008 10:30:39 GMT Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <6e6df35e-e641-44d9-9f56-c0732306eec2@q27g2000prf.googlegroups.com> <98ce48ed-c7c7-43c5-8c9c-f08628a2e98e@y22g2000prd.googlegroups.com> Message-ID: On 2008-06-10, Rhamphoryncus wrote: > On Jun 10, 1:55 am, Antoon Pardon wrote: >> On 2008-06-09, Rhamphoryncus wrote: >> >> >> >> > On Jun 9, 5:33 am, Antoon Pardon wrote: >> >> On 2008-06-07, Rhamphoryncus wrote: >> >> >> > On Jun 6, 12:44 pm, The Pythonista wrote: >> >> >> It's always been my understanding that you can't forcibly kill a thread >> >> >> in Python (at least not in a portable way). The best you can do is >> >> >> politely ask it to die, IIRC. >> >> >> > Inherently, the best you can do in most languages is ask them politely >> >> > to die. Otherwise you'll leave locks and various other datastructures >> >> > in an inconvenient state, which is too complex to handle correctly. >> >> > The exception is certain functional languages, which aren't capable of >> >> > having threads and complex state in the same sense. >> >> >> Well it would of course depend on what is considered asking politely? >> >> >> If one thread could cause an exception being thrown in an other thread, >> >> would this be considered a polite way to ask? Would it be considered >> >> an acceptable way? >> >> > The exception must not be raised until a point explicitly designed as >> > safe is hit. Otherwise, any function that manipulates data you'll >> > still use will potentially be buggered. Consider sys.stdout: codecs, >> > buffering, lots to go wrong. >> >> I don't see the point. Exceptions are raised now without the ability >> of an explicitly designed safe point. If something unexpected happens >> your code can raise an exception and leave your data buggered too if >> you didn't anticipate it propely. > > Although in theory you could get any exception at any point, in > practise you shouldn't unless your program is broken. If it is broken > the exceptions shouldn't be caught and should cause the program to > terminate, so the harm is reduced. The exceptions that should happen > (such as IOError) should be from predicted points, and anticipated. In pratice you can schedule an alarm and have the alarm handler raise an exception in your code. It is the resposibility of the developer to write his code in such a way that it can handle such an interruption as it should. Given that the above is already possible I don't see why we should protect the programmer from such an asynchronous exception merely because they can be raised from an other thread. -- Antoon Pardon From calvin.cheng at od-eon.com Thu Jun 19 12:14:03 2008 From: calvin.cheng at od-eon.com (Calvin Cheng) Date: Fri, 20 Jun 2008 00:14:03 +0800 Subject: Getting Python to run Python Scripts in cygwin Message-ID: <719d28270806190914t38c3eb55gec5f7f3f8613b560@mail.gmail.com> Hi guys, This may be a cygwin issue but I was hoping to get some answers here as well if someone has fixed this problem before. Basically, I am able to run "python .py" python files in command prompt. Unfortunately, I can't seem to get it to work in cygwin. I always get an error that says: python: can't open file '.py': [Errno 2] No such file or directory I have looked at my environment variables and it seems to be correct. Would be grateful if someone who has gotten python to work correctly on cygwin could point me in the right direction. It is very cumbersome switching back-and-forth between command prompt and cygwin just to run python scripts. Thank you in advance, Calvin From mike at ipglobal.net Tue Jun 3 10:29:26 2008 From: mike at ipglobal.net (Support Desk) Date: Tue, 3 Jun 2008 09:29:26 -0500 Subject: regex help In-Reply-To: References: <0ac601c8c57e$3c9d6bc0$a501a8c0@office.ipglobal.net> <0ada01c8c583$24f60630$a501a8c0@office.ipglobal.net> Message-ID: <0ade01c8c586$39816510$a501a8c0@office.ipglobal.net> That?s it exactly..thx -----Original Message----- From: Reedick, Andrew [mailto:jr9445 at ATT.COM] Sent: Tuesday, June 03, 2008 9:26 AM To: Support Desk Subject: RE: regex help The regex will now skip anything with an '@'in the filename on the assumption it's already in the correct format. Uncomment the os.rename line once you're satisfied you won't mangle anything. import glob import os import re for filename in glob.glob('*.abook'): newname = filename newname = re.sub(r'^[^@]+\.abook$', '@domain.com.abook', filename) if filename != newname: print "rename", filename, "to", newname #os.rename(filename, newname) > -----Original Message----- > From: Support Desk [mailto:mike at ipglobal.net] > Sent: Tuesday, June 03, 2008 10:07 AM > To: Reedick, Andrew > Subject: RE: regex help > > Thx for the reply, > > I would first have to list all files matching user.abook then rename > them to > user at domain.com.abook something like Im still new to python and haven't > had > much experience with the re module > > import os > import re > > emails = os.popen('ls').readlines() > for email in emails: > print email, '-->', > print re.findall(r'\.abook$', email) > > > > -----Original Message----- > From: Reedick, Andrew [mailto:jr9445 at ATT.COM] > Sent: Tuesday, June 03, 2008 8:52 AM > To: Support Desk; python-list at python.org > Subject: RE: regex help > > > From: python-list-bounces+jr9445=att.com at python.org > > [mailto:python-list-bounces+jr9445=att.com at python.org] > > On Behalf Of Support Desk > > Sent: Tuesday, June 03, 2008 9:32 AM > > To: python-list at python.org > > Subject: regex help > > > > I am trying to put together a regular expression that will > > rename users address books on our server due to a recent > > change we made.? Users with address books user.abook need > > to be changed to user at domain.com.abook I'm having trouble > > with the regex. Any help would be appreciated. > > > import re > > emails = ('foo.abook', 'abook.foo', 'bob.abook.com', 'john.doe.abook') > > for email in emails: > print email, '-->', > print re.sub(r'\.abook$', '@domain.com.abook', email) > > > > ***** > > The information transmitted is intended only for the person or entity > to > which it is addressed and may contain confidential, proprietary, and/or > privileged material. Any review, retransmission, dissemination or other > use > of, or taking of any action in reliance upon this information by > persons or > entities other than the intended recipient is prohibited. If you > received > this in error, please contact the sender and delete the material from > all > computers. GA623 > > From paul at boddie.org.uk Fri Jun 20 18:42:00 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 20 Jun 2008 15:42:00 -0700 (PDT) Subject: How do I create a new Node using pulldom? References: Message-ID: <55fd3d79-5865-4f2d-a534-9472c60d78d8@b1g2000hsg.googlegroups.com> On 20 Jun, 22:17, "susan_... at hotmail.com" wrote: > I'm using xml.dom.pulldom to parse through an XML file. I use > expandNode() to scrutinize certain blocks of it that I'm interested > in. Right. This is the thing which differentiates pulldom from traditional DOM implementations, which I'll discuss below. > Once I find a block of XML in the input file that I'm interested in, I > need to add my own block ..... to the pulldom tree I'm > building in memory. Understood. > The documentation on PullDom is worse than atrocious. It is simply non- > existant. I can't even find a simple explanation of what the functions > are named and what arguments they take. Sheesh. Sheesh, indeed. I think the authors assumed a familiarity with the DOM APIs, but they're regarded as being somewhat "old school" by many these days, so it's possible that you aren't too familiar with the PyXML/DOM style of the API employed. > When I have a node N of the tree, I think that I can use > N.appendChild() to do what I want (just guessing from the function > name which I can see). > > appendChild takes 1 argument -- a new node. Correct. I think that you also need to have expanded the part of the document where the node will be placed. For example: stream = xml.dom.pulldom.parseString(s) for event, node in stream: if : stream.expandNode(node) > But I don't know how to create such a node. This is a traditional DOM activity, but it's easy to be disoriented if you don't already have a document object (which has the necessary methods). However, such an object is readily available: doc = node.ownerDocument You can then create a node using the usual create* methods. For example: element = doc.createElement("new") And then you can use appendChild on the original node: node.appendChild(element) Note that since the document under node has been expanded, subsequent nodes pulled from the stream will start with an END_ELEMENT event involving the node concerned. > Can someone out there please post a code fragment showing how to > create a pulldom node? The simpler and more commented it is the > better. Try this: import xml.dom.pulldom s = "xxx" # Start parsing. stream = xml.dom.pulldom.parseString(s) # Process each event. for event, node in stream: # Do the addition of an element within "node". if event == xml.dom.pulldom.START_ELEMENT and \ node.localName == "node": # Have to expand first. stream.expandNode(node) # Get the document and create the element. doc = node.ownerDocument element = doc.createElement("new") # Add the element; see what we've produced. node.appendChild(element) print node.toxml() Hope this helps! Paul From gh at ghaering.de Fri Jun 6 07:21:52 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 06 Jun 2008 13:21:52 +0200 Subject: How to kill a thread? In-Reply-To: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> Message-ID: John Dohn wrote: > Hi there, > > How can I kill a threading.Thread subclass from MainThread? > > My threads are waiting for data in Queue.get() method: > class MyThread(threading.Thread): > def run(self): > while True: > data = queue.get() # <- here it waits most of the time > ... process data > > From the main thread I start several working threads: > thr = MyThread() > thr.start() > ... feed the queue > and at the end for each thread I'd like to do something like thr.kill() > or thr.stop() or thr.destroy() or ... you got the point. I can't figure > out how. > > Is there a way to do it? When I do this, I put a special value in the queue (like None) and in the worker thread, check for the special value and exit if found. Threads can also be marked as "daemon threads" (see docs for threading.Thread objects). This will make the application terminate if only "daemon threads" are left. So best would probably be soemthing like - call setDaemon() when creating worker threads - ... - send all worker/daemon threads None via queue - wait some time, like time.sleep(1.0), to let daemon exit themselves - exit main application -- Gerhard From george.sakkis at gmail.com Tue Jun 17 01:36:55 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 16 Jun 2008 22:36:55 -0700 (PDT) Subject: 2Q's: How to autocreate instance of class;How to check for membership in a class References: <48571086$0$5010$607ed4bc@cv.net> Message-ID: On Jun 16, 9:16?pm, asdf wrote: > So I'm writing a script which will create several instances of User() > class. I want each instance to be named after the login name > of a user. I don't know beforehand how many users the script will > have to create or how they are named. Right now I've created a dictionary > of usernames as keys and objects themselves as values. That's probably the most reasonable representation. It works, > but is very unwieldy, because every time I need to access a value from > within an object I have to do something like dict-user[x].value. It seems you are not aware of being able to name intermediate objects: # name2user: mapping of names to User instances for name in 'Bob', 'John', 'Sue': u = name2user[name] print u.value print u.password ... In the sample above, u refers to whatever name2user[name] refers (hopefully a User instance here), it does not create a copy. Therefore after the assignment you can refer to the user as u instead of name2user[name]. Not only this is easier to read but, unlike statically typed languages, it is faster too. An expression such as "a[b].c[d]" involves (at least) three method calls, so as long as it doesn't change it is faster to compute it once, give it a name and refer to the name afterwards. > My second question is how can I check if object is a member of a class. > so let's say I create a=User(), b=User()... > Can I do something similar to > if x.Users()==TRUE: > ? ? ? ? print "user already created" I am not sure what you mean here. If you want to check whether a user with a given name exists, look it up in the dictionary: if 'Bob' in name2user: ... If you ask how to check if some name x is a User instance, use the isinstance() function: if isinstance(x, User): print x.password Checking for class membership though is usually considered unnecessary or even harmful in Python. Just assume 'x' is a User and use it anyway. George From dstromberglists at gmail.com Sat Jun 28 23:54:53 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Sun, 29 Jun 2008 03:54:53 GMT Subject: C++ or Python References: Message-ID: On Fri, 27 Jun 2008 15:22:26 -0700, Kurda Yon wrote: > I would like to know what are advantages of Python in comparison with C > ++? In which cases and why Python can be a better tool than C++? > > Thank you! Python's automatic tracebacks on errors facilitate debugging very nicely. Python doesn't have much in the way of stray pointer references or out of bounds array references (you'd pretty much have to use a poorly-written extension module to get them), making development in and maintenance of python code much less expensive in human time. Python has garbage collection, which means you don't need to worry much about memory leaks. Python isn't just another curly brace language - it reads more like the pseudocode you'd see scribbled on a white board, perhaps than any other language. Python's a very dynamic language - so there are things where C++ would catch errors for you that Python wouldn't. However, this also means that you don't spend time declaring variables over and over in Python. Also, things like passing a method as a function parameter is a no-brainer (requires extra syntax in java because of the cautious type system - not sure about C++). Python's dynamicity also means that you don't need a clunky mechanism like templates or have to use inheritance just to get type parameters. In python, everything is an object. Not everything has methods, but everything can be stuck into a variable - modules, pieces of code, whatever. Just try to stick an arbitrary header file's expansion into a variable in C++. From sjmachin at lexicon.net Sat Jun 14 06:23:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 14 Jun 2008 03:23:28 -0700 (PDT) Subject: write Python dict (mb with unicode) to a file References: Message-ID: <9da41e26-3e8b-4632-a8eb-419070fd1be4@z24g2000prf.googlegroups.com> On Jun 14, 7:13 pm, dmitrey wrote: > hi all, > what's the best way to write Python dictionary to a file? > > (and then read) > > There could be unicode field names and values encountered. I'm presuming that "field names" means "dictionary keys". If not unicode, are the remainder of the keys and values: strings encoded in ASCII? strings encoded otherwise? neither str nor unicode? > Thank you in advance, D. "Best" depends on how you measure it. cPickle is one alternative (ensure you use protocol=-1). Speed should be OK, but format not documented AFAIK other than in the source code, so not readable outside the Python universe. Also it won't matter what types of data you have. A portable alternative (and simple enough if all your data are str/ unicode) would be to encode all your strings as UTF-8, and then write the key/value pairs out to a csv file: # untested pseudocode for basestring-only case: for k, v in mydict.iteritems(): csv_writer.writerow((k.encode('utf8'), v.encode('utf8'))) # if you have str instances encoded other than in ASCII or your system's default encoding, you'll have to work a bit harder ... Cheers, John From ram.rachum at gmail.com Mon Jun 16 16:47:48 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Mon, 16 Jun 2008 13:47:48 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> <5b63ca4c-b9f8-4b71-8b0f-ea7ad33010fd@l64g2000hse.googlegroups.com> Message-ID: <551d7b5a-73bc-4574-956f-44ebf56311d8@s50g2000hsb.googlegroups.com> On Jun 16, 12:57?am, "ram.rac... at gmail.com" wrote: > On Jun 15, 11:30?pm, Christian Heimes wrote: > > > > > ram.rac... at gmail.com wrote: > > > I have a physical system set up in which a body is supposed to > > > accelerate and to get very close to lightspeed, while never really > > > attaining it. After approx. 680 seconds, Python gets stuck and tells > > > me the object has passed lightspeed. I put the same equations in > > > Mathematica, again I get the same mistake around 680 seconds. So I > > > think, I have a problem with my model! Then I pump up the > > > WorkingPrecision in Mathematica to about 10. I run the same equations > > > again, and it works! At least for the first 10,000 seconds, the object > > > does not pass lightspeed. > > > I concluded that I need Python to work at a higher precision. > > > I conclude that your algorithm is numerical wrong. It probably suffers > > from a rounding error which increases itself in every iteration. > > Increasing the precision doesn't solve your problem. It's only going to > > hide the fact that your algorithm doesn't do its job. > > > Please don't get me wrong. I don't want to imply that you are an idiot > > who doesn't know what he is doing. :] Most likely you weren't taught how > > to write numerical sound algorithms. Let's all blame your school or > > university. *g* > > > Numerics is a complex area and it took me more than a year to learn the > > basics. Don't be embarrassed! > > I'll try to read some. But I used mpmath to pump up the precision in > my code, and now the problem doesn't happen. So I think it's okay for > now. Thanks to all contributors for your advice. Ram Rachum. From giuott at gmail.com Mon Jun 2 10:05:01 2008 From: giuott at gmail.com (Giuseppe Ottaviano) Date: Mon, 2 Jun 2008 16:05:01 +0200 Subject: ANN: equivalence 0.1 In-Reply-To: <91ad5bf80806020630o783f0b11hbd0d33ceea008e39@mail.gmail.com> References: <8adaef43-dc92-49d8-858d-0d0247a7b485@m73g2000hsh.googlegroups.com> <28450AD1-E90C-44BE-B885-D74DD7A65618@gmail.com> <91ad5bf80806020630o783f0b11hbd0d33ceea008e39@mail.gmail.com> Message-ID: <9AA62D6E-99D5-4C80-8E7A-5872196E1AC4@gmail.com> > > Interesting.. it took me a while to figure out why the second case is > so much slower and you're right, it is indeed quadratic. I don't know > how likely would such pathological cases be in practice, given that > the preferred way to merge a batch of objects is > eq.merge(*xrange(10001)), which is more than 3 times faster than the > non-pathologic first case (and which I optimized even further to avoid > attribute lookups within the loop so it's more like 5 times faster > now). Also the batch version in this case remains linear even if you > merge backwards, eq.merge(*xrange(10000,-1,-1)), or in any order for > that matter. The example just showed what could happen if the merges are done in pathological order, it is not about batch merging. I think that pathological cases like this indeed show up in real cases: many algorithms of near duplicate elimination and clustering reduce to finding connected components of a graph whose edges are given as a stream, so you can't control their order. With this implementation, every time a component sized N is given a second (or following) argument to merge, you pay Omega(N). > I am familiar with it and I will certainly consider it for the next > version; for now I was primarily interested in functionality (API) and > correctness. Good :) From d3vvnull at gmail.com Fri Jun 13 17:46:26 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Fri, 13 Jun 2008 16:46:26 -0500 Subject: does paramiko support python2.5? In-Reply-To: References: <808793.504.qm@web44809.mail.sp1.yahoo.com> Message-ID: <170543c70806131446k1615fabci69c028324928483c@mail.gmail.com> paramiko is an ssh module On Fri, Jun 13, 2008 at 2:49 PM, Terry Reedy wrote: > > "Praveena B" wrote in message > news:808793.504.qm at web44809.mail.sp1.yahoo.com... > when i used paramiko in python2.5 i got the error below. > File "C:\praveena\python scripts\sshlib\ssh.py", line 5, in > import paramiko > File "C:\Python25\Lib\site-packages\paramiko\__init__.py", line 69, in > > from transport import randpool, SecurityOptions, Transport > File "C:\Python25\Lib\site-packages\paramiko\transport.py", line 32, in > > from paramiko import util > File "C:\Python25\lib\site-packages\paramiko\util.py", line 31, in > from paramiko.common import * > File "C:\Python25\lib\site-packages\paramiko\common.py", line 98, in > > from osrandom import OSRandomPool > File "C:\Python25\Lib\site-packages\paramiko\osrandom.py", line 129, in > > raise ImportError("Cannot find OS entropy source") > ImportError: Cannot find OS entropy source > > ==================== > I have no idea what paramiko is, but the error message suggests an OS > rather than Python problem. Can you run paramiko with an earlier version > of Python on the same machine as it is currently set up? > > If so, check (and possibly post) the OSRandomPool class/function in > osrandom.py for anything that might be sensitive to 2.5 changes (there were > not very many, and just about none should have broken code). > > tjr > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From hank.infotec at gmail.com Thu Jun 5 14:22:44 2008 From: hank.infotec at gmail.com (Hank @ITGroup) Date: Fri, 06 Jun 2008 04:22:44 +1000 Subject: Please unregister this mail-address out of mailing-list. Message-ID: <48482EF4.2060801@gmail.com> Dear Python Staff, I am writing this letter to unsubscribe this mail-address from python mail-list. One problem is that this python community is so active that I always lost myself to find my business emails. So, I want to quit this mail-address from you, and want to set up a specific mail-box to receive all python mails. Since could find a way to unsubscribe the mails, I need to write this letter to you. Please help. BTW, python is indeed great, thank you all for any supports. Hank. From tommy.nordgren at comhem.se Thu Jun 19 06:19:18 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Thu, 19 Jun 2008 12:19:18 +0200 Subject: =?ISO-8859-1?Q?Re:_[SPAM]_=A1=B6python_in_a_nutshell=A1=B7and=A1?= =?ISO-8859-1?Q?=B6programming_python=A1=B7?= In-Reply-To: References: Message-ID: <62DF2B9C-D8F7-4E2D-9480-BCCC4CA3CBF3@comhem.se> On 19 jun 2008, at 04.02, yps wrote: > as a new learner of python,which book in and > is more suitable? > and recommend several books? > thanks > best regards > > pase.Y > > > -- > http://mail.python.org/mailman/listinfo/python-list programming Python is quite good for experienced programmers who want to learn Python. It don't tutor on the Syntax, however, so it needs to be complemented with an introduction to the syntax. Guidos ebook Introduction to Python, (available with the Python dist) helps here. ----------------------------------- See the amazing new SF reel: Invasion of the man eating cucumbers from outer space. On congratulations for a fantastic parody, the producer replies : "What parody?" Tommy Nordgren tommy.nordgren at comhem.se From __peter__ at web.de Fri Jun 13 04:43:00 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Jun 2008 10:43:00 +0200 Subject: Plotting Graphs + Bestfit lines References: <1a919a2b-6430-4e2e-a190-2e00e43a6138@25g2000hsx.googlegroups.com> <022d382b-0b7b-4757-855a-f07019791fcc@d45g2000hsc.googlegroups.com> <05e67e40-db9c-4d85-94c1-f0e31dd5da38@27g2000hsf.googlegroups.com> Message-ID: arslanburney at gmail.com wrote: >> > Still confused though i get the instance part ur trying to tell me. > Tried that out too. No error however, best fit lines still not being > made on the graph. Only the 3 plot lines show up. Gave it another shot. You might want something like from __future__ import division import Gnuplot def bestfit(uinput, **kw): sigmax = sigmay = sigmaxy = sigmaxsq = 0 for x, y in uinput: sigmax += x sigmay += y sigmaxy += x * y sigmaxsq += x * x n = len(uinput) sigmaxwhl = sigmax * sigmax sigmaxsigmay = sigmax * sigmay num = sigmaxsigmay - n * sigmaxy den = sigmaxwhl - n * sigmaxsq num2 = sigmax * sigmaxy - sigmay * sigmaxsq gradient = num / den intercept = num2 / den return Gnuplot.Func('%f * x+%f' % (gradient, intercept), **kw) def plot(original, expected, actual): gp = Gnuplot.Gnuplot() gp('set data style lines') # Make the plot items plot1 = Gnuplot.PlotItems.Data(original, title="Original") plot2 = Gnuplot.PlotItems.Data(expected, title="Expected") plot3 = Gnuplot.PlotItems.Data(actual, title="Actual") bf2 = bestfit(expected, title="Best fit expected") bf3 = bestfit(actual, title="Best fit actual") gp.plot(plot1, plot2, plot3, bf2, bf3) return gp if __name__ == "__main__": gp = plot( [(2,3), (4,8), (5,9), (6,2)], [(1,7), (3,3), (4,5), (5,6)], [(1,3), (3,10), (4,8), (7,9) ] ) raw_input() It's all in one file for simplicity. Note that I did not check the best fit algorithm, just tried to simplify what you already had. Use at your own risk. Peter From miki.tebeka at gmail.com Mon Jun 9 15:54:59 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 9 Jun 2008 12:54:59 -0700 (PDT) Subject: Getting current screen resolution References: Message-ID: <06bd8fd0-ab4e-4101-ae84-c9773339622d@m36g2000hse.googlegroups.com> Hello, > This is a "thing" that has been annoying me all morning: and I can't > work out how to do it. > > I need a way to get the DPI or screen resolution of the monitor that a > script is currently runnign on. > > I have a way in Windows but it doesnt port to Unix (which is important). > > Any ideas? Maybe one of Tkinter.Tk winfo_* methods? HTH, -- Miki http://pythonwise.blogspot.com From ptmcg at austin.rr.com Tue Jun 24 05:34:34 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 24 Jun 2008 02:34:34 -0700 (PDT) Subject: String split with " and/or ' and/or \ References: Message-ID: <0f3ab0de-3990-43be-ad67-611c4e8be26d@j33g2000pri.googlegroups.com> On Jun 24, 3:56?am, Kurt Mueller wrote: > How to (super)split a string (literal) containing " and/or ' and/or \. > > example: > > ' a ?" ?b b ? " ?c\ c '.supersplit(' ') > -> > ['a', ' ?b b ? ', 'c c'] > > Thanks and Gr?essli > -- > Kurt M?ller: > kurt.muel... at aerodynamics.ch Or did you mean this? >>> re.split(r'''['"]|\\ ''',' a " b b " c\ c ') [' a ', ' b b ', ' c', 'c '] (In your example, you should prefix you quoted string literal with an r, as in: r' a " b b " c\ c '.supersplit(' ') That way, the '\' character will be treated as just any other character. -- Paul From eliben at gmail.com Sat Jun 21 02:14:06 2008 From: eliben at gmail.com (eliben) Date: Fri, 20 Jun 2008 23:14:06 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> Message-ID: <79a1c500-1844-4405-8f52-21e845a85f9b@z66g2000hsc.googlegroups.com> On Jun 20, 2:44 pm, Peter Otten <__pete... at web.de> wrote: > eliben wrote: > > Additionally, I've found indentation to be a problem in such > > constructs. Is there a workable way to indent the code at the level of > > build_func, and not on column 0 ? > > exec"if 1:" + code.rstrip() > > Peter Why is the 'if' needed here ? I had .strip work for me: def make_func(): code = """ def foo(packet): return ord(packet[3]) + 256 * ord(packet[4]) """ d = {} exec code.strip() in globals(), d return d['foo'] Without .strip this doesn't work: Traceback (most recent call last): File "exec_code_generation.py", line 25, in foo = make_func() File "exec_code_generation.py", line 20, in make_func exec code in globals(), d File "", line 2 def foo(packet): ^ IndentationError: unexpected indent From drobinow at gmail.com Sun Jun 22 21:57:26 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Sun, 22 Jun 2008 18:57:26 -0700 (PDT) Subject: -1/2 References: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> Message-ID: On Jun 22, 2:32?pm, "Serve Lau" wrote: > What is the expected result of -1/2 in python? I would say -1, but it depends on whether the "-" is a unary minus. >>> -1/2 -1 >>> 3 -1/2 3 From kyosohma at gmail.com Mon Jun 2 17:30:47 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 2 Jun 2008 14:30:47 -0700 (PDT) Subject: python blogs References: <19d5037f-837d-4f6b-9e56-d4e6d84b277d@y22g2000prd.googlegroups.com> Message-ID: <0f2beac5-ed73-47a2-95bd-8c6a563d4424@z72g2000hsb.googlegroups.com> On Jun 2, 4:14?pm, miller.pau... at gmail.com wrote: > On Jun 2, 2:49?pm, pythonbl... at gmail.com wrote: > > > It seems like Python blogs are gaining popularity. It seems to me that > > they play a crucial role in promoting Python as a language. > > Neat! ?Do blogs on your site have to be about Python programming, or > can people blog about anything? I personally like Doug Hellman's Python Module of the Week posts. The people over at Planet TurboGears are usually interesting too. http://blog.doughellmann.com/ http://planet.turbogears.org/ Other than those though, I haven't really seen much that's updated regularly. Mike From bruno.42.desthuilliers at websiteburo.invalid Tue Jun 3 11:16:44 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 03 Jun 2008 17:16:44 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> Message-ID: <48456031$0$4824$426a74cc@news.free.fr> Russ P. a ?crit : > On Jun 2, 6:41 am, Carl Banks wrote: > >> You are not realizing that only useful(**) thing about data hiding is >> that some code has access to the data, other code does not. If you >> "hide" data equally from everyone it's just a useless spelling change. > > I think you're missing the point. > > As I see it, the primary value of data hiding is that it provides > useful information on which data and methods are intended for the > client and which are intended for internal use. It's like putting a > front panel on a TV set with the main controls intended for the > viewer. > > People seem to be preoccupied with whether or not the back panel of > the TV is locked, but that is not the main issue. Sure, you probably > want to make the back panel removable, but you don't want the viewer > opening it up to change the channel, and you certainly don't want to > put all the internal adjustments for factory technicians together with > the controls for the end user. > > As far as I am concerned, the current Python method of using > underscores to distinguish between internal and external methods and > data is an ugly hack that goes completely against the elegance of the > language in other areas. As far as I'm concerned, it's JustFine(tm). I don't have to ask myself if an attribute is part of the API or not, I know it immediatly. > It is like a TV set with no back cover and > the volume and channel controls intermingled with the factory > controls. The underscores are just an afterthought like a red dot or > something used to tell the TV viewer what to fiddle with. Your opinion. But beware of leaky TV-Set-metaphor abstractions > Python is a very nice language overall, but as far as I am concerned > the underscore convention is a blemish. I just wish people wouldn't > get so infatuated with the language that they cannot see the obvious > staring them in the face. I definitively don't have problem with this naming convention, which I'd find useful ever with a language having enforced access restrictions. If that's the only - or worse - wart you find in Python, then it must surely be a pretty good language !-) From bronger at physik.rwth-aachen.de Sat Jun 14 17:14:10 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 14 Jun 2008 23:14:10 +0200 Subject: Making wxPython a standard module? References: <6bidd7F3bg8usU1@mid.uni-berlin.de> <87fxrfx0h0.fsf@physik.rwth-aachen.de> Message-ID: <87wskrvhwd.fsf@physik.rwth-aachen.de> Hall?chen! Grant Edwards writes: > [...] > > IMO, a few of the "un-Pythonic" things about wxPython are: > > 1) Window ID numbers. When I started to use wxPython, there was a newly-introduced wx.ID_ANY that you could give instead of -1. My eyes filtered it out after a couple of hours, just as they do with "self". > [...] > > 2) the "flags" parameter. Well, I like flags, and I don't see that they are unpythonic. I find the code they produce very legible. > [...] > > 3) the parent/child tree See wx.ID_ANY. > [...] > > 4) sizers Maybe because I come from TeX/LaTeX, i liked sizers immediately. They worked well for me. > [...] > > 5) binding > > "What? you wanted a button that _did_ something when you > clicked it?" You're right, this can be better. There's too much explicitness. However, if you really hate the construct, you can define a shortcut. > [...] > > 6) Thousands of wx.UPPER_CASE_INTEGER_HEX_CONSTANTS Thank you for the thorough explanations but in my opinion your points are minor. Additionally, most of them are a matter of taste. I don't think that because you didn't find sizers convenient, or some parts too explicit, you can say that wxWidgets is un-Pythonic. I rather have the impression that you like terseness, which is totally okay but a different thing. I agree that changing the naming conventions and making use of properties would increase pythonicness, but on an already high level. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From greg at cosc.canterbury.ac.nz Wed Jun 11 03:54:04 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 11 Jun 2008 19:54:04 +1200 Subject: ANN: Pyrex 0.9.8.4 Message-ID: Pyrex 0.9.8.4 is now available: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ This version fixes a bug introduced by the last change to unsigned integer indexing. What is Pyrex? -------------- Pyrex is a language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. From ivan.illarionov at gmail.com Thu Jun 5 11:48:11 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 5 Jun 2008 08:48:11 -0700 (PDT) Subject: Tuples part 2 References: <6d3e6d40-63a6-40d1-8ea4-5ddf40238d8d@m44g2000hsc.googlegroups.com> <99bc30fb-532a-4c4f-9f5e-e7a18c28d2a5@z72g2000hsb.googlegroups.com> <0ecaaa47-3ad4-4f67-9d48-94d5d1951bc6@y21g2000hsf.googlegroups.com> Message-ID: On 5 ???, 19:38, George Sakkis wrote: > On Jun 5, 11:21 am, Ivan Illarionov wrote: > > > > > On 5 ???, 18:56, Ivan Illarionov wrote: > > > > On 5 ???, 18:19, "victor.hera... at gmail.com" > > > wrote: > > > > > On Jun 5, 3:49 pm, Ivan Illarionov wrote: > > > > > > On 5 ???, 01:57, "victor.hera... at gmail.com" > > > > > wrote: > > > > > > > Hi Everyone, > > > > > > > i have another question. What if i wanted to make n tuples, each with > > > > > > a list of coordinates. For example : > > > > > > > coords = list() > > > > > > for h in xrange(1,11,1): > > > > > > for i in xrange(1, 5, 1) : > > > > > > for j in xrange(1, 5, 1) : > > > > > > for k in xrange(1,2,1) : > > > > > > coords.append((i,j,k)) > > > > > > lista+str(h)= tuple coords > > > > > > print tuple(coords) > > > > > > > so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do > > > > > > it the way i show you above but it is not working properly. I wish you > > > > > > could help me with that. Thanks again, > > > > > >>> from itertools import repeat, izip > > > > > >>> coords = tuple((i,j,k) for i in xrange(1,5) for j in xrange(1,5) for k in xrange(1,2)) > > > > > >>> locals().update(("tuple%s" % i, coord) for i, coord in izip(xrange(1,11), repeat(coords))) > > > > > >>> tuple1 > > > > > > ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (2, 1, 1), (2, 2, 1), (2, > > > > > 3, 1), (2 > > > > > , 4, 1), (3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1), (4, 1, 1), (4, 2, > > > > > 1), (4, 3 > > > > > , 1), (4, 4, 1)) > > > > > > Does this help? > > > > > > But I don't understand why you need this? > > > > > > Ivan > > > > > Hi, > > > > > What i need is, for example: > > > > > tuple 1=((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)) > > > > > tuple 2=((2, 1, 1), (2, 2, 1), (2, 3, 1), (2, 4, 1)) > > > > > tuple 3=((3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1)) > > > > > and so on. Please help me and sorry for not taking the time to post my > > > > questions properly. > > > > > Victor > > > > Or even so: > > > > locals().update(("tuple_%s" % i, tuple((i,j,k) for j in range(1,5) for > > > k in range(1,2))) for i in range(1,5)) > > > > Ivan > > > Tried to make it readable: > > > def iter_coords(i): > > for j in xrange(1,5): > > for k in xrange(1,2): > > yield i, j, k > > > def iter_vars(): > > for i in xrange(1, 5): > > yield "tuple_%s" % i, tuple(iter_coords(i)) > > > locals().update(dict(iter_vars())) > > locals().update() works by accident here because it's in global scope; > it doesn't work within a function. > > Use a proper data structure, like a dict or a list, and access each > tuple list as 'tuples[n]' instead of 'tuple_n'. > > George OP wanted variables and I showed him how to do this. I agree that a list or a dict would be better. Ivan From priyaavarmaa at gmail.com Fri Jun 27 04:30:42 2008 From: priyaavarmaa at gmail.com (lovely) Date: Fri, 27 Jun 2008 01:30:42 -0700 (PDT) Subject: Work 2 Hrs at Net EARN 10,000/- Rs Above Message-ID: HAI.......... Guys this web site s very useful to you........... How This site helps.......... how to earn money form online...... In this site, you wil earn more than 10000/- Rs per month.... its true ....... just login this site and << EARN MONEY >> www.freeonlinedollers.blogspot.com www.freedollers.blogspot.com From dullrich at sprynet.com Fri Jun 6 12:03:56 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 06 Jun 2008 11:03:56 -0500 Subject: ClassName.attribute vs self.__class__.attribute References: Message-ID: In article , Gabriel Rossetti wrote: > Larry Bates wrote: > > Gabriel Rossetti wrote: > >> Hello everyone, > >> > >> I had read somewhere that it is preferred to use > >> self.__class__.attribute over ClassName.attribute to access class > >> (aka static) attributes. I had done this and it seamed to work, until > >> I subclassed a class using this technique and from there on things > >> started screwing up. I finally tracked it down to > >> self.__class__.attribute! What was happening is that the child > >> classes each over-rode the class attribute at their level, and the > >> parent's was never set, so while I was thinking that I had indeed a > >> class attribute set in the parent, it was the child's that was set, > >> and every child had it's own instance! Since it was a locking > >> mechanism, lots of fun to debug... So, I suggest never using > >> self.__class__.attribute, unless you don't mind it's children > >> overriding it, but if you want a truly top-level class attribute, use > >> ClassName.attribute everywhere! I shouldn't butt in since everyone else knows more about this than I do, but it seems to me that saying you should do this is wrong and saying you should do that is wrong - which you should do depends on what you're trying to accomplish. There's something that comes up all the time in stuff I do, where implicitly accessing self.__class__.attribute is vital to make it work right. Say I have a Matrix class, with an __add__ method: class Matrix: def __init__(self, data): whatever def __add__(self, other): newdata = whatever return Matrix(newdata) The last line is almost surely not what I want (took me a while, long ago, to figure this out). Because someday when I have a subclass I want __add__ to return an instance of the subclass. At first I thought I needed to rewrite the last line to return SubClass(newdata). No, I simply return self.__class__(newdata) and it works exactly the way I want. > >> I wish books and tutorials mentioned this explicitly.... > >> > >> Gabriel > > > > If you define a class instance variable with the same name as the > > class attribute, how would Python be able to distinguish the two? > > That is a feature not a problem. Getter looks for instance attribute, > > if one is not found it looks for a class attribute, and upwards. This > > behavior is used by Zope to do all sorts of neat stuff. > > > > -Larry Bates > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > A class instance variable, you must mean an instance attribute no? If > that is so, then with just self.attribute? Maybe there is a concept that > I don't know about, I've studied class/static attributes and instance > attributes in my OOP classes. > > Gabriel -- David C. Ullrich From mario.ruggier at gmail.com Mon Jun 2 08:18:50 2008 From: mario.ruggier at gmail.com (mr) Date: Mon, 2 Jun 2008 05:18:50 -0700 (PDT) Subject: ValueError: unknown locale: UTF-8 References: <4842edea$0$25496$9b622d9e@news.freenet.de> Message-ID: <4cbfaa24-1bc6-47a7-9e59-d14788ea4c51@d77g2000hsb.googlegroups.com> On Jun 1, 8:43 pm, "Martin v. L?wis" wrote: > > ValueError: unknown locale: UTF-8 > > > This is on open bug or is there more to it? > > Do you have an environment variable set who is named > either LANG or starts with LC_? Actually, yes: LC_CTYPE=UTF-8 where is it coming from? This is basically on a clean new machine... who might be setting it? It is coming from a program elsewhere on the system? How should python code deal with this? Thanks! mario From deets at nospam.web.de Thu Jun 5 04:02:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 05 Jun 2008 10:02:23 +0200 Subject: Question regarding re module In-Reply-To: References: Message-ID: <48479D8F.6050304@nospam.web.de> Tomohiro Kusumi schrieb: > Hi, > > I have a question regarding re module. > # By the way I'm not in this list, so I'm sorry but please CC me. > > I tried following code in Python shell using a regular expression. > Why doesn't the result of dir(reg) have 'pattern', 'flags', and > 'groupindex' although they exist as members of _sre.SRE_Pattern > instance ? > > It sort of irritates me, because whenever I write Python code > using a module which I'm not used to using, I often try Python > shell with TAB complete to find out the member of module/instance. > It could be that the result overloads the __getattr__-method to delegate calls to some object. Thus it's not part of the outer instance. Diez From chrisspen at gmail.com Thu Jun 19 20:45:47 2008 From: chrisspen at gmail.com (Chris) Date: Thu, 19 Jun 2008 17:45:47 -0700 (PDT) Subject: Pattern Matching Over Python Lists References: <21a9c996-75ff-4f7c-b7e9-c94247f65674@c58g2000hsc.googlegroups.com> <87ej6w6ql6.fsf@internal.daycos.com> <61ea5c70-4352-4d2f-a0ef-62eb76ba933a@m36g2000hse.googlegroups.com> Message-ID: <6e31e7ef-3eea-4edc-88bc-471e78dbb46c@i76g2000hsf.googlegroups.com> On Jun 17, 1:09 pm, bearophileH... at lycos.com wrote: > Kirk Strauser: > > > Hint: recursion. Your general algorithm will be something like: > > Another solution is to use a better (different) language, that has > built-in pattern matching, or allows to create one. > > Bye, > bearophile Btw, Python's stdlib includes a regular expression library. I'm not sure if you're trolling or simply unaware of it, but I've found it quite adequate for most tasks. From bignose+hates-spam at benfinney.id.au Wed Jun 4 19:47:11 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 05 Jun 2008 09:47:11 +1000 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> <873antn9il.fsf@benfinney.id.au> <6ammujF38poe2U2@mid.uni-berlin.de> <87y75llp5x.fsf@benfinney.id.au> <87prqwltqi.fsf@benfinney.id.au> Message-ID: <87bq2glq4g.fsf@benfinney.id.au> Ethan Furman writes: > I must be missing something in this discussion. Perhaps it's the > appropriate point of view. At any rate, it seems to me that any and > every function should be tested to ensure proper results. I restrict that to "every proper behaviour the system is expected to provide should be tested". The corollary is that every behaviour is either: * part of an expected external behaviour, and thus unit tests need to assert that behaviour through the unit's public interface * not part of an expected external behaviour, and thus needs to be removed from the system This also forces a decision about "private" functionality: Either it's part of some public functionality, and thus needs to be tested via that public functionality; or it's not part of any public functionality, and needs to be removed. > It's my understanding that unit testing (a.k.a. PyUnit) is designed > for just such a purpose. Yes. -- \ "I was in the first submarine. Instead of a periscope, they had | `\ a kaleidoscope. 'We're surrounded.'" -- Steven Wright | _o__) | Ben Finney From pavlovevidence at gmail.com Thu Jun 26 17:19:46 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 26 Jun 2008 14:19:46 -0700 (PDT) Subject: Help me optimize my feed script. References: <184ee312-e54f-48bd-ac9f-1eb7e1737fc7@v26g2000prm.googlegroups.com> Message-ID: <97edcf08-b234-43dc-a91e-c3748f79d068@z72g2000hsb.googlegroups.com> On Jun 26, 3:30 pm, bsag... at gmail.com wrote: > I wrote my own feed reader using feedparser.py but it takes about 14 > seconds to process 7 feeds (on a windows box), which seems slow on my > DSL line. Does anyone see how I can optimize the script below? Thanks > in advance, Bill > > # UTF-8 > import feedparser > > rss = [ > 'http://feeds.feedburner.com/typepad/alleyinsider/ > silicon_alley_insider', > 'http://www.techmeme.com/index.xml', > 'http://feeds.feedburner.com/slate-97504', > 'http://rss.cnn.com/rss/money_mostpopular.rss', > 'http://rss.news.yahoo.com/rss/tech', > 'http://www.aldaily.com/rss/rss.xml', > 'http://ezralevant.com/atom.xml' > ] > s = '\n\nC:/x/test.htm\n' > > s += '\n' > > s += '\n\n
    \n' > > for url in rss: > d = feedparser.parse(url) > title = d.feed.title > link = d.feed.link > s += '\n

    '+ title +'

    \n' > # aldaily.com has weird feed > if link.find('aldaily.com') != -1: > description = d.entries[0].description > s += description + '\n' > for x in range(0,3): > if link.find('aldaily.com') != -1: > continue > title = d.entries[x].title > link = d.entries[x].link > s += ''+ title +'
    \n' > > s += '

    \n\n' > > f = open('c:/scripts/myFeeds.htm', 'w') > f.write(s) > f.close > > print > print 'myFeeds.htm written' Using the += operator on strings is a common bottleneck in programs. First thing you should try is to get rid of that. (Recent versions of Python have taken steps to optimize it, but still it sometimes doesn't work, such as if you have more than one reference to the string alive.) Instead, create a list like this: s = [] And append substrings to the list, like this: s.append('\n\n
    \n') Then, when writing the string out (or otherwise using it), join all the substrings with the str.join method: f.write(''.join(s)) Carl Banks From circularfunc at yahoo.se Tue Jun 24 14:32:23 2008 From: circularfunc at yahoo.se (cirfu) Date: Tue, 24 Jun 2008 11:32:23 -0700 (PDT) Subject: shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": Message-ID: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": cant i write something like: if char in "[A-Za-z]": ? From straton at lampsacos.demon.co.uk Sun Jun 8 09:50:22 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Sun, 08 Jun 2008 14:50:22 +0100 Subject: Most effective coding.. IDE question. In-Reply-To: References: Message-ID: dave wrote: > Hello everyone, > > I'm a beginning self-taught python student. Currently, I work out my > code within IDLE then when I have a version that I like, or that's > working, I move it over to a new window and save it. > > I've been playing w/ Komodo IDE lately, and while it's nice, what I > don't like is the "one line at a time" (produced by hitting up-arrow) in > the shell. In IDLE, ctrl-p can reproduce a whole function or class - > opposed to only the last line in Komodo. > > Is my IDLE method common? Or am I simply creating more of a headache > for myself? What do you recommend? I'm not that advanced and don't > need anything fancy. I'm on OS X. > > Thanks! > > Dave > For th simplest work, you could try skite as an editor; it takes you code in on window, and sends the output to another when you press F5. But--'not advanced' or not--I would suggest you look forward to the time when you will need version control, unit tests, and other utilities of a more comprehensive environment. Take a look at Eclipse, for example. For several sceencasts, python and eclipse included: http://showmedo.com/videos/programming_tools From ivan.illarionov at gmail.com Thu Jun 5 09:49:45 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 5 Jun 2008 06:49:45 -0700 (PDT) Subject: Tuples part 2 References: Message-ID: <6d3e6d40-63a6-40d1-8ea4-5ddf40238d8d@m44g2000hsc.googlegroups.com> On 5 ???, 01:57, "victor.hera... at gmail.com" wrote: > Hi Everyone, > > i have another question. What if i wanted to make n tuples, each with > a list of coordinates. For example : > > coords = list() > for h in xrange(1,11,1): > for i in xrange(1, 5, 1) : > for j in xrange(1, 5, 1) : > for k in xrange(1,2,1) : > coords.append((i,j,k)) > lista+str(h)= tuple coords > print tuple(coords) > > so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do > it the way i show you above but it is not working properly. I wish you > could help me with that. Thanks again, >>> from itertools import repeat, izip >>> coords = tuple((i,j,k) for i in xrange(1,5) for j in xrange(1,5) for k in xrange(1,2)) >>> locals().update(("tuple%s" % i, coord) for i, coord in izip(xrange(1,11), repeat(coords))) >>> tuple1 ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (2 , 4, 1), (3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1), (4, 1, 1), (4, 2, 1), (4, 3 , 1), (4, 4, 1)) Does this help? But I don't understand why you need this? Ivan From sri_annauni at yahoo.co.in Fri Jun 20 08:05:12 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Fri, 20 Jun 2008 17:35:12 +0530 (IST) Subject: Execute a script on a remote machine Message-ID: <406350.34562.qm@web7908.mail.in.yahoo.com> Hi, My requirement is i have to?execute a python script on a remote machine as a subprocess from a python script and to get the subprocess pid of the process running the script. Is there anyway to do that?? I have used subprocess.popen() method to do that. I have done as following: executable = '/usr/bin/rsh' args = [executable, hostname, scriptname] pid = subprocess.popen(args) It returned the pid of rsh. But i am interested in the pid of the process running the script. Can anyone help me out here? Thanks, Srini Unlimited freedom, unlimited storage. Get it now, on http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/ From markscottwright at gmail.com Tue Jun 17 16:55:35 2008 From: markscottwright at gmail.com (markscottwright) Date: Tue, 17 Jun 2008 13:55:35 -0700 (PDT) Subject: Is there a standard binary search with overridable comparisons? Message-ID: <09baffe9-691a-47b0-9ba5-1de3231d6cba@8g2000hse.googlegroups.com> I've got an ordered list of MyClasses that I want to be able to do binary searches on, but against a tuple. MyClass has valid __lt__(self, rhs) and __eq__(self, rhs) member functions that work when rhs is a tuple. This works: l = [MyClass(..), MyClass(..), ...] l.find((a,b)) But this doesn't: bisect.bisect(l, (a,b)) I'm assuming this is because inside bisect, it does 'key < list[x]' rather than 'list[x] < key', so it's the tuple's __lt__ that is called, rather than MyClass's tuple. Is there a way around this? Can I monkeypatch a new __lt__ into the tuple class? Here's some sample code that demonstrates the problem (it uses ints rather than tuples, but the import bisect class MyC: def __init__(self, v): self.v = v def __lt__(self, rhs): return self.v < rhs # cant search for int in a list of MyC's l = sorted([MyC(x) for x in range(1000)]) bisect.bisect(l, 40) 1001 # AKA not found # but, I can search for MyC in a list of ints l = sorted(range(1000)) bisect.bisect(l, MyC(40)) 41 From shubalubdub at gmail.com Sun Jun 8 15:56:45 2008 From: shubalubdub at gmail.com (shubalubdub at gmail.com) Date: Sun, 8 Jun 2008 12:56:45 -0700 (PDT) Subject: Newbie help (TypeError: int argument required) References: Message-ID: On Jun 8, 1:43?pm, Iain Adams wrote: > Hi, > > I am new to python. I have been having trouble using the MysqlDB. I > get an error pointing from the line > > cursor.execute("UPDATE article SET title = %s, text = %s WHERE id = > %u", (self.title, self.text, self.id)) > > Here is the error: > > ?line 56, in save > ? ? cursor.execute("UPDATE article SET title = %s, text = %s WHERE id > = %u", (self.title, self.text, self.id)) > ? File "/var/lib/python-support/python2.5/MySQLdb/cursors.py", line > 151, in execute > ? ? query = query % db.literal(args) > TypeError: int argument required > > However when I print out type(self.id) I get . > > So surely I have provided an int argument. > > Any ideas anyone?? From MySQLdb User's Guide (http://mysql-python.sourceforge.net/ MySQLdb.html): To perform a query, you first need a cursor, and then you can execute queries on it: c=db.cursor() max_price=5 c.execute("""SELECT spam, eggs, sausage FROM breakfast WHERE price < %s""", (max_price,)) In this example, max_price=5 Why, then, use %s in the string? Because MySQLdb will convert it to a SQL literal value, which is the string '5'. When it's finished, the query will actually say, "...WHERE price < 5". From larry.bates at websafe.com` Mon Jun 16 12:35:52 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 16 Jun 2008 11:35:52 -0500 Subject: 'string'.strip(chars)-like function that removes from the middle? In-Reply-To: References: Message-ID: Ethan Furman wrote: > Greetings. > > The strip() method of strings works from both ends towards the middle. > Is there a simple, built-in way to remove several characters from a > string no matter their location? (besides .replace() ;) > > For example: > .strip --> 'www.example.com'.strip('cmowz.') > 'example' > .??? --> --- 'www.example.com'.strip('cmowz.') > 'exaple' > -- > Ethan > filter() >>> removeChars = ';j' >>> filter(lambda c: c not in removeChars, x) 'asdfklasdfkl' >>> or a list comprehension x="asdfjkl;asdfjkl;" >>> ''.join([c for c in x if c not in ';']) 'asdfjklasdfjkl' -Larry From rasky at develer.com Tue Jun 3 05:59:19 2008 From: rasky at develer.com (Giovanni Bajo) Date: Tue, 03 Jun 2008 09:59:19 GMT Subject: PyInstaller: problem to build exe with PyQt4 References: Message-ID: On Tue, 03 Jun 2008 08:35:37 +0200, Mark Delon wrote: > Hi, > > I need to generate single EXEcutable via PyInstaller. It will be > genereated -> i get one single executable. > > AFTER CALL (exe) I get an error: "no module named _gt" > > Build command: > 1. Configure.py > 2. Makespec.py -F
    """ return HttpResponse(output) def ajax(request): output = """

    Hello World from Django and AJAX

    Current time is: %s

    """ % str(datetime.now())[11:19] return HttpResponse(output, mimetype="text/plain") Note, that refresh time is in 'setTimeout('ajaxFunction();', 1000);' in this example it is 1 second. 3. edit urls.py inside YOURPROJECTNAME directory to something like this: from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^myscript/$', 'YOURPROJECTNAME.views.myscript'), (r'^ajax/$', 'YOURPROJECTNAME.views.ajax'), ) 4. run 'python manage.py runserver' inside YOURPROJECTNAME directory 5. point your browser to 'http://127.0.0.1:8000/myscript/' and you'll see the result. 6. Deploy your app to Apache web server http://www.djangoproject.com/documentation/modpython/ http://www.djangoproject.com/documentation/fastcgi/ Hope this Django/AJAX introduction is helpfull Please note that this code is extremely simplified you probably need to learn more about Django and AJAX/Javascript by yourself Ivan From torppa at staff.megabaud.fi Tue Jun 10 01:53:08 2008 From: torppa at staff.megabaud.fi (Jarkko Torppa) Date: Tue, 10 Jun 2008 05:53:08 GMT Subject: 65K length limitation in MySQLdb? References: <4e79050f-ee50-42f0-9b84-4571faa30ee5@a32g2000prf.googlegroups.com> Message-ID: On 2008-06-10, TT wrote: > I'm trying to using the following code insert a long string into a > MySQL table, the data type is of that column is TEXT. When the length > of the content is longer than 65K, it get truncated in the database. > Any idea about this? Thanks It's limitation on your sql engine, use longtext. http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html -- Jarkko Torppa From kyrie at uh.cu Fri Jun 27 20:15:51 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Fri, 27 Jun 2008 20:15:51 -0400 Subject: Do I need "self" and "other"? In-Reply-To: <04e2afb7-b96c-446a-816a-ffac0ea81d5b@p25g2000hsf.googlegroups.com> References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> <04e2afb7-b96c-446a-816a-ffac0ea81d5b@p25g2000hsf.googlegroups.com> Message-ID: <200806272015.53248.kyrie@uh.cu> On Friday 27 June 2008 06:41:22 pm Kurda Yon wrote: > OK, I see. In the given example "self" is just a name which can be > replace by whichever (valid) name. Is that always like that? I mean, > does "slef" have a special meaning in some cases or it is always "just > a name like any other"? I am asking that because "self" is highlighted > in my text editor, so I assume that it can have a special meaning. I > also heard that "self" refers to a object and I am not sure what that > "refers" means. It's a name, like any other. It only has special meaning on the minds of most python programmers. That name is used, by convention (and only because of convention) to refer the the ... erm... 'self' object. That said, of all python conventions, it is perhaps the one most zealously followed. That's why your editor highlights it. So, code will not break if you use any other valid name instead of self. But you shouldn't. Everything will work perfectly - except the readability. Cheers, -- Luis Zarrabeitia (aka Kyrie) Fac. de Matem?tica y Computaci?n, UH. http://profesores.matcom.uh.cu/~kyrie From ptmcg at austin.rr.com Thu Jun 19 06:40:11 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 19 Jun 2008 03:40:11 -0700 (PDT) Subject: Pyparsing performance boost using Python 2.6b1 Message-ID: I just ran my pyparsing unit tests with the latest Python 2.6b1 (labeled internally as Python 2.6a3 - ???), and the current 1.5.0 version of pyparsing runs with no warnings or regressions. I was pleasantly surprised by the improved performance. The most complex parser I have is the Verilog parser, and I have just under 300 sample input files, so the test gets a chance to run over a range of code and source inputs. Here are the lines/second parsing for the Verilog data (higher numbers are better): Python V2.5.1 Python V2.6b1 base 209.2 307.0 with packrat optimization enabled 349.8 408.0 This is a huge percentage improvement, anywhere from 15-50%! I do not know what it is about 2.6 that runs so much faster, but given that packratting achieves somewhat less improvement, I would guess that the 2.6 performance comes from some optimization in making function calls, or in GC of local variables when functions are completed (since packratting is a form of internal memoization of parse expressions, which thereby avoids duplicate calls to parsing functions). Using psyco typically gives another 30-50% performance improvement, but there is no psyco available for 2.6 yet, so I skipped those tests for now. -- Paul From remy.blank at pobox.com Tue Jun 3 17:49:01 2008 From: remy.blank at pobox.com (Remy Blank) Date: Tue, 03 Jun 2008 23:49:01 +0200 Subject: ANN: Sydebar 1.0 - A browser sidebar generator for Python documentation Message-ID: Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: quoted-printable I am pleased to announce the first release of Sydebar, a browser sidebar = generator for Python documentation. For the impatient, sample outputs=20 for all Python versions ever released can be found here: http://c-space.org/download/Sydebar/samples/ The program generates a single, self-contained XHTML file for a specific = Python documentation URL, which can be local or remote. The generated=20 file is loaded into the sidebar of some popular browsers (tested on=20 Firefox and Opera, Mozilla should work as well), and presents a tabbed=20 interface with one page for each of the following documentation sections:= * Tutorial * Language reference * Library reference * Python/C API * Extending and embedding * Global module index Each page shows a collapsible tree of chapters, with links opening the=20 corresponding section in the main browser pane. The global module index=20 features an incremental search functionality with fast keyboard navigatio= n. Moreover, a search page allows performing searches on various subsets of = python.org (specific parts of the website, PEPs, newsgroups, PyPI and=20 the issue tracker). The documentation and PyPI entry can be found here: http://c-space.org/software/Sydebar.html http://pypi.python.org/pypi/Sydebar I would like to mention that Sydebar was inspired by python-sidebar from = Daniel Lundin at Edgewall Software, and even though I didn't borrow any=20 code from there, the layout does bear quite some resemblance. Feedback is very welcome. Thanks for reading! -- Remy -------------- next part -------------- Content-Type: application/pgp-signature; name="signature.asc" Content-Description: OpenPGP digital signature Content-Disposition: attachment; filename="signature.asc" -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.9 (GNU/Linux) iEYEARECAAYFAkhFvFEACgkQCeNfIyhvXjISEACgmUXSorHaZ7JjNC2AqTuJtWod BAgAn3g/97+9cI9m5n2QBpvcmtxQnGB0 =IQ6Q -----END PGP SIGNATURE----- From evidentemente.yo at gmail.com Wed Jun 25 03:15:14 2008 From: evidentemente.yo at gmail.com (evidentemente.yo) Date: Wed, 25 Jun 2008 00:15:14 -0700 (PDT) Subject: calling a .exe from Python References: Message-ID: Hey, thank you very much!!!:D Would it matter if my .exe doesn't return any value? would it return like an "ok" or something??? On 24 jun, 14:32, Nick Craig-Wood wrote: > evidentemente.yo wrote: > > ?Hi, i am trying to call a .exe from my .py file, i have found the exec > > ?function, but i'm not sure of how to use it:S > > > ?would it be f.e.: > > > ?execl (mypath/myfile.exe,myfile,arg1,arg2,...) > > > ????? > > > ?Another question is, when i call my .exe with exec, i understand that > > ?my .py file will stop running, and instead the new process will be > > ?launched instead of it. Is it true? > > ?Is there a way to launch my .exe without finishing my .py file?? > > > ?thank you very much:) > > Probably what you want is this... > > from subprocess import call > > rc = call(["mypath/myfile.exe",arg1,arg2]) > > rc will contain the exit status > > See the subprocess module for more things you can do > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick From jon at ffconsultancy.com Thu Jun 5 06:37:48 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Thu, 05 Jun 2008 11:37:48 +0100 Subject: The Importance of Terminology's Quality References: Message-ID: Robert Maas, http://tinyurl.com/uh3t wrote: >> From: dkco... at panix.com (David Combs) >> Lisp is *so* early a language (1960?), preceeded mainly only by >> Fortran (1957?)?, and for sure the far-and-away the first as a >> platform for *so many* concepts of computer-science, eg lexical vs >> dynamic ("special") variables, passing *unnamed* functions as >> args ... maybe is still the only one in which program and data >> have the same representation -- that it'd seem logical to use it's >> terminology in all languages. > > Yeah, but why did you cross-post to so many newsgroups? Are you > trying to run a flame war between advocates of the various > languages? What would be the point? We all know that Java, Perl, Python and Lisp suck. They don't even have pattern matching over algebraic sum types if you can imagine that. How rudimentary... -- Dr Jon D Harrop, Flying Frog Consultancy http://www.ffconsultancy.com/products/?u From xdicry at gmail.com Thu Jun 19 03:57:18 2008 From: xdicry at gmail.com (Evan) Date: Thu, 19 Jun 2008 00:57:18 -0700 (PDT) Subject: [SMTPLIB] how to send a "Multiline" mail with smtplib? Message-ID: Hello - I'm new with Python, I try to do a mail problem, the code likes below: +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ import smtplib import mimetypes from email.Encoders import encode_base64 from email.MIMEAudio import MIMEAudio from email.MIMEBase import MIMEBase from email.MIMEImage import MIMEImage from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText msg = MIMEMultipart() msg['From'] = 'ab at xx.net' msg['To'] = 'ab at xx.net' msg['Subject'] = 'test subject' body=MIMEText('hello,\r\n ok',_subtype='html',_charset='windows-1255') msg.attach(body) server = smtplib.SMTP('mail.xx.net') server.sendmail('ab at xx.net', 'ab at xx.net', msg.as_string()) server.quit() +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ I try to use "\r\n" or "\n", but no luck, nothing with them, I still get a Single-line text in the mail. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ hello, ok ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ So how do I send a multiline mail? such as : +++++++++++++++++++++++++++++++++++++++++++ Hello, 1, 2, ok +++++++++++++++++++++++++++++++++++++++++++ I would like to get help from you, thanks so much. From bruno.desthuilliers at gmail.com Fri Jun 20 16:47:44 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 20 Jun 2008 13:47:44 -0700 (PDT) Subject: sublassing as a verb References: Message-ID: On 20 juin, 22:34, davidj411 wrote: > docs on urllib module say this about the FancyUrlOpener: > "class FancyURLopener( ...) > > FancyURLopener subclasses URLopener providing default handling > for ..." > > does that mean the FancyURLopener is a subclass of URLopener? You could easily find out by yourself, you know ?-) Python 2.5.1 (r251:54863, Apr 6 2008, 17:20:35) [GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from urllib import URLopener, FancyURLopener >>> issubclass(FancyURLopener, URLopener) True From henryar2 at gmail.com Sun Jun 22 06:56:22 2008 From: henryar2 at gmail.com (Henry Read) Date: Sun, 22 Jun 2008 18:56:22 +0800 Subject: Learning Python in a group In-Reply-To: <507738ef0806220343r3e9ea053neeec0baf0ccfdbe6@mail.gmail.com> References: <507738ef0806220343r3e9ea053neeec0baf0ccfdbe6@mail.gmail.com> Message-ID: I'm a beginner, too.But python wasn't my first programming language. On Sun, Jun 22, 2008 at 6:43 PM, Jonathan Roberts wrote: > Hi all, > > I'm looking to learn Python (as my first programming language) and I'm > pretty sure I'd be more successful doing this with a group of other > people. > > I've currently got one other person to learn with me, and we plan to > work remotely over the net using tools such as IM/VoiP/Gobby/WIkis > etc. We'd still like a few others to work with us, with a group of > about 5 or 6 being seen as ideal. We'd also like to find somebody to > act as a mentor/guide who might be happy to meet with us once every > couple of weeks to help keep us moving in the right direction and find > solutions to problems when we get really stuck! > > Wondered if there was anybody here who might be interested in working > with us in either of these roles? We both have differing goals, but > ultimately we'd just like to get more familiar so that we can provide > some simple fixes to packages we maintain/scratch a few itches of our > own. Any one is welcome, no matter what your own aim :) > > Would love to hear feedback, especially from anyone who's interested > in working with us... > > Best, > > Jon > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 16 05:06:58 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 16 Jun 2008 11:06:58 +0200 Subject: Best way to make a number of tests against an object('s attributes) with absence of switch statement? In-Reply-To: <15aaceb5-2f9c-4891-98c2-fe7ac3e19f1c@k37g2000hsf.googlegroups.com> References: <15aaceb5-2f9c-4891-98c2-fe7ac3e19f1c@k37g2000hsf.googlegroups.com> Message-ID: <48562d32$0$1281$426a34cc@news.free.fr> Phillip B Oldham a ?crit : > What would be the optimal/pythonic way to subject an object to a > number of tests (based on the object's attributes) and redirect > program flow? > > Say I had the following: > > pets[0] = {'name': 'fluffy', 'species': 'cat', 'size': 'small'} > pets[1] = {'name': 'bruno', 'species': 'snake', 'size': 'small'} > pets[2] = {'name': 'rex', 'species': 'dog', 'size': 'large'} > > What I'd like to do is loop through 'pets', and test each object. Some > of the tests I'd like to perform are: > > Is the size 'small' and species not 'dog'? > Is the species 'cat' and name 'fluffy'? > Is the species not 'dog' or 'cat'? > > In PHP I'd use a switch statement similar to the following: > > foreach( $pets as $pet) { > switch(true) { > case ( $pet['size'] === 'small' && $pet['species'] !== 'dog' ): > // do something > break; > // etc... > } > } > > Now, I understand from a bit of googling that python doesn't have a > switch statement, and because of this people rely on python's > polymorphism. You could also put it the other way round : Python doesn't have a switch statement because peoples use polymorphism !-) (nb : not that my "reversed" statement is in any way more true than yours - but the fact is that procedural switch statement vs OO polymorphic dispatch is not such a new topic...) > Thats great, but I've yet to come across a decent > example which make a "click". > > Any thoughts on how to proceed? The braindead canonical OO solution would be to make a specific class for each species each implementing it's own version of do_something(). The problem is that it would only dispatch on species, not other attributes (size etc). Which is a inherent limitation of the canonical OO type-based single dispatch mechanism. A more elaborate canonical OO solution would be to use the visitor pattern to overcome the single dispatch limitation. A yet more elaborate (but way less canonical) solution is to use predicate-based dispatch (cf Philip Eby's work). Anyway, and while each dispatch mechanism (from basic branching to complex predicate-based systems) has it's pros and cons, I'd first think twice (or more) about whether my current dispatch problem has some relative stability wrt/ the domain - IOW, it's structurally part of the domain and won't change anytime soon - or if it's one of those ad-hoc short-lived illogical "business rule" that is potentially subject to unpredictable change any other day. Because the appropriate solution really depends on this kind of considerations. Now wrt/ your concrete example: truth is that, while expressed as a switch statement, it's in fact really a if/elif/.../, since the condition is not a constant (so you don't gain any performance gain from using a switch). So the simplest translation in Python is to use an if/elif/... for pet in pets: if pet['size'] == 'small' and pet['species'] !== 'dog': // do something elif (other complex condition): // etc From nick at craig-wood.com Wed Jun 4 10:30:21 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 04 Jun 2008 09:30:21 -0500 Subject: ctypes, function pointers and a lot of trouble References: <832f57f4-7d26-44a5-8abe-567165cc532f@f36g2000hsa.googlegroups.com> Message-ID: Matt wrote: > Hm, thanks, now I can access my data in the functions and also write > them but the program keeps terminating right at the point when the > "open" function finishes. Unfortunately everything closes and I get no > error messages. > > I did some additional work in the meantime and changed my code so it has > the correct datatypes now: > > > def pystreamopen (contextH, mode, pErr): > print "opening..." > print contextH.contents.dwBufferSize #just to check the structure > print mode #tells about what the DLL wants to do with this stream You program is crashing somewhere after here since mode is printed but nothing else is > contextH.contents.mode = c_byte(5) #5=Permission to read and write > contextH.contents.lPos = c_uint(0) #start position > > print pErr.contents > pErr.contents = c_uint(0) Try commenting out these lines and see if it works, then uncomment one at a time. Also is that supposed to be returning something? > Anyway, meanwhile decided to try a different approach. Maybe I have > more luck by having the function write the data directly into a file on > the HDD. > Doe anyone know how to translate the following into Python/ctypes? > > I googled quite a lot before but all topic-related I found was my own > posting here in this NG :S > > pFilStrm->hFile = CreateFile( pFilStrm->szFileName, > dwDesiredAccess, dwShareMode, NULL, > dwCreationDisposition, > FILE_ATTRIBUTE_NORMAL, > NULL ); use os.read os.write and os.open which will give you OS handles rather than python file objects, ie I think these are a fairly direct interface to CreatFile etc (but I could be wrong - I'm not a windows expert!) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From Russ.Paielli at gmail.com Fri Jun 6 14:56:26 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Fri, 6 Jun 2008 11:56:26 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <4847d39d$0$7614$426a74cc@news.free.fr> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <8f68b4a0-8f0f-42d6-8e96-53a97433f708@v26g2000prm.googlegroups.com> <48495745$0$26543$426a74cc@news.free.fr> Message-ID: <819c8708-95ca-4640-b305-39826c09c06a@t12g2000prg.googlegroups.com> On Jun 6, 8:28 am, Bruno Desthuilliers wrote: > Russ P. a ?crit : > > > > > On Jun 5, 2:27 pm, Dennis Lee Bieber wrote: > >> On Thu, 5 Jun 2008 11:36:28 -0700 (PDT), "Russ P." > >> declaimed the following in comp.lang.python: > > >>> would need to use a "mangled" name to access private data or methods. > >>> But you will be using the name many times, you can reassign your own > >>> name, of course, so the mangled name need not appear more than once > >>> where it is needed. > >> Which will break the first time the "innards" rebind a value to the > >> mangled name, as the "simplified" external name will still be bound to > >> the previous value. > > > I'm not sure you understood what I meant. In current Python, if I need > > access to data element __XX in class YourClass, I can use > > ZZ._YourClass__XX, but if I don't want to clutter my code with that > > mangled name, I can just write > > > XX = ZZ._YourClass__XX > > > and refer to it from that point on as XX. > > > Obviously if the meaning of > > __XX changes within class ZZ, this will break, but that's why you are > > supposed to avoid using private data in the first place. > > AFAICT, What Dennis meant is that the binding of ZZ._YourClass__XX > changes between the moment you bind it to local XX and the moment you > use it, then you're out. Perhaps I should have stipulated that this should be done only in a local scope and in an application that is not multi-threaded. Then I don't see how you can have a problem. From xucs007 at gmail.com Sat Jun 21 19:54:03 2008 From: xucs007 at gmail.com (xucs007 at gmail.com) Date: Sat, 21 Jun 2008 16:54:03 -0700 (PDT) Subject: flock seems very unsafe, python fcntl bug? Message-ID: <9abe51c3-c022-42e9-9d7d-acba7391d007@79g2000hsk.googlegroups.com> I ran following 2 programs (lock1, lock2) at almost same time, to write either "123456", or "222" to file "aaa" at the same time. But I often just got "222456" in "aaa" . Is this a bug of python fcntl module ? See 2 programs I ran: #!/usr/bin/env python import fcntl, time file = open('aaa', "w") fcntl.flock(file, fcntl.LOCK_EX) file.write('123456') time.sleep(10) file.close() #!/usr/bin/env python import fcntl, time file = open('aaa', "w") fcntl.flock(file, fcntl.LOCK_EX) file.write('222') time.sleep(10) file.close() From benjamin.kaplan at case.edu Thu Jun 19 17:15:59 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 19 Jun 2008 17:15:59 -0400 Subject: Noob: finding my way around the docs... In-Reply-To: References: Message-ID: On Thu, Jun 19, 2008 at 5:06 PM, kj wrote: > > > > I'm a Python noob, and haven't yet figured out my way around the > Python documentation. > > For example, suppose I learn about some great module foo.bar.baz, > and when I run the python interpreter and type "import foo.bar.baz", > lo and behold, it is already installed on our system, which means > that (knowing that our system is pretty bare-bones as far as python > goes) most likely foo.bar.baz is part of the standard python > installation. > > So, if I were an experienced Pythonista, how would I go about > finding the documentation for foo.bar.baz? > > This situation happened most recently to me, if we replace foo.bar.baz > with xml.dom.ext. It was indeed installed on our system, but I > could find no mention of it in docs.python.org. > > Somehow I have the feeling that there's some major stash of > documentation that I haven't learned about yet... > > FWIW, I'm a Perlhead, and I'm very used (maybe too used) to the > fact that if the Perl module Foo::Bar::Baz is installed on our > system, all I need to do to read its full-blown documentation in > all its glory is to type "perldoc Foo::Bar::Baz" at the command > line. Is there anything like this in Python? > > TIA! > > kj > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. > -- > http://mail.python.org/mailman/listinfo/python-list > To get the docs, just open up the shell and type: >>> import module >>> help(module) -------------- next part -------------- An HTML attachment was scrubbed... URL: From boris.smirnov at gmail.com Thu Jun 12 06:08:00 2008 From: boris.smirnov at gmail.com (boriq) Date: Thu, 12 Jun 2008 03:08:00 -0700 (PDT) Subject: suppress opening command window after using os.system command References: Message-ID: <8ad19472-bbb4-4283-88bf-2bcf6b91790c@26g2000hsk.googlegroups.com> On 12 Jun., 11:51, "Gabriel Genellina" wrote: > En Thu, 12 Jun 2008 05:28:13 -0300, boriq ? > escribi?: > > > I'm using in my script command os.system('command') on Windows XP. > > Each time the os.system command is used, python opens an empty ms-dos > > command window (the black one) and then closes it. So when in one > > script the os.system command 50 times is used, I see 50 black windows. > > > Is there a way of how to suppress this unnecessary command windows to > > be opened? > > Use the subprocess module instead of os.system > > -- > Gabriel Genellina I'm on version 2.2.1 because of a program we use and it uses this version. and the subprocess module was implemented in version 2.4 Any possibility to do it with the old stuff in ver 2.2.1? Thx From apardon at forel.vub.ac.be Wed Jun 4 08:02:01 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Jun 2008 12:02:01 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> Message-ID: On 2008-06-04, NickC wrote: > On May 26, 7:32 am, "Joe P. Cool" wrote: >> I saw this "don't need it" pattern in discussions about the ternary >> "if..else" expression and about "except/finally on the same block >> level". >> Now Python has both. > > if/else was added solely because people kept coming up with ways of > embedding a pseudo conditional inside expressions and writing buggy > code in the process. All it really saves you in practice is a bit of > vertical whitespace, so, no, you still don't need it - but if you > insist on doing it, at least there's now an easy way to do it > correctly. If I remember correctly it was added because one of the python developers was bitten by a bug in the standard library code that was caused by the use of the and-or emulation, mentioned in the FAQ. And although one indeed doesn't need this. There are a lot of things in Python one doesn't need. Python could be limited to single operator expressions. You don't need: x = a * b + c You can write it just like this: x = a * b x = x + c And if you want a list comprehension like the following: ls = [ x * x + 4 for x in xrange(10)] You can of course write it as follows: def sqrplus4(a): rs = a * a return rs + 4 ls = [sqrplus4(x) for x in xrange(10)] Now of course noone would defend such a limitation on the grounds that one doesn't need the general case and that the general case will only save you some vertical space. But when it came to the ternary operator that was exactly the argument used, to defend the lack of it. >> > In Python, the philosophy "we're all consenting adults here" applies. >> >> Please don't sell a missing feature as a philosophy. Say you don't >> need/want >> it. But don't call it philosophy. > > Gosh, and here I thought treating programmers as non-idiots was > actually one of the guiding philosophies in the discussion on python- > dev. I have heard the argument: "Such a feature will be abused too easily" and similar too many times to find this credible. -- Antoon Pardon From rhamph at gmail.com Sat Jun 14 13:10:10 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Sat, 14 Jun 2008 10:10:10 -0700 (PDT) Subject: best way to create a timer References: Message-ID: On Jun 12, 11:42 pm, Alexnb wrote: > I am wondering what is the best way to create a timer, like an alarm, once it > reaches a time, it triggers an event. I have a way of doing this but it > seems like it isn't good at all. If it helps at all I am using a Tkinter, > but that probably doesn't mean much. The way I was doing it was using a > while loop, and just saying while current time is not = to trigger time, do > nothing, and when it is, do event. Tkinter makes a big difference here. Like most (all?) event loops, it provides a way to call a function after a specified amount of time. Here's two pages I found: http://mail.python.org/pipermail/python-list/2001-August/101233.html http://www.astro.washington.edu/owen/TkinterSummary.html#After Note that it only fires once. If you want it to fire again you're callback will have to setup another timer. From bj_666 at gmx.net Fri Jun 6 05:34:56 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Jun 2008 09:34:56 GMT Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> <769c54bf-8664-4179-bd17-c18705320606@27g2000hsf.googlegroups.com> Message-ID: <6aselvF38p22kU1@mid.uni-berlin.de> On Thu, 05 Jun 2008 23:56:40 -0700, dwahli wrote: > On Jun 6, 8:44?am, "Terry Reedy" wrote: >> >> Of course, enumerate(iterable) is just a facade over zip(itertools.count(), >> iterable) > > So you could write: > gen = (x for x in itertools.izip(itertools.count(8), [0, 1, 1, 1, 1, > 1, 1, 2, 2, 3, 3])) > print list(gen) Useless use of a generator expression. This: gen = itertools.izip(itertools.count(8), [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3]) print list(gen) has the same effect without the intermediate generator that does nothing but passing the items. Ciao, Marc 'BlackJack' Rintsch From lucaberto at libero.it Fri Jun 6 04:59:28 2008 From: lucaberto at libero.it (luca72) Date: Fri, 6 Jun 2008 01:59:28 -0700 (PDT) Subject: import cherrypy2 References: Message-ID: <0853b1cc-33bb-416e-9b2e-0fa146ede1c1@79g2000hsk.googlegroups.com> On 6 Giu, 10:31, Chris wrote: > On Jun 6, 10:22 am, luca72 wrote: > > > > > Hello i can't import cherrypy2 but i don't know why this is the sys > > path: > > > '', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > setuptools-0.6c7-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg', '/home/pirataja/ > > opo.net/python/lib/python2.5/site-packages/TurboKid-1.0.4-py2.5.egg', > > '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > TurboJson-1.1.2-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > python2.5/site-packages/TurboCheetah-1.0-py2.5.egg', '/home/pirataja/ > > opo.net/python/lib/python2.5/site-packages/simplejson-1.9.1-py2.5- > > linux-i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site- > > packages/RuleDispatch-0.5a0.dev_r2306-py2.5-linux-i686.egg', '/home/ > > pirataja/opo.net/python/lib/python2.5/site-packages/PasteScript-1.6.2- > > py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > FormEncode-1.0.1-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > python2.5/site-packages/DecoratorTools-1.7-py2.5.egg', '/home/pirataja/ > > opo.net/python/lib/python2.5/site-packages/configobj-4.5.2-py2.5.egg', > > '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > CherryPy-2.3.0-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > python2.5/site-packages/kid-0.9.6-py2.5.egg', '/home/pirataja/opo.net/ > > python/lib/python2.5/site-packages/Cheetah-2.0.1-py2.5-linux- > > i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > PyProtocols-1.0a0dev_r2302-py2.5-linux-i686.egg', '/home/pirataja/ > > opo.net/python/lib/python2.5/site-packages/PasteDeploy-1.3.1- > > py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > Paste-1.7-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > python25.zip', '/home/pirataja/pirata-jacopo.net/python/lib/ > > python2.5', '/home/pirataja/opo.net/python/lib/python2.5/plat- > > linux2', > > '/home/pirataja/opo.net/python/lib/python2.5/lib-tk', > > '/home/pirataja/opo.net/python/lib/python2.5/lib-dynload', '/home/ > > pirataja/opo.net/python/lib/python2.5/site-packages'] > > > For my is all ok but whe i do import cherrypy2 i get no mudule name > > cherrypy2 > > > Regards > > > Luca > > because it's "import cherrypy" and not "import cherrypy2" sorry but from another python installation i import cherrypy2 as cherrypy and all works Regards Luca From Quill_Patricia at emc.com Wed Jun 18 04:54:13 2008 From: Quill_Patricia at emc.com (Quill_Patricia at emc.com) Date: Wed, 18 Jun 2008 04:54:13 -0400 Subject: Getting Python exit code when calling Python script from Java program Message-ID: <102AF37FC3CE794DB52B45646265EC9602387CF9@CORPUSMX30B.corp.emc.com> I have a Python script which is used to load data into a database. Up to now this script has been run by customers from the Windows command prompt using "python edg_loader.pyc". Any error messages generated are written to a log file. A project team working in the same company as me here would like to use this loading utility. They write UI applications for Windows using Java. They were able to launch the Python script from within Java by creating a Process using Java ProcessBuilder class. However, the way the error handling is currently implemented isn't really suitable for use in a UI application. As I'm sure you can appreciate it's not really feasible to tell users of a UI program to keep checking the log files while the loading is underway!!. Ideally they would like the Python loading utility to return an error code and error message - the error message could then be displayed on a message box on the UI. I seem to be having problems implementing this. I tried using the sys.exit() method in my script and passed non -zero values. However the value wasn't picked up the by Java Process.exitValue() method - it kept picking up 0. On investigation it turned out that the exit value being read is from python.exe process, not from the Python script. Is there any way I can obtain the return value of a python script from a Java program? I did manage to get some sort of return error message. I wrote a test message to sys.stderr in the Python script and this was picked up by Java Process.getErrorSteam() method. However I would really like to get the return codes working if possible and would appreciate any suggestions on how to implement this. Thanks, Patricia Quill From sjmachin at lexicon.net Sun Jun 8 04:36:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 8 Jun 2008 01:36:47 -0700 (PDT) Subject: simple question on list manipulation from a newbie References: <76ccc0a8-90de-4717-9e6f-06836827b1e1@i18g2000prn.googlegroups.com> <6hD2k.4836$co7.3109@nlpi066.nbdc.sbc.com> <9ab9cb3f-787f-4552-9dc2-3f36c4c2ebe1@j33g2000pri.googlegroups.com> Message-ID: <2e2e11fc-881f-427a-9618-33c1577dd4be@d19g2000prm.googlegroups.com> On Jun 8, 4:42 pm, Sengly wrote: [snip] > Thank you all for your help. I found a solution as the following: The following is a solution to what? > > alist = [ > {'noun': 'dog', 'domestic_dog', 'Canis_familiaris'}, That is not yet valid Python. You will get a syntax error pointing to the comma after 'domestic_dog'. Do you mean: (1) alist = [ {'noun': ('dog', 'domestic_dog', 'Canis_familiaris')}, {'noun': ('frump', 'dog')}, # etc ] or (2) alist = [ ('dog', 'domestic_dog', 'Canis_familiaris'), ('frump', 'dog'), # etc ] or (3) something else? > {'noun': 'frump', 'dog'}, > {'noun': 'dog',}, > {'noun': 'cad', 'bounder', 'blackguard', 'dog', 'hound', 'heel'}, > {'noun': 'frank', 'frankfurter', 'hotdog', 'hot_dog', 'dog', > 'wiener', 'wienerwurst', 'weenie'}, > {'noun': 'pawl', 'detent', 'click', 'dog'}, > {'noun': 'andiron', 'firedog', 'dog', 'dog-iron'}, > ] > > def getAll(alist): > list=[] > for i in range(0,len(alist)): > list.extend(alist[i][:]) Note: the use of [:] to copy the contents of each element indicates that you think that each element is a sequence (list/tuple/whatever) i.e. option (2) above. > return list > Whatever that is solving, it could be written much more clearly as: answer = [] # don't shadow the builtin list function # and use meaningful names for sublist in alist: answer.extend(sublist[:]) return answer Aside: Why do you think you need to copy sublist? Does the plot involve later mutation of alist? And it can be done even more clearly using a list comprehension: [element for sublist in alist for element in sublist] HTH, John From space.captain.face at gmail.com Sat Jun 7 18:36:44 2008 From: space.captain.face at gmail.com (Kalibr) Date: Sat, 7 Jun 2008 15:36:44 -0700 (PDT) Subject: Dynamically naming objects. References: <8a99c3fa-1eeb-49b3-a714-b6063ec1daab@d19g2000prm.googlegroups.com> <3d2a85b2-255d-4e93-8cfb-e2772f57b69a@u6g2000prc.googlegroups.com> <15z2k.1218$LL4.885@bignews7.bellsouth.net> Message-ID: <69ba93e1-c1fe-4471-8feb-fa636e9a3a56@d19g2000prm.googlegroups.com> On Jun 8, 2:58 am, Hans Nowak wrote: > Kalibr wrote: > > On Jun 7, 1:20 pm, Hans Nowak wrote: > >> Kalibr wrote: > >>> I've been developing a small script to fiddle with classes, and came > >>> accross the following problem. Assuming I get some user input asking > >>> for a number, how would I spawn 'n' objects from a class? > >>> i.e. I have a class class 'user' and I don't know how many of them I > >>> want to spawn. > >>> Any ideas? > >> Sure. This will give you a list of n instances of user: > > >> [user() for i in range(n)] > > >> Of course, you could also use a good old for loop: > > >> for i in range(n): > >> u = user() > >> ...do something with u... > > >> Hope this helps! > > >> -- > >> Hans Nowak (zephyrfalcon at gmail dot com)http://4.flowsnake.org/ > > > whoops, replied to author.... > > > What I wanted to ask before was won't 'u' be overwritten with a new > > object each time the loop ticks over? > > Yes, so you have to store it somewhere, if you want to keep the object around. > The list comprehension mentioned above stores all the objects in a list, after > which they can be accessed at will via indexing. > > > what I want to do is have, say 5 users in a game, so I'd have to spawn > > 5 objects. I can't do that because I have'nt hardcoded any object > > names for them. > > > or does it somehow work? how would I address them if they all have the > > name 'u'? > > users = [user() for i in range(n)] > > # use: users[0], users[1], etc > > -- > Hans Nowak (zephyrfalcon at gmail dot com)http://4.flowsnake.org/ Ok, wait, I see where this is going. I just did the list comprehension. I was under some misguided idea that you actually had to have a unique variable name for all the new objects you spawned. Thanks for all you help guys! From kretik at yahoo.com Wed Jun 18 02:18:51 2008 From: kretik at yahoo.com (kretik) Date: Tue, 17 Jun 2008 23:18:51 -0700 Subject: Ternary operator alternative in Ptyhon Message-ID: I'm sure this is a popular one, but after Googling for a while I couldn't figure out how to pull this off. Let's say I have this initializer on a class: def __init__(self, **params): I'd like to short-circuit the assignment of class field values passed in this dictionary to something like this: self.SomeField = \ params.has_key("mykey") ? params["mykey"] : None) Obviously I know this is not actual Python syntax, but what would be the equivalent? I'm trying to avoid this, basically: if params.has_key("mykey"): self.SomeField = params["mykey"] else: self.SomeField = None This is not a big deal of course, but I guess my main goal is to try and figure out of I'm not missing something more esoteric in the language that lets me do this. Thanks in advance. From kyosohma at gmail.com Wed Jun 25 14:43:50 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 25 Jun 2008 11:43:50 -0700 (PDT) Subject: how to give focus to another application References: Message-ID: <5e7909fb-eed2-45a8-9e94-94b8ee1f9c91@m3g2000hsc.googlegroups.com> On Jun 25, 1:23?pm, "massimo s." wrote: > Hi, > > I would like to know if 1)there is a Python way to tell under which > terminal process a Python command-line application is running 2)there > is a Python way to tell the OS to give focus to another window. > > Solutions for Windows, Linux and OS X are welcome, even if OS-specific > (of course general solutions are better, but I can kludge & check the > platform). > > Thanks, > M. On Windows, you can use the pywin32 modules to assist you. There's a sub-module in them called win32gui that has a SetForegroundWindow method. I usually use win32gui.EnumWindows() to loop through all the open processes and then use both win32gui.ShowWindow() and win32gui.SetForegroundWindow() to make the window I want appear. I'm guessing that each OS has their own methods for this as you would almost certainly have to use some kind of low-level calls to get handles on processes you didn't create. Thus, the likelihood that there are cross-platform methods is pretty low. ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org From Lie.1296 at gmail.com Sun Jun 8 02:08:38 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 7 Jun 2008 23:08:38 -0700 (PDT) Subject: New variable? References: <18105511-7ae1-45e9-8c43-f34c1c4f5aeb@c58g2000hsc.googlegroups.com> Message-ID: On Jun 4, 1:40?am, tmallen wrote: > What's the proper way to instantiate a new variable? x = ""? You don't need to. The reason why you need to "declare" variable when doing something like a += 1 is because this is actually a shorthand for a = a + 1 (unless you override __radd__), the a on the right-hand side is not yet assigned to any objects (remember that python use the "name tag" model instead of "variable" model). From hat at se-162.se.wtb.tue.nl Wed Jun 18 08:50:39 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 18 Jun 2008 14:50:39 +0200 Subject: dict order References: <4804032a-adef-4973-ae21-acc4ad2dce37@z72g2000hsb.googlegroups.com> <411fc353-dd54-4bbc-a72e-ddee66408313@c58g2000hsc.googlegroups.com> <1a7a2dc6-4acf-473d-a51c-4715ca9c7068@c19g2000prf.googlegroups.com> Message-ID: On 2008-06-18, Robert Bossy wrote: > Lie wrote: >>> Whoops, I think I misunderstood the question. If what you're asking >>> whether two dictionary is equal (equality comparison, rather than >>> sorting comparison). You could do something like this: >>> > Testing for equality and finding differences are trivial tasks indeed. > It is the sort order I'm interested in. The meaning of the order is not > really an issue, I'm rather looking for a consistent comparison function > (in the __cmp__ sense) such as: > if d1 > d2 and d2 > d3, > then d1 > d3 > > I'm not sure the hashing method suggested by Albert guarantees that. I read the post as the desire to test equality between dictionary-like data structures. With some care (see below) (and the ability to compute the hash fast), you could use hashing as way to decide that two such structures are not equal. Afaik you cannot use hashing for testing order ('<' or '>'). If I gave that impression, sorry; it was not my intention. In the equality case, you need special care with computing the hash value of the keys (and values), since you want to have the same hash result of the dictionary independent of the order of the keys. One way of achieving that is to use XOR (^) to combine hash-values of the elements. Unfortunately, XOR may not always produce good hash values. If you want ordered dictionaries (as in you can compare dictionaries with each other, and decide which is larger), I'd suggest to keep the keys of the dictionaries sorted. Dictionary comparing can then be done by comparing keys in increasing order (for example). If you encounter two non-equal keys, you immediately can use the order of those two keys as the order of the dictionaries. (ie the order of two dictionaries is decided by the order of the first non-equal keys). This gives you the transitive property (d1 > d2 and d2 > d3 implies d1 > d3). (and len() is a cheap first order filter here; dictionaries are ordered by length first, and by first non-equal keys second then.) I have used this trick to define ordered sets (which are basically dictionaries without value part). It worked like a charm. Sincerely, Albert From usenet at janc.be Fri Jun 6 16:59:47 2008 From: usenet at janc.be (Jan Claeys) Date: Fri, 06 Jun 2008 20:59:47 GMT Subject: Python is slow References: <4836772e$0$6097$426a74cc@news.free.fr> <89be7f59-4c08-4739-ab07-d310e0c6aef3@2g2000hsn.googlegroups.com> Message-ID: Op Fri, 23 May 2008 14:00:33 -0700, schreef bruno.desthuilliers at gmail.com: > Now this I can tell is false. The problem is not that it's difficult to > "make a native compiler for" dynamic languages, the problem is that it's > difficult to write native compiler for dynamic languages that generates > code that beats the VM/byte-code interpreter/whatever you name it to be > wotrh the effort. Well, it would be much easier if there would be hardware that was designed for object oriented & dynamic programming... ;-) (Most current hardware is designed for use with C & similar languages, or sometimes for massively parrallel computing (e.g. GPUs), but the last tries to design hardware to fit something like Python date back to the 1980s AFAIK...) -- JanC From johnjsal at gmailNOSPAM.com Sun Jun 15 23:11:08 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sun, 15 Jun 2008 23:11:08 -0400 Subject: newbie question: for loop within for loop confusion In-Reply-To: References: Message-ID: <4855d9d1$0$11629$607ed4bc@cv.net> takayuki wrote: > for letter in avoid: > if letter in word: > break > else: > print word Take the word 'dog', for example. What the above loop is doing is basically this: 1. for letter in avoid uses 'a' first 2. is 'a' in 'dog'? 3. no, so it prints 'dog' 4. go back to for loop, use 'b' 5. is 'b' in 'dog'? 6. no, so it prints 'dog' again 7. go back to for loop..... Since it goes sequentially through 'abcd', it will say that the first three letters are not in 'dog', and therefore print it three times. Then it finally sees that 'd' *is* in dog, so it skips it the fourth time through the loop. From cwitts at gmail.com Fri Jun 13 03:53:20 2008 From: cwitts at gmail.com (Chris) Date: Fri, 13 Jun 2008 00:53:20 -0700 (PDT) Subject: Comments on my first script? References: <7e3a7c92-6204-46dd-8df8-90218f2fb314@26g2000hsk.googlegroups.com> <4016716e-0ff7-41aa-951a-ed9562ff2ac8@m44g2000hsc.googlegroups.com> <7bb26acf-8b58-4d29-8e64-05a75eb5e584@d45g2000hsc.googlegroups.com> Message-ID: On Jun 13, 9:38?am, Phillip B Oldham wrote: > Thanks guys. Those comments are really helpful. The odd semi-colon is > my PHP background. Will probably be a hard habbit to break, that > one! ;) If I do accidentally drop a semi-colon at the end of the line, > will that cause any weird errors? > > Also, Chris, can you explain this: > a, b = line.split(': ')[:2] > > I understand the first section, but I've not seen [:2] before. That's slicing at work. What it is doing is only taking the first two elements of the list that is built by the line.split. From eliben at gmail.com Sat Jun 21 09:46:15 2008 From: eliben at gmail.com (eliben) Date: Sat, 21 Jun 2008 06:46:15 -0700 (PDT) Subject: Fast and easy GUI prototyping with Python References: <9c349bf0-ef63-4463-bd4e-cdbe331b58c3@z66g2000hsc.googlegroups.com> Message-ID: <2ad5ed9b-b813-4a8c-8aa5-cd87f02c2b27@s50g2000hsb.googlegroups.com> On Jun 21, 3:36 pm, ero... at gmail.com wrote: > Which tools would you use? I want the interface design to be as easy > and fast as possible, all ideology aside. I'm considering either > IronPython+Visual Studio or Python+Qt -- but I'm open for other > suggestions. > > Visual Studio seems to offer the easiest solution, but is IronPython > stable enough? How easy is the IronPython/Visual Studi integration? > What about IronPython Studio? I've had success using wxPython in conjunctin with wxGlade. wxGlade is quite flexible, allows quick previews and generates code that's not bad. The wxPython binding is very well supported and works nicely in practice. And, best of all, this solution is both free and completely cross-platform. Eli From bees.inc at gmail.com Wed Jun 4 04:03:42 2008 From: bees.inc at gmail.com (BEES INC) Date: Wed, 4 Jun 2008 18:03:42 +1000 Subject: Interesting Math Problem Message-ID: <748f2d520806040103q48689a01i310ee07df20a5e73@mail.gmail.com> I've been awfully busy programming lately. My Django-based side project is coming along well and I hope to have it ready for use in a few weeks. Please don't ask more about it, that's really all I can say for now. Anyways, I came across an interesting little math problem today and was hoping some skilled programmers out there could come up with a more elegant solution than mine. Problem: Star Ratings People can rate cheeseburgers on my website with a star rating of 0-5 stars (whole stars only), 5 being mighty tasty and 0 being disgusting. I would like to show the average of everyone's ratings of a particular cheeseburger to the nearest half star. I have already calculated the average rating as a float (star_sum) and the total number of people that rated the particular cheeseburger (num_raters). The result should be stored as a float in a variable named "stars." My Solution (in Python): # round to one decimal place and # separate into whole and fractional parts parts = str(round(star_sum/num_raters, 1)).split('.') whole = int(parts[0]) frac = int(parts[1]) if frac < 3: ___frac = 0 elif frac > 7: ___frac = 0 ___whole += 1 else: ___frac = 5 # recombine for a star rating rounded to the half stars = float(str(whole)+'.'+str(frac)) Mmmm? In-N-Out Burgers? Please reply if you've got a better solution. From larry.bates at websafe.com` Mon Jun 30 09:13:30 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 30 Jun 2008 08:13:30 -0500 Subject: List Performance In-Reply-To: References: <42358e0b-a351-4862-8f6a-1938eedeff6c@s21g2000prm.googlegroups.com> Message-ID: <2eydnaP-saOZQfXVnZ2dnUVZ_qvinZ2d@comcast.com> Peter Otten wrote: > Ampedesign wrote: > >> If I happen to have a list that contains over 50,000 items, will the >> size of the list severely impact the performance of appending to the >> list? > > No. > > $ python -m timeit -n20000 -s"items = []" "items.append(42)" > 20000 loops, best of 3: 0.554 usec per loop > $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" > 20000 loops, best of 3: 0.529 usec per loop > > http://wiki.python.org/moin/TimeComplexity > > Peter Peter, So its actually faster to append to a long list than an empty one? That certainly would not have been intuitively obvious now would it? -Larry From d3vvnull at gmail.com Thu Jun 5 07:51:54 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Thu, 5 Jun 2008 06:51:54 -0500 Subject: Python and Harry Potter? In-Reply-To: <6apvtsF3892asU1@mid.uni-berlin.de> References: <6aprloF38p4l7U1@mid.dfncis.de> <6apvtsF3892asU1@mid.uni-berlin.de> Message-ID: <170543c70806050451v326bf862l1b3a5e752328e8fb@mail.gmail.com> Harry Potter is a Parselmouth. He can speak to snakes. Of course, Amazon would get this right! Sheesh! On Thu, Jun 5, 2008 at 6:10 AM, Marc 'BlackJack' Rintsch wrote: > On Thu, 05 Jun 2008 11:58:14 +0200, Helmut Jarausch wrote: > > > Today I've got an email from Amazon recommending me > > Harry Potter and the Deathly Hallows > > > > and they told me why they recommended this book, > > because I've bought > > Core PYTHON Programming > > > > Didn't know, Harry Potter is a Python fan. > > I would've expected something with more magic, like Perl. :-) > > Ciao, > Marc 'BlackJack' Rintsch > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From s0suk3 at gmail.com Sat Jun 28 02:54:22 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Fri, 27 Jun 2008 23:54:22 -0700 (PDT) Subject: surprising behaviour of os.environ.clear References: Message-ID: <494d6aa7-5c66-4dab-98d9-2d3ac66fe198@a70g2000hsh.googlegroups.com> On Jun 27, 4:05 pm, "Joe P. Cool" wrote: > If I call os.environ.clear in a python program child processes still > see the deleted entries. But when I iterate over the keys like so > > names = os.environ.keys > for k in names: > del os.environ[k] > > then the entries are also deleted for the child processes. Where is > the difference? Is this a bug? > (Observed in Python 2.5.2) > For one thing, the expression 'os.environ.keys' will yield a method object (not a list, as you're probably expecting), but iterating over a method as you did should produce an exception. If you want to get the list of environment vars, you have to call the method, like 'os.environ.keys()'. Also, aren't changes to environment vars supposed to be visible to child processes anyway? Which one are you suggesting that behaves the wrong way, 'os.environ.clear()' or 'del os.environ[key]'? From alexnbryan at gmail.com Sat Jun 21 23:24:01 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Sat, 21 Jun 2008 22:24:01 -0500 Subject: Connecting a Desktop App to a Web App Message-ID: <61460E55-28FD-42A3-85EB-4D352E21CC30@gmail.com> Okay, well I wouldn't be creating the app, so, any hints on how to figure out the API of a web app I don't know super well? From support.intranet at libero.it Wed Jun 4 12:40:54 2008 From: support.intranet at libero.it (support.intranet at libero.it) Date: Wed, 4 Jun 2008 09:40:54 -0700 (PDT) Subject: Exit from os.chroot() References: Message-ID: On 4 Giu, 17:08, Wolfgang Draxinger wrote: > support.intranet wrote: > > Hello! I'm writing a small script and I need to call the > > os.chroot function. The problem is, a few lines below I need to > > call a program in /usr/bin. Is there a way to exit from the > > chroot, or to limit the chroot to a single function or thread? > > Thanks in advance > > No, chroot applies to the whole process and once applied it can't > be reverted. Otherwise the whole idea of chroot being a FS jail > would not work. > > So you need some programs in your chroot: Then put a directory > usr/bin into the chroot directory and bind the system's /usr/bin > there: > > mount --bind /usr/bin $chroot/usr/bin > > The same has to be done with all library stuff. Another option > would be to place a statically linked busybox and it's > subprogram links into the chroot > > Wolfgang Draxinger > -- > E-Mail address works, Jabber: hexar... at jabber.org, ICQ: 134682867 Thanks! I'll try the bind way From mensanator at aol.com Fri Jun 6 21:00:06 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 6 Jun 2008 18:00:06 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> <0294ec96$0$25039$c3e8da3@news.astraweb.com> Message-ID: <2fcf90a2-349d-4ef1-8f67-a357be71738f@d1g2000hsg.googlegroups.com> On Jun 6, 3:19?pm, "John Salerno" wrote: > "Mensanator" wrote in message > > news:c55356a4-04a0-442e-ad84-f35156cdec9c at z72g2000hsb.googlegroups.com... > On Jun 6, 1:44 am, "Terry Reedy" wrote: > > > "Mensanator" wrote in message > > And since the OP foolishly > hardcoded his range bounds > > Hmm, I just love the arrogance of some people. I actually posted a response > to my own thread that asked about this situation of how best to make the > range, but it doesn't seem to have posted. It wasn't meant to be arrogant. Just that you must be careful with zip() because it will not throw an exception if the two iterables are of different length (this behaviour is by design) but simply return tuples for the shorter of the iterables. Hardcoding the range bounds instead of setting them dynamically is a classic cause of this type of error. Obviously, you want the range to start with 8, but what should be the upper bound? The start plus the length of the other iterable keeping in mind that if length is 11, last index is 8+10 since counting starts at 0. So you want range(8,8+len(score_costs)) Using enumerate() means you don't have to figure this out and you'll never get an error or bad results that don't make an error. From kamhung.soh at gmail.com Fri Jun 6 19:03:23 2008 From: kamhung.soh at gmail.com (Kam-Hung Soh) Date: Sat, 07 Jun 2008 09:03:23 +1000 Subject: readline() & seek() ??? In-Reply-To: <078bfcbf-4f6c-459c-9f68-619af24c3678@27g2000hsf.googlegroups.com> References: <12655f64-33b1-4ab0-b6fb-294bfd2fa8c6@d45g2000hsc.googlegroups.com> <078bfcbf-4f6c-459c-9f68-619af24c3678@27g2000hsf.googlegroups.com> Message-ID: Chris wrote: > On Jun 6, 5:13 am, Kam-Hung Soh wrote: >> Tim Roberts wrote: >>> DataSmash wrote: >>>> I have a text file that contains thousands of lines and each line is >>>> 256 characters long. >>>> This is my task: >>>> For each line in the file, move to the 25th character, if the >>>> character is a "T", >>>> move to the 35th character of the line and read 5 characters from >>>> there. >>>> Capture these 5 characters and write them to a new text file, each 5 >>>> characters separated by a comma. >>>> I appreciate your help! >>> Did you even TRY this? Your task reads like pseudocode that translates >>> virtually line-for-line to Python code. >>> fout = open('outputfile.txt','w') >>> for line in open('inputfile.txt'): >>> if line[24] == 'T': >>> fout.write( line[34:39] + ',' ) >> Should the last line be ... >> >> fout.write(','.join(line[34:39]) >> >> -- >> Kam-Hung Soh Software Salariman > > each 5 characters need to be delimited by a comma, your statement > would have a comma between each of the 5 characters. You're right; I see where I got confused. -- Kam-Hung Soh Software Salariman From s0suk3 at gmail.com Sat Jun 7 02:57:03 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Fri, 6 Jun 2008 23:57:03 -0700 (PDT) Subject: Parsing a path to components References: <7d7dd66c-b2bb-4a9a-a2e4-589079cda97b@e39g2000hsf.googlegroups.com> Message-ID: <14bf5448-4677-4ced-9d79-b4eb0c048218@56g2000hsm.googlegroups.com> On Jun 7, 12:55?am, eliben wrote: > Hello, > > os.path.split returns the head and tail of a path, but what if I want > to have all the components ? I could not find a portable way to do > this in the standard library, so I've concocted the following > function. It uses os.path.split to be portable, at the expense of > efficiency. > > ---------------------------------- > def parse_path(path): > ? ? """ Parses a path to its components. > > ? ? ? ? Example: > ? ? ? ? ? ? parse_path("C:\\Python25\\lib\\site-packages\ > \zipextimporter.py") > > ? ? ? ? ? ? Returns: > ? ? ? ? ? ? ['C:\\', 'Python25', 'lib', 'site-packages', > 'zipextimporter.py'] > > ? ? ? ? This function uses os.path.split in an attempt to be portable. > ? ? ? ? It costs in performance. > ? ? """ > ? ? lst = [] > > ? ? while 1: > ? ? ? ? head, tail = os.path.split(path) > > ? ? ? ? if tail == '': > ? ? ? ? ? ? if head != '': lst.insert(0, head) > ? ? ? ? ? ? break > ? ? ? ? else: > ? ? ? ? ? ? lst.insert(0, tail) > ? ? ? ? ? ? path = head > > ? ? return lst > ---------------------------------- > > Did I miss something and there is a way to do this standardly ? > Is this function valid, or will there be cases that will confuse it ? > You can just split the path on `os.sep', which contains the path separator of the platform on which Python is running: components = pathString.split(os.sep) Sebastian From aisaac at american.edu Thu Jun 5 19:58:15 2008 From: aisaac at american.edu (Alan Isaac) Date: Thu, 05 Jun 2008 23:58:15 GMT Subject: parser recommendation In-Reply-To: References: Message-ID: One other possibility: SimpleParse (for speed). It is very nice. Alan Isaac From sjmachin at lexicon.net Wed Jun 25 19:02:52 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 25 Jun 2008 16:02:52 -0700 (PDT) Subject: Newbie question about tuples and list comprehensions References: Message-ID: On Jun 26, 7:37 am, idiolect wrote: > Hi all - Sorry to plague you with another newbie question from a > lurker. Hopefully, this will be simple. > > I have a list full of RGB pixel values read from an image. I want to > test each RGB band value per pixel, and set it to something else if it > meets or falls below a certain threshold - i.e., a Red value of 0 > would be changed to 50. > > I've built my list by using a Python Image Library statement akin to > the following: > > data = list(image.getdata()) > > Which produces a very long list that looks like [(0,150,175), > (50,175,225),...]. I'm trying to figure out a fast and pythonic way > to perform my operation. The closest I've come so far to a succinct > statement is a list comprehension along the syntax of: > > source = [((x,y,z),(x+50,y+50,z+50))[bool(x or y or z < 50)] for > (x,y,z) in source] > > ...which kind of approaches the effect I'm looking for, but it doesn't > really test and change each value in the tuple individually. My > understanding of the things you can do with lists and python in > general is rather naive, so I would appreciate any insight anyone can > offer since I am not sure if I'm even headed down the correct path > with list comprehensions. > "x or y or z < 50" doesn't do what you think it does: >>> x, y, z = 120, 130, 140 >>> x or y or z < 50 120 >>> ((x or y) or z) < 50 False >>> x or (y or (z < 50)) 120 >>> Here's one approach (requires Python 2.5 or later): [(50 if x < 50 else x, 50 if y < 50 else y, 50 if z < 50 else z) for (x, y, z) in source] From florencio.cano at gmail.com Wed Jun 11 04:33:52 2008 From: florencio.cano at gmail.com (Florencio Cano) Date: Wed, 11 Jun 2008 10:33:52 +0200 Subject: How to view how much memory some process use in Windows? Message-ID: How can I monitor with a Python script how much memory does a process use in Windows? I want to do statistics about memory consumption of processes like Firefox, Antivirus, etc. When I search in Google I only find information about how to monitor this in linux or how to reduce Python programs memory usage. From davidreynon at gmail.com Tue Jun 17 17:12:53 2008 From: davidreynon at gmail.com (korean_dave) Date: Tue, 17 Jun 2008 14:12:53 -0700 (PDT) Subject: using the string functions (ex. find()) on a multi-symbol string Message-ID: <8debb6d8-2181-4938-be02-5579b4ed8e14@d45g2000hsc.googlegroups.com> How can i use the find() function on a string that is composed of tons of symbols that cause errors... THis is my string: find("

    Connected!

    ","margin") The tough part about this is that the string is dynamically produced. So I can't manually go into the string and eliminate the quote-marks or to "literal-character" them. From tjreedy at udel.edu Thu Jun 26 18:04:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 26 Jun 2008 18:04:40 -0400 Subject: Error when interfacing with TCP/IP In-Reply-To: <538D574F1250484EA840C88924E04B5E0C8A45AA@vistap101.vlgdc.visteon.com> References: <538D574F1250484EA840C88924E04B5E0C8A45AA@vistap101.vlgdc.visteon.com> Message-ID: Devarajulu, Baskar (D.) wrote: > Hi, > > I'm using Python and working for automation of testing ,I face error > when the script accessed TCP/IP Interface > > COMM_TYPE = 1 # Choose 1 - TCP IP Communication or 0 - > RS232 communication. > TCP_ip = '136.18.201.53' # the TCP IP address of the PC. > port = 8080 > BAUD_RATE = 115200 > > if (COMM_TYPE == 1): > asap3.TcpOpen(TCP_ip,port) > > Error: > > C:/Apps/dSPACE51/Common/Python22/Modules/InterfaceLibs/asap3lib.py", > line 320, in TcpOpen > asap3libError: Error connect TCP/IP > Thanks if you can help. asap3lib.py is not part of the stdlib, and the error message is not very informative. Look at line 320 and see what might trigger the error. From carbonimax at gmail.com Mon Jun 23 09:02:34 2008 From: carbonimax at gmail.com (Carbonimax) Date: Mon, 23 Jun 2008 06:02:34 -0700 (PDT) Subject: py2exe, PyQT, QtWebKit and jpeg problem References: Message-ID: <2b292f88-db2d-4fd3-a4b2-de72ff1b5387@c58g2000hsc.googlegroups.com> On Jun 21, 12:21?am, David Boddie wrote: > On Friday 20 June 2008 17:24, Phil Thompson wrote: > > > On Fri, 20 Jun 2008 08:04:57 -0700 (PDT), Carbonimax > > wrote: > >> I have a problem with py2exe and QtWebKit : > >> I make a program with a QtWebKit view. > >> If I launch the .py directly, all images (jpg, png) are displayed but > >> if I compile it with py2exe I have only png images. No jpg ! > >> No error message, nothing. > > >> Have you a solution ? Thank you. > > > At a guess, the JPEG support is implemented as a Qt plugin which you are > > not including. > > Yes, that would appear to the be most obvious cause. See here for another > report about this: > > http://lists.trolltech.com/qt4-preview-feedback/2008-03/msg00064.html > > David How can I do that ? If I copy the dll in the dist directory, and I use QPluginLoader() and load(), it does work in the .py but it doesn't in .exe made with py2exe my code : dll = QPluginLoader(path_to_dll) res = dll.load() res == true in the .py res == false in the .exe :-/ From ptmcg at austin.rr.com Wed Jun 18 10:01:23 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 18 Jun 2008 07:01:23 -0700 (PDT) Subject: Does '!=' equivelent to 'is not' [drifting OT...] References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> Message-ID: <9f496e22-31e8-4135-a3bc-a020476a90f5@b1g2000hsg.googlegroups.com> On Jun 17, 7:09?am, Derek Martin wrote: > On Tue, Jun 17, 2008 at 04:33:03AM -0300, Gabriel Genellina wrote: > > > Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)' > > > and 'not(id(a) == id(b))' > > > No. > > > Saying a flat "no" alone, without qualifying your statement is > generally interpreted as rude in English... ?It's kind of like how you > talk to children when they're too young to understand the explanation. > Yucky. > Geez, man, this is Usenet. If you want rude or condescending, the answer would have been "No, you flatulent moron." Or maybe the alarmist, "No! No! No!" I see the unqualified "No." often on this list, as a short cut for "Your technical explanation is flawed or has overlooked a critical point or corner case," and is usually followed by more details further down in the post to explain what the misconception or oversight was. Back in my college days, I would not be surprised for a professor to respond "No." (or worse) if I offered an erroneous explanation to another student. The unqualified "No." may be curt, and on a more sensitive day, one might write "No. (see below)", but as one of the most informed and careful posters on this list, I'm inclined to give Gabriel a little slack. -- Paul From alexnbryan at gmail.com Tue Jun 10 12:28:35 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 10 Jun 2008 09:28:35 -0700 (PDT) Subject: problems with opening files due to file's path Message-ID: <17759531.post@talk.nabble.com> Okay, so what I want my program to do it open a file, a music file in specific, and for this we will say it is an .mp3. Well, I am using the system() command from the os class. The problem I am running into is that when I send the path of the file to the system() command, which for those of you who don't know the system command is the equivalent of typing one command into command prompt or terminal depending on your system. But let's say that the file is "C:\Music\01 - Track.mp3" or something like that where the number 0 is next to the backslash. Another example is this "C:\Music\track(single)\Track.mp3" The problem here is that the ")" at the end of the single, is conflicting with the backslash as well. Now here is the exact code I was trying to do and when I run it I get false returned. system("\"C:\Documents and Settings\Alex\My Documents\My Music\Rhapsody\Bryanbros\Weezer\(2001)\04 - Island In The Sun.wma\"") Okay, now as you can see it sends it to the system with quotes "\"" and works if I change the file path and get rid of the "04" and the ")" it works, so that is the problem no doubt. If anyone has a way to do this please let me know, or even another way to open a music file like this. Help? -- View this message in context: http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17759531.html Sent from the Python - python-list mailing list archive at Nabble.com. From davidj411 at gmail.com Fri Jun 27 12:38:31 2008 From: davidj411 at gmail.com (davidj411) Date: Fri, 27 Jun 2008 09:38:31 -0700 (PDT) Subject: Using Python Scripts with IIS - ASP or Python-based CGI scripts with IIS - which makes more sense? Message-ID: when does is make sense to use a ASP style Page (.psp) over a Python- based CGI script with IIS. ? http://support.microsoft.com/kb/276494 ASP requires registering the python engine. which has better performance? The ASP style uses a new part of the python language which is unfamiliar to me, e.g. "Response.Write('Python Test
    ')" . Where can i learn about the syntax for ASP (PSP) with Python? Thanks! From duncan.booth at invalid.invalid Wed Jun 11 17:10:41 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Jun 2008 21:10:41 GMT Subject: basic code of what I am doing References: Message-ID: Alexnb wrote: > path = self.e.get() > path = "\"" + path + "\"" > os.startfile(path) Why are you adding spurious quote marks round the filename? os.startfile() will strip them off, but you don't need them. The help for os.startfile() does say though that the path must not start with a /, so you should use os.normpath to be on the safe side: os.startfile(os.path.normpath(self.e.get()) Anyway, the code works either with that change, or as you originally wrote it provided the path does not start with /. What was the question again? From floris.bruynooghe at gmail.com Mon Jun 30 20:25:54 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Mon, 30 Jun 2008 17:25:54 -0700 (PDT) Subject: lxml validation and xpath id function Message-ID: <018b5155-64f5-46b3-b426-7e6d6d1b20e3@k37g2000hsf.googlegroups.com> Hi I'm trying to use the .xpath('id("foo")') function on an lxml tree but can't get it to work. Given the following XML: And it's XMLSchema: Or in more readable, compact RelaxNG, form: element root { element child { attribute id { xsd:ID } } } Now I'm trying to parse the XML and use the .xpath() method to find the element using the id XPath function: from lxml import etree schema_root = etree.parse(file('schema.xsd')) schema = etree.XMLSchema(schema_root) parser = etree.XMLParser(schema=schema) root = etree.fromstring('', parser) root.xpath('id("foo")') --> [] I was expecting to get the element with that last statement (well, inside a list that is), but instead I just get an empty list. Is there anything obvious I'm doing wrong? As far as I can see the lxml documentation says this should work. Cheers Floris From cwitts at gmail.com Fri Jun 13 10:38:11 2008 From: cwitts at gmail.com (Chris) Date: Fri, 13 Jun 2008 07:38:11 -0700 (PDT) Subject: urllib (54, 'Connection reset by peer') error References: <92ecee86-ba92-4f14-b4f8-05064ef5406c@f63g2000hsf.googlegroups.com> Message-ID: <7cb6e19e-74f8-453d-b131-9b3739991cf9@s50g2000hsb.googlegroups.com> On Jun 13, 4:21?pm, chrispoliq... at gmail.com wrote: > Hi, > > I have a small Python script to fetch some pages from the internet. > There are a lot of pages and I am looping through them and then > downloading the page using urlretrieve() in the urllib module. > > The problem is that after 110 pages or so the script sort of hangs and > then I get the following traceback: > > > > Traceback (most recent call last): > ? File "volume_archiver.py", line 21, in > ? ? urllib.urlretrieve(remotefile,localfile) > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/urllib.py", line 89, in urlretrieve > ? ? return _urlopener.retrieve(url, filename, reporthook, data) > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/urllib.py", line 222, in retrieve > ? ? fp = self.open(url, data) > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/urllib.py", line 190, in open > ? ? return getattr(self, name)(url) > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/urllib.py", line 328, in open_http > ? ? errcode, errmsg, headers = h.getreply() > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/httplib.py", line 1195, in getreply > ? ? response = self._conn.getresponse() > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/httplib.py", line 924, in getresponse > ? ? response.begin() > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/httplib.py", line 385, in begin > ? ? version, status, reason = self._read_status() > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/httplib.py", line 343, in _read_status > ? ? line = self.fp.readline() > ? File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/socket.py", line 331, in readline > ? ? data = recv(1) > IOError: [Errno socket error] (54, 'Connection reset by peer') > > > > My script code is as follows: > ----------------------------------------- > import os > import urllib > > volume_number = 149 # The volumes number 150 to 544 > > while volume_number < 544: > ? ? ? ? volume_number = volume_number + 1 > ? ? ? ? localfile = '/Users/Chris/Desktop/Decisions/' + str(volume_number) + > '.html' > ? ? ? ? remotefile = 'http://caselaw.lp.findlaw.com/scripts/getcase.pl? > court=us&navby=vol&vol=' + str(volume_number) > ? ? ? ? print 'Getting volume number:', volume_number > ? ? ? ? urllib.urlretrieve(remotefile,localfile) > > print 'Download complete.' > ----------------------------------------- > > Once I get the error once running the script again doesn't do much > good. ?It usually gets two or three pages and then hangs again. > > What is causing this? The server is causing it, you could just alter your code import os import urllib import time volume_number = 149 # The volumes number 150 to 544 localfile = '/Users/Chris/Desktop/Decisions/%s.html' remotefile = 'http://caselaw.lp.findlaw.com/scripts/getcase.pl? court=us&navby=vol&vol=%s' while volume_number < 544: volume_number += 1 print 'Getting volume number:', volume_number try: urllib.urlretrieve(remotefile%volume_number,localfile %volume_number) except IOError: volume_number -= 1 time.sleep(5) print 'Download complete.' That way if the attempt fails it rolls back the volume number, pauses for a few seconds and tries again. From sspatz at kcnet.com Sun Jun 22 09:44:25 2008 From: sspatz at kcnet.com (Saul Spatz) Date: Sun, 22 Jun 2008 08:44:25 -0500 Subject: Learning Python: Code critique please In-Reply-To: <2f25e0ae-5828-4651-8ac6-55ba8bb50089@p25g2000pri.googlegroups.com> References: <2f25e0ae-5828-4651-8ac6-55ba8bb50089@p25g2000pri.googlegroups.com> Message-ID: macoovacany wrote: > http://macoovacany.wordpress.com/ When I tried to run it, I got all kinds of syntax errors because of non-ASCII characters; namely, you have fancy left and right single and double quotes. Once I replaced these with the ASCII equivalents, it worked fine. I suggest you use a plain ASCII text editor, like the one that comes with IDLE. HTH, Saul From taygunkekec at gmail.com Mon Jun 23 08:21:08 2008 From: taygunkekec at gmail.com (Taygun Kekec) Date: Mon, 23 Jun 2008 05:21:08 -0700 (PDT) Subject: Learning Python in a group References: <507738ef0806220343r3e9ea053neeec0baf0ccfdbe6@mail.gmail.com> <18c1e6480806220422x5d06c54byd23b249bb699691f@mail.gmail.com> <507738ef0806220452s74358615v44518469cf3b5f45@mail.gmail.com> <18c1e6480806220511s5117aef4gb4ec93bceb44a0ac@mail.gmail.com> <337ab3f9-5334-4737-baac-fded524e6d99@s50g2000hsb.googlegroups.com> Message-ID: hi guys. I would be glad to join your group because i want to learn deeper python but i am frustrated of isolation too. It would provide stimulation and encourage to study and will boost our desire to learn. So count me in! From schickb at gmail.com Tue Jun 24 19:19:23 2008 From: schickb at gmail.com (schickb) Date: Tue, 24 Jun 2008 16:19:23 -0700 (PDT) Subject: Sequence iterators with __index__ References: <433c6aca-745e-4c9f-b182-d76291449829@m73g2000hsh.googlegroups.com> Message-ID: <119bb268-2064-4128-8006-f5564f0c62f8@q27g2000prf.googlegroups.com> On Jun 24, 3:45?pm, Matimus wrote: > > > I think it would be useful if iterators on sequences had the __index__ > > method so that they could be used to slice sequences. I was writing a > > class and wanted to return a list iterator to callers. ?I then wanted > > to let callers slice from an iterator's position, but that isn't > > supported without creating a custom iterator class. > > Could you post an example of what you are talking about? I'm not > getting it. Interactive mock-up: >>> a = ['x','y','z'] >>> it = iter(a) >>> a[it:] ['x', 'y', 'z'] >>> it.next() 'x' >>> a[it:] ['y', 'z'] >>> a[:it] ['x'] >>> it.next() 'y' >>> a[it:] ['z'] This lets you use sequence iterators more general position indicators. Currently if you want to track a position and slice from a tracked position you must do it manually with an integer index. It's not difficult, but given that sequence iterators already do that already it seems redundant (and of course more error prone). > In any case, the first step is writing a PEP.http://www.python.org/dev/peps/ > Ok thanks, but I do want some idea of interest level before spending a bunch of time on this. -Brad From keasler at llnl.gov Fri Jun 20 18:33:46 2008 From: keasler at llnl.gov (Jeff Keasler) Date: Fri, 20 Jun 2008 15:33:46 -0700 Subject: optparse functionality missing Message-ID: <485C304A.7030107@llnl.gov> Hi, optparse doesn't seem to have a pass-through capability for command line parameters/options that were not registered with add_option. I'm not the first person to complain about this. On Wed Mar 17 08:20:10 CET 2004, there's a thread titled "Perceived optparse shortcomings" where someone complains of the same problem. In a scripting environment, I often want to strip some of the command line options off the argument list, and then pass the remaining options to another module that is deeper in the tool chain. optparse doesn't seem to allow this, as far as I can tell. It requires that you register all possible options with add_option() or an error is flagged. When my second tier module is an autoconf script that could have hundreds of its own options, it seems dumb to have to register all those options, just to have to reconvert them to command-line options so that I can pass them to the autoconf command line. Could we get a mode added to optparse so that any commandline parameters/options that are not registered via add_option() can be in the args return value of the parse_args() method? -Jeff From ddasilva at umd.edu Sat Jun 28 02:02:47 2008 From: ddasilva at umd.edu (Daniel da Silva) Date: Sat, 28 Jun 2008 02:02:47 -0400 Subject: this is simple... In-Reply-To: <716a7999-a2c3-4792-90f5-f253c1e8296b@j33g2000pri.googlegroups.com> References: <716a7999-a2c3-4792-90f5-f253c1e8296b@j33g2000pri.googlegroups.com> Message-ID: <8d9ec3dd0806272302y48efe2f1ta2eb3f12bdfddcad@mail.gmail.com> ToshiBoy, You might want to take a look at the filter() function, it can also be used for the kind of the thing you're doing. http://docs.python.org/tut/node7.html#SECTION007130000000000000000 >>> B = range(1,27) >>> def test(b): ... if b*b in B: ... return True ... else: ... return False ... >>> A = filter(test, B) >>> A [1, 2, 3, 4, 5] Daniel On Sat, Jun 28, 2008 at 1:00 AM, ToshiBoy wrote: > On Jun 28, 2:48 pm, Mel wrote: > > ToshiBoy wrote: > > > I have two lists A and B that are both defined as range(1,27) I want > > > to find the entries that are valid for A = BxB > > [ ... ] > > > I get, as expected 1,4,9,16,25 printed out being the only members of B > > > where the condition is true, but when I print B I get: > > > > > [1, 2, 3, 4, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25] > > > > > 1 to 5 is correct, but why doesn't the remove method remove 7 and > > > above? What am I doing wrong here? > > > > Try this: > > > > A = range(1,27) > > B = range(1,27) > > C = [] > > > > for b in B: > > print "Trying", b > > if b*b in A: > > print b > > C.append (b) > > else: > > print "Removing", b > > B.remove(b) > > print 'B', B > > print 'C', C > > > > The essential problem is that your `B.remove`s are pulling the rug out > from > > under your `for b in B:`. There are ways to mess with B while you > iterate. > > Running though B backwards will do: `for b in B[::-1]:`, or iterating > over > > a copy of B: `for b in B[:]:` or `for b in list(B):`. Leaving B alone > and > > building up the desired items in C is probably simplest. > > > > Mel. > > Thank you, of course! :-) Didn't even think of that... that I was > modifying my iterators... > > Thank you > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From irmen.NOSPAM at xs4all.nl Sun Jun 29 07:43:34 2008 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 29 Jun 2008 13:43:34 +0200 Subject: pixel colour on screen In-Reply-To: References: Message-ID: <4867756b$0$14358$e4fe514c@news.xs4all.nl> Dennis Lee Bieber wrote: > On Sat, 28 Jun 2008 11:47:46 -0700 (PDT), cjstuttle at hotmail.com > declaimed the following in comp.lang.python: > >> Could anyone help me, I'm a python noob and need some help. im trying >> to find some code that will, given a screen co-ordinate, will give me >> the colour of that pixel in RGB. i have found a lot about getting the >> pixel colour from a picture file with a given co-ordinate, but is it >> possible to do it from the whole screen output regardless what >> application the selected pixel is in? >> > Such capability differs with OS and GUI libraries. If one is lucky, > the GUI library will accept any screen coordinate -- but it is just as > likely that the OS could limit a program to only coordinates within its > own window. Maybe the easiest way is to create a screenshot of the whole screen (that should be doable from within a program, although this differs for every OS and GUI lib as well) and then get the pixel value from that. --irmen From ahaupt at gmail.com Tue Jun 17 06:11:06 2008 From: ahaupt at gmail.com (AndreH) Date: Tue, 17 Jun 2008 03:11:06 -0700 (PDT) Subject: pyinotify issue References: Message-ID: <6297fd1a-89d2-482f-8a20-5539f7784b57@k13g2000hse.googlegroups.com> On Jun 13, 3:39 pm, AndreH wrote: > Good day, > > I just installed pyinotify on my gentoo box. > > When I test the library through "pyinotify.pv -v /tmp" under root, > everything works great, but when I try the same thing under my local > user account, I receive the following error: > Error: cannot watch . (WD=-1) > > Not very helpful. I've tried VERBOSE=True mode, but it doens't provide > any additional information. > > I also tried it for a directory in my home folder just to be sure it's > not a permission problem, but no luck. > > Any ideas? > > Regards, > Andre Ok I ended up solving my problem. pyinotify is just a wrapper for the c lib, inotif.h. Installing the inotify-tools package allows one to do better troubleshooting. First, my kernel version was too old and did not allow inotify to be executed at user-level. I bumped my kernel up to 2.6.24 and enabled the user-level execution flag. Then pyinotify worked once and failed for all consecutive retries. inotifwatch said that my "maximum number of user watches" was maxed out and that I should increase it under /proc/sys/fs/inotify/ max_user_watches. Something must be wrong, since the max_user_watches was set to 8192. I played around with this setting (sysctl -w fs.inotify.max_user_watches=16843), pyinotify.py and inotifywatch, and finally came the conclusion that pyinotify 0.7.0 was buggy. I got hold of 0.7.1 which seems to have fixed this problem. Hopefully, I'm not speaking too soon. From rychphd at gmail.com Mon Jun 23 08:32:55 2008 From: rychphd at gmail.com (rych) Date: Mon, 23 Jun 2008 05:32:55 -0700 (PDT) Subject: how to export functions by name for ctype References: <8f76bf6e-08b1-4af9-a739-bdc018553374@a1g2000hsb.googlegroups.com> Message-ID: On 23 Jun, 10:32, Nick Craig-Wood wrote: > rych wrote: > > ?I'm on Windows with VS2005 testing ctypes on a very simple dll > > ?I create a test.dll project which exports a function fntest(). I don't > > ?touch anything in the autogenerated source and build it. I can load > > ?the dll but can't access the function by its name fntest. Only by > > ?ordinal number or calling getattr with "?fntest@@YAHXZ". How do I > > ?export functions by name? It's probably rather a VS2005 question, but > > ?I'm a bit disappointed ctypes doesn't work with a default export > > ?convention. > > I guess you've compiled your DLL with C++ and the above is a C++ > mangled name. > > Either compile it with C, or export the names in an extern "C" { } > block. > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick That fixed it, thank you. From trepca at gmail.com Sat Jun 21 03:05:15 2008 From: trepca at gmail.com (Sebastjan Trepca) Date: Sat, 21 Jun 2008 09:05:15 +0200 Subject: Weird local variables behaviors In-Reply-To: <8e8a1d67-4d5f-4b52-a1aa-5a08f9530b75@y21g2000hsf.googlegroups.com> References: <8e8a1d67-4d5f-4b52-a1aa-5a08f9530b75@y21g2000hsf.googlegroups.com> Message-ID: I see, intuitively one would think it would try to get it from global context as it's not yet bound in the local. Thanks for the explanation. Sebastjan On Sat, Jun 21, 2008 at 5:48 AM, Dan Bishop wrote: > On Jun 20, 7:32 pm, Matt Nordhoff wrote: >> Sebastjan Trepca wrote: >> > Hey, >> >> > can someone please explain this behavior: >> >> > The code: >> >> > def test1(value=1): >> > def inner(): >> > print value >> > inner() >> >> > def test2(value=2): >> > def inner(): >> > value = value >> > inner() >> >> > test1() >> > test2() >> >> > [trepca at sauron ~/dev/tests]$ python locals.py >> > 1 >> > Traceback (most recent call last): >> > File "locals.py", line 13, in >> > test2() >> > File "locals.py", line 10, in test2 >> > inner() >> > File "locals.py", line 9, in inner >> > value = value >> > UnboundLocalError: local variable 'value' referenced before assignment >> >> > Why can't he find the variable in the second case? >> >> > Thanks, Sebastjan >> >> Python doesn't like when you read a variable that exists in an outer >> scope, then try to assign to it in this scope. >> >> (When you do "a = b", "b" is processed first. In this case, Python >> doesn't find a "value" variable in this scope, so it checks the outer >> scope, and does find it. But then when it gets to the "a = " part... >> well, I don't know, but it doesn't like it.) > > In a language like C++, the scope of a variable is determined by the > declaration. > > int x; // A > class Example > { > int x; // B > void f() > { > int x; // C > x = 42; // Which x? > } > }; > > The "x" referred to in the statement "x = 42;" refers to local > variable of Example::f. If line C were removed, then it would refer > to the member variable of class Example. And if line B were removed, > then it would refer to the global variable. > > In Python, however, there are no declarations. Therefore, it requires > another approach. What it chose was: > > (1) Explicit "self" for object attributes. > (2) A function's local variables are defined as those appearing on the > left side of an assignment. Whether the name happens to refer to a > global is NOT considered. > -- > http://mail.python.org/mailman/listinfo/python-list > From kretik at yahoo.com Thu Jun 19 00:01:36 2008 From: kretik at yahoo.com (kretik) Date: Wed, 18 Jun 2008 21:01:36 -0700 Subject: Ternary operator alternative in Ptyhon In-Reply-To: References: Message-ID: Thank you everyone. I ended up implementing the dict.get() method, which seems "cleaner", but I'll keep the (x if y else z) syntax in mind. I didn't know it existed, I guess it's what I was looking for to begin with. Thanks again! Allen wrote: > kretik wrote: >> I'm sure this is a popular one, but after Googling for a while I >> couldn't figure out how to pull this off. From gopalm at infotechsw.com Wed Jun 11 23:48:32 2008 From: gopalm at infotechsw.com (gopal mishra) Date: Thu, 12 Jun 2008 09:18:32 +0530 Subject: How to set directory in save as combo box Message-ID: <01f201c8cc3f$2f6ba990$2fc513ac@pwit.com> Hi, In 'save as' dialog of window application, I am trying to set the path in 'save in' combo box using python win32 programming. How we can set the directory in the 'save in' combo box. Thanks, Gopal -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Mon Jun 9 05:11:58 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 9 Jun 2008 02:11:58 -0700 (PDT) Subject: need help with timezone conversion (unexpected side effect of time.mktime ??) References: <8ea566b6-9562-4ee1-8c1a-5dffea553825@j22g2000hsf.googlegroups.com> <3a6e930b-9652-48c5-89d7-1d0560687a21@d45g2000hsc.googlegroups.com> <4c8fb0bb-3e92-4b1b-b5c8-ec0b86e8934e@e53g2000hsa.googlegroups.com> <28654738-beac-443a-9c3e-677c17d442ad@f63g2000hsf.googlegroups.com> Message-ID: <7b58406a-1d92-430a-968b-970f8bb7069a@d1g2000hsg.googlegroups.com> On 9 Jun, 07:40, Ivan Velev wrote: > Thanks Paul, > > I have identified the "problem" - because of daylight change this > particular timesamp was observed twice in Europe/Sofia. Here is the > GMT-to-local-time conversion: > > +------------+---------------------+---------------------+ > | gmt_stamp | gmt_time | local_time | > +------------+---------------------+---------------------+ > | 1130631000 | 2005-10-30 00:10:00 | 2005-10-30 03:10:00 | > +------------+---------------------+---------------------+ > | 1130634600 | 2005-10-30 01:10:00 | 2005-10-30 03:10:00 | > +------------+---------------------+---------------------+ > | 1130638200 | 2005-10-30 02:10:00 | 2005-10-30 04:10:00 | > +------------+---------------------+---------------------+ > | 1130641800 | 2005-10-30 03:10:00 | 2005-10-30 05:10:00 | > +------------+---------------------+---------------------+ I still don't understand why the "problematic" timestamp would affect the latter operation, though. I can see that both timestamps could be valid depending on which time zone is supposed to be in operation - have the dates for daylight saving (summer vs. winter) time changed in Bulgaria in the last few years? Maybe asking for a conversion for a date in 2004 invokes some old rules which then affect a conversion for a date in 2005, even though that would be really bad behaviour (which I don't see on this machine here). > When you do local-time-to-GMT conversion you can expect any of those > two timestamps. I missed that initially :( (I was sure that local time > has "one hour gap" and not "one hour of overlapping time") Well, it really isn't overlapping as such: you're in different zones, of course. ;-) > > and I'd recommend the datetime module for any serious work with dates and times. > > Last time when I was playing with TZ conversions, I was not able to do > anything using datetime module - it seems that one needs to define his > own set of timezones (+ all the details) to get it working ... Am I > wrong ? Can you show me how do accomplish the same conversion using > datetime module ? I think it's easiest to install one of the libraries which provides the zone data. The first one that comes to mind is python-dateutil, but I think there are others. Paul From dmitrey.kroshko at scipy.org Sat Jun 14 05:13:56 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sat, 14 Jun 2008 02:13:56 -0700 (PDT) Subject: write Python dict (mb with unicode) to a file Message-ID: hi all, what's the best way to write Python dictionary to a file? (and then read) There could be unicode field names and values encountered. Thank you in advance, D. From mccredie at gmail.com Thu Jun 12 13:28:46 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 12 Jun 2008 10:28:46 -0700 (PDT) Subject: Simple and safe evaluator References: Message-ID: <80b23a5a-8613-4232-8954-7f7e4181322e@k37g2000hsf.googlegroups.com> On Jun 11, 9:16 pm, George Sakkis wrote: > On Jun 11, 8:15 pm, bvdp wrote: > > > > > Matimus wrote: > > > > The solution I posted should work and is safe. It may not seem very > > > readable, but it is using Pythons internal parser to parse the passed > > > in string into an abstract symbol tree (rather than code). Normally > > > Python would just use the ast internally to create code. Instead I've > > > written the code to do that. By avoiding anything but simple operators > > > and literals it is guaranteed safe. > > > Just wondering ... how safe would: > > > eval(s, {"__builtins__":None}, {} ) > > > be? From my testing it seems that it parses out numbers properly (int > > and float) and does simple math like +, -, **, etc. It doesn't do > > functions like int(), sin(), etc ... but that is fine for my puposes. > > > Just playing a bit, it seems to give the same results as your code using > > ast does. I may be missing something! > > Probably you do; within a couple of minutes I came up with this: > > >>> s = """ > > ... (t for t in 42 .__class__.__base__.__subclasses__() > ... if t.__name__ == 'file').next()('/etc/passwd') > ... """>>> eval(s, {"__builtins__":None}, {} ) > > Traceback (most recent call last): > File "", line 1, in > File "", line 3, in > IOError: file() constructor not accessible in restricted mode > > Not an exploit yet but I wouldn't be surprised if there is one. Unless > you fully trust your users, an ast-based approach is your best bet. > > George You can get access to any new-style class that has been loaded. This exploit works on my machine (Windows XP). [code] # This assumes that ctypes was loaded, but keep in mind any classes # that have been loaded are potentially accessible. import ctypes s = """ ( t for t in 42 .__class__.__base__.__subclasses__() if t.__name__ == 'LibraryLoader' ).next()( ( t for t in 42 .__class__.__base__.__subclasses__() if t.__name__ == 'CDLL' ).next() ).msvcrt.system('dir') # replace 'dir' with something nasty """ eval(s, {"__builtins__":None}, {}) [/code] Matt From mccredie at gmail.com Wed Jun 11 17:30:56 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 11 Jun 2008 14:30:56 -0700 (PDT) Subject: Simple and safe evaluator References: Message-ID: <6de2cbf8-9ab0-462b-aa66-32a7895d70c9@a70g2000hsh.googlegroups.com> On Jun 11, 1:25 pm, bvdp wrote: > Is there a simple/safe expression evaluator I can use in a python > program. I just want to pass along a string in the form "1 + 44 / 3" or > perhaps "1 + (-4.3*5)" and get a numeric result. > > I can do this with eval() but I really don't want to subject my users to > the problems with that method. > > In this use I don't need python to worry about complex numbers, > variables or anything else. Just do the math on a set of values. Would > eval() with some restricted list of permitted operators do the trick? > > I'm feeling too lazy to write/debug my own parser for this :) > > Thanks, Bob. Here is something that I wrote using the _ast module. It works pretty well, and might be a good example for others wanting to experiment with the _ast module. On a related note... if anybody wants to provide feedback on this code it would be much appreciated. It involves a lot of if/elif branches, and feels ugly. Matt [code] import _ast class SafeEvalError(Exception): pass class UnsafeCode(SafeEvalError): pass # safe types: # Sequences: # list, tuple, dict, set, frozen_set* # Literals: str, unicode, int, long, complex, float def safe_eval(text): "similar to eval, but only works on literals" ast = compile(text, "", 'exec', _ast.PyCF_ONLY_AST) return _traverse(ast.body[0].value) def _traverse(ast): if isinstance(ast, _ast.List): return [_traverse(el) for el in ast.elts] elif isinstance(ast, _ast.Tuple): return tuple(_traverse(el) for el in ast.elts) elif isinstance(ast, _ast.Dict): return dict( zip( (_traverse(k) for k in ast.keys), (_traverse(v) for v in ast.values) ) ) elif isinstance(ast, _ast.Str): return ast.s elif isinstance(ast, _ast.Num): return ast.n elif isinstance(ast, _ast.Expr): return _traverse(ast.value) elif isinstance(ast, _ast.BinOp): if isinstance(ast.op, _ast.Add): return _traverse(ast.left) + _traverse(ast.right) elif isinstance(ast.op, _ast.Sub): return _traverse(ast.left) - _traverse(ast.right) elif isinstance(ast.op, _ast.Div): return _traverse(ast.left) / _traverse(ast.right) elif isinstance(ast.op, _ast.FloorDiv): return _traverse(ast.left) // _traverse(ast.right) elif isinstance(ast.op, _ast.Mod): return _traverse(ast.left) % _traverse(ast.right) elif isinstance(ast.op, _ast.Mult): return _traverse(ast.left) * _traverse(ast.right) elif isinstance(ast.op, _ast.Pow): return _traverse(ast.left) ** _traverse(ast.right) elif isinstance(ast.op, _ast.BitAnd): return _traverse(ast.left) & _traverse(ast.right) elif isinstance(ast.op, _ast.BitOr): return _traverse(ast.left) | _traverse(ast.right) elif isinstance(ast.op, _ast.BitXor): return _traverse(ast.left) ^ _traverse(ast.right) elif isinstance(ast.op, _ast.LShift): return _traverse(ast.left) << _traverse(ast.right) elif isinstance(ast.op, _ast.RShift): return _traverse(ast.left) >> _traverse(ast.right) elif isinstance(ast, _ast.BoolOp): if isinstance(ast.op, _ast.And): return all(_traverse(v) for v in ast.values) if isinstance(ast.op, _ast.Or): return any(_traverse(v) for v in ast.values) elif isinstance(ast, _ast.UnaryOp): if isinstance(ast.op, _ast.Invert): return _traverse(ast.operand) if isinstance(ast.op, _ast.USub): return -_traverse(ast.operand) if isinstance(ast.op, _ast.UAdd): return +_traverse(ast.operand) if isinstance(ast.op, _ast.Not): return not _traverse(ast.operand) raise UnsafeCode() if __name__ == "__main__": print safe_eval("[1,2,3,{'hello':1}, (1,-2,3)], 4j, 1+5j, ~1+2*3") [/code] From Russ.Paielli at gmail.com Wed Jun 4 00:45:04 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 3 Jun 2008 21:45:04 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> <873antn9il.fsf@benfinney.id.au> Message-ID: <87e962bb-a658-4240-9bbe-e848c190c451@a32g2000prf.googlegroups.com> On Jun 3, 8:50 pm, Ben Finney wrote: > alex23 writes: > > So the basic answers I'm seeing that "do just fine" are: > > > 1. Don't test private functions. > > 2. Add functionality _to_ the private functions for testing. > > 3. Change the interface for the purpose of testing. > > > All of which seem exceptionally inefficient and run counter to the > > whole purpose of unit testing. > > It seems you have a different idea of what unit testing is for from > me. > > Isn't the entire point of encapsulation to separate internal > components from the external interface? > > Why would a unit test, the whole purpose of which is to assert some > aspect of the external behaviour of the unit of code, care about how > that code unit is implemented internally? > > If changing the internal, encapsulated components of a unit causes its > external behaviour to change, that's a bug; either in the change made > (it shouldn't have altered the external behaviour), or in the unit > test asserting the wrong thing (it shouldn't be asserting anything > about internal state of the code). > > -- > \ ?Try to become not a man of success, but try rather to become | > `\ a man of value.? ?Albert Einstein | > _o__) | > Ben Finney Thank you. Let me just add that, as I said before, I think "private" data (if it were added to Python) should be accessible through some sort of "indirect" mechanism akin to the double-leading-underscore rule. Then, even if it *is* needed for unit testing, it can be accessed. As for unit testing in C++, Java, and Ada, I confess I know nothing about it, but I assume it gets done. Considering that Ada is used to manage and control fighter jets, cruise missiles, and nuclear arsenals, let's hope it gets done right. From cwitts at gmail.com Wed Jun 25 07:33:12 2008 From: cwitts at gmail.com (Chris) Date: Wed, 25 Jun 2008 04:33:12 -0700 (PDT) Subject: python -regular expression - list element References: <62e21ec1-18f3-4572-b223-1b8a5c40688c@f63g2000hsf.googlegroups.com> <87abh9pzyd.fsf@benfinney.id.au> Message-ID: <09a7f1dd-7cb8-4369-8af7-160276b71f0e@m73g2000hsh.googlegroups.com> On Jun 25, 12:32?pm, Ben Finney wrote: > antar2 writes: > > for x in list1: > > ? ?re.compile(x) > > ? ?for y in list2: > > ? ? ? ? ? ?re.compile(y) > > ? ? ? ? ? ?if x in y: > > ? ? ? ? ? ? ? ? ? ?z = re.sub(x, 'u', y) > > but this does not work > > You need to frotz the hymangirator with spangule. > > That, or show us the actual result you're seeing and how it differs > from what you expect to happen. > > -- > ?\ ? ? "I must say that I find television very educational. The minute | > ? `\ ? somebody turns it on, I go to the library and read a book." ?-- | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Groucho Marx | > Ben Finney That made me laugh :D Why not a list comprehension ? ::: list1 = ['a','o'] ::: list2 = ['star', 'day', 'work', 'hello'] ::: [l2.replace(l1,'u') for l2 in list2 for l1 in list1 if l1 in l2] ['stur', 'duy', 'wurk', 'hellu'] From fc14301589 at icqmail.com Sun Jun 1 03:24:41 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Sun, 01 Jun 2008 15:24:41 +0800 Subject: File browser in python gui References: <4841353e_1@news.tm.net.my> <48419d7c_2@news.tm.net.my> Message-ID: <48424eb9_1@news.tm.net.my> On 02:48, domenica 01 giugno 2008 TheSaint wrote: > I'm gonna back to study a little I'm facing tough time, I can't get clear by Trolltech's C++ examples. I'm a bit puzzled :), I'd like to remain with the QT widget set, but hard learning curve. Other simplified developing TK are giving different widgets, I don't expect to mix up :( -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From lepto.python at gmail.com Tue Jun 24 02:23:12 2008 From: lepto.python at gmail.com (oyster) Date: Tue, 24 Jun 2008 14:23:12 +0800 Subject: Any GUI lib wiget is capable of a WYSIWYG editor? Message-ID: <6a4f17690806232323p5f10ff22s15b65d97539eed57@mail.gmail.com> that is an html editor with text and picture, while the picture is linked to the local image file. for wxPython, the richtextcontrol save the image as en embedded object, so it is not my choice is there any other GUI lib and/or sample code to do so? thanks From straton at lampsacos.demon.co.uk Mon Jun 23 04:59:41 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Mon, 23 Jun 2008 09:59:41 +0100 Subject: binary number format ? format character %b or similar. In-Reply-To: <194cf4ed-2ca4-455b-b36e-9fb69b118c07@d77g2000hsb.googlegroups.com> References: <194cf4ed-2ca4-455b-b36e-9fb69b118c07@d77g2000hsb.googlegroups.com> Message-ID: Mensanator wrote: > On Jun 22, 4:07?pm, Ken Starks wrote: >> weheh wrote: >>> I don't know if you found this example: >>> http://www.daniweb.com/code/snippet285.html >> Thanks for that. The offerings are very similar to the >> algorithms I wrote myself. >> >> It wasn't the solution I was after,really; that's >> easy. It was whether anything had found its way into >> the standard library. > > Isn't that coming in Python 3.0? Thanks for the tip! following which, I found information at: http://docs.python.org/dev/3.0/library/string.html#formatstrings > > You could also use gmpy, which has a lot of > other bit-functionality in addition to displaying > them. > Yes, that'll be useful. Thanks again. From deets at nospam.web.de Mon Jun 9 09:34:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 09 Jun 2008 15:34:27 +0200 Subject: lists to save in a tuple References: <130e261e-1e1a-4657-b8db-8a7704fb083d@z66g2000hsc.googlegroups.com> Message-ID: <6b4psbF35e8fgU1@mid.uni-berlin.de> Nader wrote: > Hello, > > I have two lists and would save them in a tuple. > > a = [1,2,3] > b = ['a','b','c'] > > with the next statement I can do that: > > t = [(x,y), for x in a for y in b] > > This gives the next list: > > [(1,'a'),(1,'b'),(1,'c'), (2,'a'),(2,'b'),(2,'c'), (3,'a'),(3,'b'), > (3,'c')] > > But I want the next list: > > [(1,'a'),(2,'b'),(3,'c')] > > Would somebody tell me how I can solve this problem? zip(a, b) Diez From upton at virginia.edu Fri Jun 27 16:14:01 2008 From: upton at virginia.edu (Dan Upton) Date: Fri, 27 Jun 2008 16:14:01 -0400 Subject: [Employment] New TurboGears Job in Eugene, OR In-Reply-To: <486547C9.7090701@ulmcnett.com> References: <4df107ec-7193-412a-addf-ecbb4b6a3f3a@p25g2000hsf.googlegroups.com> <486547C9.7090701@ulmcnett.com> Message-ID: <5504f9ac0806271314oc8fc35ct3511fa208a872d38@mail.gmail.com> On Fri, Jun 27, 2008 at 4:04 PM, Paul McNett

    wrote: > Silas Snider wrote: >> >> Full-time academic year position >> Salary range: $2819 - $4404 per month ( $16.26 - $25.41 per hour) > >> The following knowledge, skills and experience are necessary for this >> position: >> >> Expert Python and SQL programming skills, and proficiency with >> Javascript, CSS, XHTML and web standards. Professional experience with >> open source projects, ideally using Turbogears and MySQL. Experience >> with Mac OSX Server or other server administration. Familiarity with >> version control. Skills using on-line documentation for open source >> packages. Wide knowledge of open-source software and ability to find, >> evaluate, learn and implement new open source technologies. > > They want an expert for a maximum of $25 per hour? If they find someone, > it'll be a pretty good bullshitter looking for experience. > That's often the problem with academic positions. They frequently just don't have the money for what they actually want. I used to work for a university's web office and they listed the position as requiring a CompSci degree at least 2 years experience, but the offered salary was low even for someone being hired right out of college. From johnjsal at NOSPAMgmail.com Tue Jun 17 09:39:07 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 17 Jun 2008 09:39:07 -0400 Subject: Buffer size when receiving data through a socket? References: <20080616202135.41c407de.johnjsal@NOSPAMgmail.com> Message-ID: <03985958$0$8452$c3e8da3@news.astraweb.com> "John Salerno" wrote in message news:20080616202135.41c407de.johnjsal at NOSPAMgmail.com... > from socket import * > > host = 'localhost' > port = 51567 > address = (host, port) > buffer_size = 1024 > > client_socket = socket(AF_INET, SOCK_STREAM) > client_socket.connect(address) > > while True: > data = raw_input('> ') > if not data: > break > client_socket.send(data) > data = client_socket.recv(buffer_size) > if not data: > break > print data > > client_socket.close() Also, is that second "if not data: break" statement necessary? It seems like once you get past the first if, you don't need the second one. Of course, I guses it's possible that the server could return a False value, but even still, would it make sense to break out of the loop and close the connection because of that? It runs fine without the if statement, but I'm wondering if I just haven't encountered the proper problem situation yet. From dstromberglists at gmail.com Fri Jun 13 14:24:10 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Fri, 13 Jun 2008 18:24:10 GMT Subject: How to sort very large arrays? References: Message-ID: On Fri, 13 Jun 2008 17:54:32 +0000, kj wrote: > I'm downloading some very large tables from a remote site. I want to > sort these tables in a particular way before saving them to disk. In > the past I found that the most efficient way to do this was to > piggy-back on Unix's highly optimized sort command. So, from within a > Perl script, I'd create a pipe handle through sort and then just print > the data through that handle: > > open my $out, "|$sort -t '\t' -k1,1 -k2,2 -u > $out_file" or die $!; > print $out $_ for @data; > > But that's distinctly Perlish, and I'm wondering what's the "Python Way" > to do this. > > TIA! > > kynn os.system and os.popen are much like what you'd find in C. The subprocess module is more specific to python, and is a little more complicated but more powerful. From omer at no-log.org Wed Jun 25 15:24:25 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Wed, 25 Jun 2008 21:24:25 +0200 Subject: reading from list with paths In-Reply-To: <6c1ed580-259a-4df2-b389-ecf38296a138@25g2000hsx.googlegroups.com> References: <6c1ed580-259a-4df2-b389-ecf38296a138@25g2000hsx.googlegroups.com> Message-ID: <200806252124.25967.omer@no-log.org> Le Wednesday 25 June 2008 20:59:38 antar2, vous avez ?crit?: > Hello, > > I would like to read and print files, of which the complete filepaths > are > mentioned in another textfile. In this textfile (list.txt) are for > example the following paths: > > /data/chorec/chorec-nieuw/s01/S01C001M1/S01C001M1_1LG_f01.TextGrid > /data/chorec/chorec-nieuw/s01/S01C001M1/ > S01C001M1_1LGPseudo_f01.TextGrid > /data/chorec/chorec-nieuw/s01/S01C001M1/S01C001M1_AVI1_f01.TextGrid > > I know how to open and read one file in my current directory, > but after trying to find this out my self, I give up... > > I already got one answer for this question, but it did not work > What's the problem exactly ? If you already know how to read a file you have all what you need: f_list = open('list.txt') for filename in f_list : f = open(filename) print f.read() f.close() f_list.close() If you get an error, please post the full error message with the backtrace. -- C?dric Lucantis From sarvi at cisco.com Fri Jun 20 01:26:15 2008 From: sarvi at cisco.com (Saravanan Shanmugham (sarvi)) Date: Thu, 19 Jun 2008 22:26:15 -0700 Subject: Python as a Testing Language - TTCN-3 Comparison Message-ID: Well, looks like someone did such a comparison just recently. Just FYI PDF at the link below http://www.site.uottawa.ca/~bernard/A%20comparison%20between%20ttcn-3%20 and%20python%20v%2011.pdf Comparing TTCN-3 with raw python as they have done is not fair. But even then some of the comparisons made does not seem to make good use of python constructs to be fair. It seems to me with a little bit of a well written python test framework behind the scenes the comparison wouldn't be as bad as this document shows. For example they compare a TTCN-3 structure and template to Python objects. But I am guessing for these uses a Dictionary would have been a better way of representing a TTCN-3 template or structure in python. Anyway, to me what this does point out is that the current python test frameworks(python the language) are just good enough, compared to TTCN-3. We just need a better python test framework and may be in that process we may be able to identify some python language constructs, if any, that might make it easier to build the test framework or describe test cases. Sarvi ________________________________ From: Saravanan Shanmugham (sarvi) Sent: Wednesday, June 11, 2008 1:28 PM To: 'python-list at python.org' Subject: Python as a Testing Language - TTCN-3 Comparison Hi, Is there any work being done to make Python better suited for writing test cases for any problem space. I am a huge python fan and one of the things that got me there was the simplicy and elegance its constructs that allow me to do complex programming operations in very few lines without compromising on readability. When I was looking for an efficient language for describing test cases for any problem domain, I naturally thought Python would be my best bet. (Even though Tcl is used extensively, and I have used it). But I found something called TTCN-3 which is a language designed specifcally for describing test cases. I found the following comparison of TTCN-3 with Junit and Tcl http://www.site.uottawa.ca/~bernard/Tutorial_JUnit_tcltk_ttcn-3_animated .pdf It clearly shows the elegance of the language when it comes to describing test cases. Questions: 1. Does anyone one know of a similar comparison of TTCN-3 with Python? Or does some one have an idea how it would compare if we actually did a comparison. 2. Two powerfull things that seems to make TTCN-3 suite for testing is the Template matching mechanism and the concept Alternate matching or Trees. How best do we do this in Python? Is there room for improvement language constructs that could make this simpler. Thx, Sarvi -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Tue Jun 17 07:21:20 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 17 Jun 2008 04:21:20 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <4856e80c$0$30401$9b622d9e@news.freenet.de> <2d1e9b84-3dc7-4822-9c61-73991a527c67@s50g2000hsb.googlegroups.com> <48574b41$0$30410$9b622d9e@news.freenet.de> Message-ID: <31defced-c60d-45dc-a32a-af01a2b84c89@2g2000hsn.googlegroups.com> Martin v. L.: > http://wiki.python.org/moin/TimeComplexity Thank you, I think that's not a list of guarantees, while a list of how things are now in CPython. > If so, what's the advantage of using that method over d.items[n]? I think I have lost the thread here, sorry. So I explain again what I mean. I think for this data structure it's important to keep all the normal dict operations at the same speed. If you use a C implementation vaguely similar to my pure python recipe you can perform the del in O(1) too, because pairs are joined in (double) linked list. But such data structure is O(n) to find the n-th item inserted into the sequence. Bye, bearophile From geoff.bache at jeppesen.com Wed Jun 11 16:51:29 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Wed, 11 Jun 2008 13:51:29 -0700 (PDT) Subject: Converting a simple python script to a simple windows executable References: <135a4069-8d99-4fef-b794-ac3e87ea9a25@e39g2000hsf.googlegroups.com> Message-ID: On Jun 11, 9:49?pm, jay graves wrote: > On Jun 11, 2:25 pm, geoffbache wrote: > > > Anyone have any better ideas? > > How about ExeMaker? > > http://effbot.org/zone/exemaker.htm > > I have not used it but it seems to do what you want. > > ... > Jay Thanks, this looks very promising! Will try out a bit more tomorrow but I think it should work. Regards, Geoff From alexelder at gmail.com Mon Jun 16 14:07:38 2008 From: alexelder at gmail.com (Alex Elder) Date: Mon, 16 Jun 2008 11:07:38 -0700 (PDT) Subject: String Concatenation O(n^2) (was: Re: Explaining Implementing a Binary Search Tree.) References: <3fc761710806160941q3c1a93b5p7761fbe148718585@mail.gmail.com> <20080616170916.4714.1881297769.divmod.quotient.9773@ohm> Message-ID: I found this article useful when dealing with strings in Python: http://www.skymind.com/~ocrow/python_string/ It may help squeeze some more time out of your code. 8-) Alex. From workitharder at gmail.com Mon Jun 9 01:46:25 2008 From: workitharder at gmail.com (bukzor) Date: Sun, 8 Jun 2008 22:46:25 -0700 (PDT) Subject: Newbie help (TypeError: int argument required) References: Message-ID: <98ee3f11-cd9c-412e-8c9e-9d38943484c5@z24g2000prf.googlegroups.com> On Jun 8, 11:43?am, Iain Adams wrote: > Hi, > > I am new to python. I have been having trouble using the MysqlDB. I > get an error pointing from the line > > cursor.execute("UPDATE article SET title = %s, text = %s WHERE id = > %u", (self.title, self.text, self.id)) > > Here is the error: > > ?line 56, in save > ? ? cursor.execute("UPDATE article SET title = %s, text = %s WHERE id > = %u", (self.title, self.text, self.id)) > ? File "/var/lib/python-support/python2.5/MySQLdb/cursors.py", line > 151, in execute > ? ? query = query % db.literal(args) > TypeError: int argument required > > However when I print out type(self.id) I get . > > So surely I have provided an int argument. > > Any ideas anyone?? Change your u to an s and you'll be fine. If you want a specific format on the integer, format it first and pass in the string. From cwitts at gmail.com Wed Jun 4 04:38:38 2008 From: cwitts at gmail.com (Chris) Date: Wed, 4 Jun 2008 01:38:38 -0700 (PDT) Subject: Help need with subprocess communicate References: <0312b7e9-bffe-4360-bf3a-f5b3b26d243d@l64g2000hse.googlegroups.com> <530ccda9-818e-4abe-9f82-0720e27c48fd@z72g2000hsb.googlegroups.com> <8aef95d4-065d-4afe-bed6-bb3b4aabe04e@u12g2000prd.googlegroups.com> <94CdnYdgxM4m19vVnZ2dnUVZ_qTinZ2d@earthlink.com> Message-ID: <5300f781-51db-4d84-bf62-e05c04b6aba6@l42g2000hsc.googlegroups.com> On Jun 4, 9:56?am, Dennis Lee Bieber wrote: > On Tue, 3 Jun 2008 23:48:38 -0700 (PDT), rdab... at gmail.com declaimed the > following in comp.lang.python: > > > Is there way to configure the stdout buffer size so that it flushes > > earlier.. > > Is there a way to make above mentioned piece code working? > > ? ? ? ? I believe there is a command line argument that will set Python into > an unbuffered mode... BUT, unless the spawned process/program has some > similar option, you have no control over its output. > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? ?wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ starting your application with "python -u" sets it to unbuffered binary stdout and stderr, hopefully that helps. From grflanagan at gmail.com Tue Jun 17 03:48:52 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Tue, 17 Jun 2008 09:48:52 +0200 Subject: Removing inheritance (decorator pattern ?) In-Reply-To: <200806170510.58587.maric@aristote.info> References: <439e5f62-73d2-4d13-88b5-8d7afa16da09@w7g2000hsa.googlegroups.com> <200806170510.58587.maric@aristote.info> Message-ID: Maric Michaud wrote: > Le Monday 16 June 2008 20:35:22 George Sakkis, vous avez ?crit : >> On Jun 16, 1:49 pm, Gerard flanagan wrote: [...] >>> variation of your toy code. I was thinking the Strategy pattern, >>> different classes have different initialisation strategies? But then you >>> could end up with as many Strategy classes as subclasses, I don't know. [...] >> This doesn't solve the original problem, the combinatorial explosion >> of empty subclasses. [...] > > Yes, and it fails to implement the strategy pattern as well... which would > have solved the problem as it is intended exactly for this purpose. > Ok, better would have been 'my made-up strategy pattern, any resemblance to other patterns, either living or dead, is purely coincidental' :-) Non-canonically, G. From jonas at MIT.EDU Thu Jun 12 17:21:31 2008 From: jonas at MIT.EDU (Eric Jonas) Date: Thu, 12 Jun 2008 17:21:31 -0400 Subject: cPickle asymptotic performance? In-Reply-To: <8763se4h1s.fsf@mulj.homelinux.net> References: <8763se4h1s.fsf@mulj.homelinux.net> Message-ID: <1213305691.8320.28.camel@convolution> On Thu, 2008-06-12 at 20:57 +0200, Hrvoje Niksic wrote: > Eric Jonas writes: > > > I've done some benchmarking while attempting to serialize my (large) > > graph data structure with cPickle; I'm seeing superlinear performance > > (plotting it seems to suggest n^2 where n is the number of nodes of my > > graph), in the duration of the pickle.dump calls and I can't quite > > figure out why. > > Try gc.disable() before loading the pickle, and gc.enable() after. > > > Is cPickle's behavior known to be O(n^2)? > > No, but the garbage collector's sometimes is. Wow, that totally fixed it -- we went from 1200 seconds to 60 seconds. I'm somewhat shocked -- is the occasionally-abysmal behavior of the GC documented anywhere? ...Eric From gandalf at shopzeus.com Mon Jun 9 05:10:59 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 09 Jun 2008 11:10:59 +0200 Subject: [Fwd: Re: How to make one program connect to more than one TCP?] In-Reply-To: <1174.10.191.1.101.1212967299.squirrel@webmail.its.ac.id> References: <1361.222.124.226.218.1212587123.squirrel@webmail.its.ac.id> <4846A609.6080809@shopzeus.com> <1174.10.191.1.101.1212967299.squirrel@webmail.its.ac.id> Message-ID: <484CF3A3.1030306@shopzeus.com> agus at cs.its.ac.id wrote: > i want to make one program that the steps like this: > 1. download email from email account, for example: agus at yahoo.com, saved > in a file, for example: downloadedEmail.txt > Can be done via the standard imaplib module. No need to use twisted. > 2. parsing the downloadedEmail.txt, get the sender, subject and the > message.if there is attachmet/s, not be taken. > Save it as an eml file. Use the standard email.Parser module for extracting headers. > 3. posting the downloadedEmail.txt that has been parsed into nntp server. > 4. open nntp client for example 'thunderbird' to acces your nntp server. > I have no clue about it. > i attach my programs to u.. > it is very important for me as final project in my study class, too > difficult for me....thanks for your help!!! > Well, I can send you some examples that show how to download and parse emails from imap server. I have never used nntp before so.... Some examples are attached, and also a code fragment: IMAPDate.py - to convert between IMAP and datetime.date imaputils.py - to show how to connect to IMAP server and list folders on it (you need to create your own local.py file...), also shows how to append a new message to a folder on the imap server. code_fragment.py - to show how to search for messages on the server and download them as pure data string, it is NOT a complete program! And finally, here is how you parse and email: import email.Parser email_data = file('test2.eml','rb').read() parser = email.Parser.Parser() Then you need to example "parser" and its methods. Anyway, it is your homework, I don't think that I'm going to give more help unless you have a specific question. :-) Best, Laszlo -------------- next part -------------- A non-text attachment was scrubbed... Name: IMAPDate.py Type: text/x-python Size: 1372 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: imaputils.py Type: text/x-python Size: 1285 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: code_fragment.py Type: text/x-python Size: 4805 bytes Desc: not available URL: From maric at aristote.info Fri Jun 13 12:55:24 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 13 Jun 2008 18:55:24 +0200 Subject: Summing a 2D list In-Reply-To: <873anhtjlr.fsf@ara.blue-cable.net> References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <873anhtjlr.fsf@ara.blue-cable.net> Message-ID: <200806131855.24859.maric@aristote.info> Hello, Le Friday 13 June 2008 17:55:44 Karsten Heymann, vous avez ?crit?: > Maric Michaud writes: > > So, writing C in python, which has dictionnary as builtin type, > > should be considered "more elegant" ? > > IMO that's a bit harsh. > harsh ? Sorry, I'm not sure to understand. > > You are comparing apples with lemons, there is no such a difference > > between list index access and dictionnary key access in Python. > > [...] > > > If you know in advance the number and names of users, what prevent > > you to initialize completelly the target dictionnary ? > > > > The following code compare the same algorithm, once with list and > > the second time with dict : > > [...] > > > The result is pretty close now : > > > > maric at redflag1 17:04:36:~$ ./test.py > > with list 1.40726399422 > > with dict 1.63094091415 > > > > So why use list where the obvious and natural data structure is a > > dictionnary ? > > I'd never argue that using a dictionary is the obvious and natural > data structure for this case. But is it the best? Honestly, as your > very nice example shows, we have two solutions that are equally fast, > equally complex to code and equally robust, but one needs Yes, but my example take ordered integer for keys (users' names) which they should not be in a real case, so retrieving the result is by way easier (and faster) with a dictionnary. > approximately the double amount of memory compared to the other. I don't see how you came to this conclusion. Are you sure the extra list take twice more memory than the extra dictionary ? > So, as much as i like dictionaries, what's the gain you get from using it > in this corner case? It's the very purpose of it's usage, store and retrieve data by key. Cheers, -- _____________ Maric Michaud From george.sakkis at gmail.com Thu Jun 5 09:41:32 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 5 Jun 2008 06:41:32 -0700 (PDT) Subject: Tuples part 2 References: <295215b0-83b4-46a7-ac94-ed94be57ccad@27g2000hsf.googlegroups.com> Message-ID: <0d3f0f2b-f345-44f9-adb3-6fbed603cce9@d1g2000hsg.googlegroups.com> On Jun 5, 9:26 am, "victor.hera... at gmail.com" wrote: > On Jun 5, 1:37 am, bearophileH... at lycos.com wrote: > > > > > victor.hera... at gmail.com: > > > Do you mean something like this? (notice the many formatting > > differences, use a formatting similar to this one in your code) > > > coords = [] > > > for i in xrange(1, 5): > > for j in xrange(1, 5): > > for k in xrange(1, 2): > > coords.append( (i, j, k) ) > > > coords *= 10 > > print coords > > > Bye, > > bearophile > > Hi, > > the result i would like is similar to a set of n tuples: tuple_1, > tuple_2,...,tuple_n. I use h in order to enumerate the tuples and > i,j,k would be the coordinates. >From the pseudocode you wrote at first, tuple_1, tuple_2, ..., tuple_n would be all equal. Is this intentional, and if so, what's the purpose ? George From apardon at forel.vub.ac.be Mon Jun 2 05:00:08 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 2 Jun 2008 09:00:08 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> Message-ID: On 2008-05-24, Ben Finney wrote: > Sh4wn writes: > >> first, python is one of my fav languages, and i'll definitely keep >> developing with it. But, there's 1 one thing what I -really- miss: >> data hiding. I know member vars are private when you prefix them with >> 2 underscores, but I hate prefixing my vars, I'd rather add a keyword >> before it. > > From whom are you trying to hide your attributes? > > In Python, the philosophy "we're all consenting adults here" applies. > You shouldn't pretend to know, at the time you write it, all the uses > to which your code will be put. Barriers such as enforced "private" > attributes will only cause resentment when people, despite your > anticipations, *need* to access them and are then forced to hack their > way around them. I don't find this argument very compelling. You can't anticipate all functionality people would like your function to have. Acces to information in a (private) attribute is just one of those possible functionallities. People will resent you if you don't provide functionality they think fits logically in your package. > If you want the users of your code to know that an attribute should > not be used as a public API for the code, use the convention of naming > the attribute with a single leading underscore. This is a string > signal that the attribute is part of the implementation, not the > interface. The reader is then on notice that they should not rely on > that attribute; but they are not *prohibited* from using it if > necessary to their ends. But they will resent you just as much if you decide to rewrite your module in such a way that the attribute is no longer present or is used now in a slightly different way, so that it break code. -- Antoon Pardon From none at this.time Fri Jun 6 13:51:14 2008 From: none at this.time (The Pythonista) Date: Fri, 06 Jun 2008 13:51:14 -0400 Subject: Assigning to __class__ : bad form? Message-ID: <61f33$48497912$7402@news.teranews.com> I've been wondering for a while about whether assigning to __class__ is bad form or not. Specifically, I mean doing so when some other method of implementing the functionality you're after is available (i.e. using an adapter, or something like the strategy pattern). To give an example and a non-example of what I'm talking about, consider the following recipes from the online Python Cookbook: Ring Buffer: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68429 In this case, I think the assignment to __class__ just obfuscates things, and the example would be better coded as a single class. On the other hand, Fast copy of an object having a slow __init__ : http:// aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66507 This seems like a reasonable use case for assigning to __class__ (except that it's already implemented in the 'new' module, but, read the Martelli- bot's comments near the end of the recipe). I consider this a reasonable use case for assigning to __class__, because, short of the 'new' module, I don't see any other way to accomplish it. So, what is the opinion of the broader Python community? Is code that assigns to __class__ just clever trickiness to be avoided, or is it sometimes a good thing? -- code.py: A blog about life, the universe, and Python http://pythonista.wordpress.com ** Posted from http://www.teranews.com ** From nospam at nospam.com Sun Jun 1 09:28:27 2008 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 01 Jun 2008 15:28:27 +0200 Subject: Good grid + calendar, etc.? References: <9c80b15f-791e-4933-984b-fd8bf0bafef1@m36g2000hse.googlegroups.com> Message-ID: On Sun, 1 Jun 2008 06:00:03 -0700 (PDT), Mike Driscoll wrote: >I recall that there is an advanced calendar widget that's been made by >one of the regulars on the wxPython list, but it's not a part of the >official distribution at this time. You'll have to ask about calendar >widgets and such there though. The impression I get, is that those extra widgets (besides the usual edit, listbox, etc.) aren't really developped/maintained, which is a problem when comitting for applications that will have to be developped for a few years. For instance, is there a calendar in wxPython that has this look and feel, and is under active development? http://www.devexpress.com/Products/VCL/ExScheduler/ >The grid can be quite advanced. Did you look at the wxPython demo? Or >Dabo? Yes, but although the basic wigets are just fine, wxGrid looks a bit like the basic TStringGrid in Delphi, ie. it's pretty basic so that several vendors came up with enhanced alternatives. But maybe I haven't played with it long enough. www.asiplease.net/computing/delphi/images/string_grid_demo_popstars.gif It lacks sorting capability, merging cells with the same content, etc. From bronger at physik.rwth-aachen.de Sun Jun 15 11:47:31 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 15 Jun 2008 17:47:31 +0200 Subject: Making wxPython a standard module? References: <6bidd7F3bg8usU1@mid.uni-berlin.de> <87fxrfx0h0.fsf@physik.rwth-aachen.de> <87wskrvhwd.fsf@physik.rwth-aachen.de> <87skvfvd0b.fsf@physik.rwth-aachen.de> <3L-dnZvBzrFZh8jVnZ2dnUVZ_uudnZ2d@posted.visi> Message-ID: <87d4miwvho.fsf@physik.rwth-aachen.de> Hall?chen! Grant Edwards writes: > On 2008-06-14, Torsten Bronger wrote: > >>> You're saying that having the user or-together a bunch of >>> bitmasks and pass the result as an integer is a common way for >>> Python functions/object allow the user to turn optional features >>> on and off? >> >> "Common" doesn't matter. > > Yes it does. "Common in Python" is what defines "Pythonic". Then I have your definition of it. I don't think that it leads to good design, though. In case of doubt, choose what's common in Python, but other characteristics must have higher priority. >> Legibility and practicality matter. > > [...] With a little practice and care, functional programming in > prefix-notation (a-la Scheme) can both practical and legible, Not legible for a Python-only programmer like me, and I am the target audience. > but it still isn't Pythonic. > > [...] > >>> They are sources of bugs. >> >> I don't think so. What do you mean? > > Because certain flags are only to be used in certain contexts, but > there's no way to force (or even to indicate) that usage to the > user. Related flags are orthogonal so that the library can well detect an error. Okay, you can pass a *very* wrong parameter, like telling wxPython that this event should have an OK button, but I find this problem case artificial. > [...] > >> I used to use C++ before I switched to Python, but I don't see >> any C++ in wxPython. > > The whole "flags" thing with a truckload of globally defined > integer constants competing for a single namespace is pure C/C++. > Were wxWidgets written in Python, I guarantee that wouldn't be the > way it was done. Well, of course it would look heavily different with a different history but this applies to every piece of software. As I said, I used flags in my own package, designed with Python 2.4. And I consider myself a purist. So, there are things that are bad or sub-optimal, but flags are a matter of personal preference. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From badmuthahubbard at gmail.com Sun Jun 8 02:28:14 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Sun, 8 Jun 2008 09:28:14 +0300 Subject: More than one element of list changing when only one should be In-Reply-To: <8200bab70806070753y69652e74v73a280cfacb23af2@mail.gmail.com> References: <8200bab70806070753y69652e74v73a280cfacb23af2@mail.gmail.com> Message-ID: <8200bab70806072328m733e0303hbae1e15ef8428370@mail.gmail.com> I solved this problem. I still don't understand why, but it seems Python was appending a reference to the first element at the end of the list, rather than copying the data. I used something like: "self.regionlist.append(list(self.regionlist[self.hregion])" and now it works fine, i.e., altering the appended list member doesn't change the copied one. -Chuckk On Sat, Jun 7, 2008 at 5:53 PM, Chuckk Hubbard wrote: > Hello. > This program is clunky, I know; I'm not a programmer, but I need to > use this program, so I'm writing it. > The problem: > I have a cursor following the mouse that shows frequency ratios of > potential notes in relation to 1/1 (something like Middle C). At any > time, the user may hit "t" to move 1/1 to wherever the cursor is. > There is also the option to use many regions, so that some of the > notes in the score, in region 0, for instance, can have 1/1 as their > base, and others, in region 1 for instance, could have perhaps 3/2 as > their base. > > The program starts out with 2 existing regions, region 0 = 1/1, and > region 1 = 3/2. If the user hits r+NUM, the cursor switches to region > NUM. If NUM is longer than the list of regions (self.regionlist), a > new region is appended with the same base as the current one, and the > cursor goes to that region. > > SO, if you start this program, then: > 1) move the cursor around a little; > 2) hit 'r' and '1' at the same time - now you are in region 1; > 3) hit 'r' and '0', now region 0; > 4) hit 'r' and '2', now a new region 2 is created with the same > parameters as region 0, and self.regionlist is appended with the new > info - now you're in region 2; > 5) move the mouse until the fraction reads anything other than 1/1; > 6) hit 't' to transpose the current region by that fraction; > > You can see by the output in the text window that self.regionlist[0] > AND self.regionlist[2] have been updated. Only [2] should have been > changed. > > 7) hit 'r' and '0', and see that region 0 has now changed its base to > match region 2. > > I hope someone is curious enough to get through this and help me. I > tried extracting the function in question into its own mini-file and > the problem didn't happen. I can't think of any reason these lines: > > self.regionlist[self.hregion][0] = self.curnum > self.regionlist[self.hregion][1] = self.curden > self.regionlist[self.hregion][3] = self.octave11 = self.yadj > > should change self.regionlist[0] AND self.regionlist[2] in the same > call, but they do. Also, if I add more regions in series, they all > update each other. > > Thanks for your time. > > -Chuckk > > -- > http://www.badmuthahubbard.com > -- http://www.badmuthahubbard.com From johnjsal at NOSPAMgmail.com Wed Jun 18 09:59:27 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 18 Jun 2008 09:59:27 -0400 Subject: One more socket programming question References: <4858772c$0$5015$607ed4bc@cv.net> Message-ID: <4859145f$0$28604$c3e8da3@news.astraweb.com> "Tim Roberts" wrote in message news:sjdh541b2u7m789i8ef6rmple5smklbt9i at 4ax.com... > John Salerno wrote: >> >>I'm now experimenting with the SocketServer class. Originally I >>subclassed the StreamRequestHandler to make my own custom handler, but a >>result of this seems to be that the client socket closes after it has >>been used, instead of staying open. > > Right. "handle" is not called for one REQUEST at a time, it's called for > one CONNECTION at a time. If you need a connection to be persistent, then > your handle() function needs to sit in a loop making recv calls until you > detect that the conversation is complete. Ah, so I need to rewrite my handle method. I was thinking that the specialized setup() and/or finish() calls from StreamRequestHandler were the reason that the connection was closed after one use (which is why I tried BaseRequestHandler instead). Thanks. From sturlamolden at yahoo.no Thu Jun 5 06:15:21 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 5 Jun 2008 03:15:21 -0700 (PDT) Subject: multiprocessing module (PEP 371) References: <877a5774-d3cc-49d3-bb64-5cab8505a419@m3g2000hsc.googlegroups.com> Message-ID: <1c867dff-a909-4b9e-99ec-b096ddfbd83d@c58g2000hsc.googlegroups.com> On Jun 5, 11:02 am, pataphor wrote: > This is probably not very central to the main intention of your post, > but I see a terminology problem coming up here. It is possible for > python objects to share a reference to some other object. This has > nothing to do with threads or processes, although it can be used as a > *mechanism* for threads and processes to share data. It is complicated in the case of processes, because the object must be kept in shared memory. The complicating factor is that the base address of the memory mapping, which is not guaranteed to be the same in the virtual address space of different processes. From Lie.1296 at gmail.com Sun Jun 15 13:22:13 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 15 Jun 2008 10:22:13 -0700 (PDT) Subject: Creating a TCP/IP connection on already-networked computers References: <4853f269$0$11615$607ed4bc@cv.net> Message-ID: <73ea41f5-2723-48d4-8a52-9ece0260ba5c@u12g2000prd.googlegroups.com> On Jun 14, 11:31?pm, John Salerno wrote: > Let me see if this question even makes sense...I'm reading Core Python > Programming and I jumped ahead to the more specific topics like network > programming. I plan to follow along with the example in that chapter and > create a socket connection between my desktop and laptop. > > However, these two computers are already connected on my home network > (using the Windows Network Setup Wizard), so I was wondering if this > will have any effect on what I might try to do with Python. In other > words, if the program I write actually works and allows the two > computers to speak to each other, will that be a result purely of the > program, or will it have anything to do with the fact that they are > already on a home network together? (i.e. there's another variable in play?) > > Thanks. The Windows Network Wizard is a poor abstraction to set up layer 3 and 4 (the TCP/IP and lower) and layer 5 (the file sharing). You don't need to run this wizard if you've set up your TCP/IP and lower correctly manually (which, according to me, is easier than using the wizard). In a normal situation, you shouldn't need to worry about setting up the layer 3 and 4, you can assume that this two already set up. Some problem lies when connecting two computers through internet, such as you may have to use external IP address or set up port forwarding on the server-side. This is due to the use of 192.168.xxx.xxx as inside-LAN IP address instead of letting each device on the whole world has their own IP address. From schickb at gmail.com Wed Jun 25 03:11:54 2008 From: schickb at gmail.com (schickb) Date: Wed, 25 Jun 2008 00:11:54 -0700 (PDT) Subject: Sequence iterators with __index__ References: <433c6aca-745e-4c9f-b182-d76291449829@m73g2000hsh.googlegroups.com> <119bb268-2064-4128-8006-f5564f0c62f8@q27g2000prf.googlegroups.com> Message-ID: <996af953-f2a5-4dc5-ac9d-f98067cacbf7@l42g2000hsc.googlegroups.com> On Jun 24, 5:46 pm, Terry Reedy wrote: > > Wanting to slice while iterating is a *very* specialized usage. I disagree because iterators mark positions, which for sequences are just offsets. And slicing is all about offsets. Here is a quote from the already implemented PEP 357: "Currently integers and long integers play a special role in slicing in that they are the only objects allowed in slice syntax. In other words, if X is an object implementing the sequence protocol, then X[obj1:obj2] is only valid if obj1 and obj2 are both integers or long integers. There is no way for obj1 and obj2 to tell Python that they could be reasonably used as indexes into a sequence. This is an unnecessary limitation." But this isn't just about slicing. I'd like sequence iterators to be usable as simple indexes as well; like a[it] (which __index__ would also provide). > In any case: > A. If the iterator uses in incrementing index to iterate, you want access. > B. Using an iterator as an integer will strike most people as > conceptually bizarre; it will never be accepted. It's not meant to be used as an integer. It's meant to be used as a position in the sequence, which iterators already are. The fact that the position is represented as an integer is not that important (except to python). I'll grant you that it is conceptually strange that you could use an iterator on one sequence as an index into another. > C. Doing so is unnecessary since the internal index can just as easily > be exposed as an integer attribute called 'index' or, more generally, > 'count'. > a[it.count:] looks *much* better. > D. You can easily add .index or .count to any iterator you write. The > iterator protocol is a minimum rather than maximum specification. Following that line of reasoning, the __index__ special method shouldn't really exist at all. Your arguments would suggest that NumPy shouldn't use __index__ either because: a[ushort.index] "looks *much* better". > E. You can easily wrap any iterable/iterator in an iterator class that > provides .count for *any* iteration process. Sure, and that is why I mentioned this in my original post. But the idea is to avoid redundant code and data in the case of sequences, and make it a standard feature. > F. Even this should be unnecessary for most usages. Built-in function > enumerate(iterable) generates count,item pairs in much the same manner: I am not aware of a way to get the current position out of an enumerate object without advancing it (or creating a custom wrapper). If the special __index__ method was added it might be interesting ;) But iterators are already a clean and abstract position marker, and for sequences it seems surprising to me that they can't really be used as such. -Brad From Lie.1296 at gmail.com Thu Jun 19 06:12:25 2008 From: Lie.1296 at gmail.com (Lie) Date: Thu, 19 Jun 2008 03:12:25 -0700 (PDT) Subject: how to send a "Multiline" mail with smtplib? References: Message-ID: <72daf82c-1921-4aba-b41a-3bf13d3f0e51@s21g2000prm.googlegroups.com> On Jun 19, 4:02?pm, Justin Ezequiel wrote: > perhaps change html > > body=MIMEText('hello,\r\n > ok',_subtype='html',_charset='windows-1255') > > to plain > > body=MIMEText('hello,\r\n > ok',_subtype='plain',_charset='windows-1255') If that was the case, and you needed a line break in html-mode, use
    or

    tags. From larry at portcommodore.com Sun Jun 29 11:16:20 2008 From: larry at portcommodore.com (larry at portcommodore.com) Date: Sun, 29 Jun 2008 08:16:20 -0700 (PDT) Subject: help debugging noob code - converting binary data to images... References: <56955a42-155c-4c37-9bf6-5a99cadb5c79@l42g2000hsc.googlegroups.com> Message-ID: <8a9b4e80-45cf-4145-85c0-94d2f2a04aa4@j22g2000hsf.googlegroups.com> Wonderful, thank you! Will try them out this evening. The image module syntax looks more like what I was expecting than TKinter. All the online drawing examples I found yesterday used TKinter; image was only shown to manipulate pre-made images. Larry From python at rcn.com Mon Jun 16 13:25:21 2008 From: python at rcn.com (Raymond Hettinger) Date: Mon, 16 Jun 2008 10:25:21 -0700 (PDT) Subject: 'string'.strip(chars)-like function that removes from the middle? References: Message-ID: On Jun 16, 10:09?am, Peter Otten <__pete... at web.de> wrote: > Ethan Furman wrote: > > The strip() method of strings works from both ends towards the middle. > > Is there a simple, built-in way to remove several characters from a > > string no matter their location? (besides .replace() ;) > >>> identity = "".join(map(chr, range(256))) > >>> 'www.example.com'.translate(identity, 'cmowz.') > > 'exaple' And in Py2.6, you'll be able to simplify further: >>> 'abcde'.translate(None, 'bd') 'ace' Raymond From pavlovevidence at gmail.com Sun Jun 1 10:05:23 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 1 Jun 2008 07:05:23 -0700 (PDT) Subject: python's setuptools (eggs) vs ruby's gems survey/discussion References: <71ff8ebc-96e6-40f8-bcf2-43a0a2bd4135@w7g2000hsa.googlegroups.com> Message-ID: <78f01f07-c300-48f7-b5a0-8f3fa7e75e1d@z72g2000hsb.googlegroups.com> On Jun 1, 4:47 am, Alia Khouri wrote: > Can we open up the discussion here about how to improve setuptools > which has become the de facto standard for distributing / installing > python software. I've been playing around with ruby's gems which seems > to be more more mature and usable. > > From my perspective, the relative immaturity of setuptools and its > simultaneous widespread use is a clear python weakness and can make > python less easy to absorb than it should be. > > A few questions (please add more) so far are: Oh boy. > (1) Should setuptools be standard? Shamelessly speaking as someone who does no wish to enter this particular niche of Python: I would hope the Python community can do better. > (2) What bugs you most about the current featureset? 1. setuptools will download and install dependencies on the user's behalf, without asking, by default. It can be disabled, but I think it's extremely rude: it should ask by default. 2. One cannot simply import modules from packages that use entry_points: you have to go through package resources. Very annoying. 3. Tools such as py2exe don't work with packages that use entry_points except with some hand tweaks (at least as of the last time I tried). One might suggest that py2exe should learn how to include setuptools models, but I don't think people who write tools like py2exe ought to be burdened with it. py2exe was possible because the import mechanism was theretofore so straightforward. FWIW, I've abandoned usage of a package that used entry points because of this issue. > (3) Which features do you need the most (list in order of need)? Not that my needs are all important, but: 1. Works. 2. Ability to install to unusual locations (BIG) 3. Packages can be installed separately by hand if the user so desires (copying to site directory, hand editing if necessary) 4. Ability to easily specify compiler options when rebuilding extension modules. 5. Handles data files reasonably > (4) Shouldn't we just port gems to python? Fine with me, some new blood would be useful here. > (5) What's the best community process to improve setuptools? Have the BDFL declare that it's the official Python package manager. Of course, I hope if it ever comes to that the BDFL will pronounce something else to be the official Python package manager, preferrably something that isn't based on distutils. > Hope this discussion can be constructive. In any case, I do appreciate > the effort that went into creating setuptools (Thanks Phillip J. > Eby :-). It's existence is clearly better than otherwise. I don't agree. It's probably better than otherwise for enterprise applications, which is the environment for which it was designed. For instance, entry points and dependency bookkeeping are useful in such environments, since there are policies to ensure consistent and reasonable usage. For open source, mom-and-pop operations, and other smaller projects, I think it adds a whole lot of complexity over what otherwise is a simple thing. Carl Banks From mensanator at aol.com Sat Jun 7 21:03:09 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 7 Jun 2008 18:03:09 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> <484ad07b$0$25721$607ed4bc@cv.net> Message-ID: <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> On Jun 7, 6:43?pm, "Terry Reedy" wrote: > "John Salerno" wrote in message > > news:484ad07b$0$25721$607ed4bc at cv.net...| Mensanator wrote: > > | > | > Surely enumerate() wasn't added to Python with no intention of > | > ever being used. > | > | I see your reasons for preferring enumerate over zip, but I'm wondering > | if using enumerate this way isn't a little hackish or artificial. > > It seems to be a difference of personal preference. ?I see no reason to > write a for loop (statement or expression) when a simple usage of basic > builtins does the same. ?Mensanator apparently does. ? *sigh* I never said a for..loop was preferable. What I said was the answer to "Can I do this with a list comprehension?" I never said you shouldn't use the builtins. What I DID say was that how the builtins actually work should be understood and it APPEARED that the OP didn't understand that. Maybe he understood that all along but his example betrayed no evidence of that understanding. > So it goes. So I was trying to help the guy out. So sue me. > > Because zip stops when the first iterator is exhausted, the original zip > with range can be pretty well future proofed with a high stop value. > > zip(range(9,2000000000), iterable) Oh, dear. You didn't actually try this, did you? > > Of course, a non-1 step can be added to the range. I would hope so, otherwise you're going to have a problem creating a list with two billion integers. You might want to try xrange() in your production code. > > tjr From socyl at 987jk.com.invalid Fri Jun 13 13:54:32 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 13 Jun 2008 17:54:32 +0000 (UTC) Subject: How to sort very large arrays? Message-ID: I'm downloading some very large tables from a remote site. I want to sort these tables in a particular way before saving them to disk. In the past I found that the most efficient way to do this was to piggy-back on Unix's highly optimized sort command. So, from within a Perl script, I'd create a pipe handle through sort and then just print the data through that handle: open my $out, "|$sort -t '\t' -k1,1 -k2,2 -u > $out_file" or die $!; print $out $_ for @data; But that's distinctly Perlish, and I'm wondering what's the "Python Way" to do this. TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From sjmachin at lexicon.net Sun Jun 8 19:31:48 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 8 Jun 2008 16:31:48 -0700 (PDT) Subject: Q re documentation Python style References: Message-ID: <71beb475-7602-462a-af9f-f22c79ee2347@x19g2000prg.googlegroups.com> On Jun 9, 7:17 am, kj wrote: [snip] > For example, I want to document a function that > takes a dictionary as argument, and this dictionary is expected to > have 5 keys. (When the number of mandatory arguments gets above > 4, I find that it's too difficult to remember their order, so I > resort to using a dictionary as the single argument.) Like myfunc({'strarg': 'foo', 'intarg': 42}) ?? So the start of this function would look something like this: def myfunc(dictarg): strarg = dictarg['strarg'] intarg = dictarg['intarg'] # the real work starts now Why not use keyword args? >>> def func(a1, a2): ... print 'a1=%r a2=%r' % (a1, a2) ... >>> func('foo', 42) a1='foo' a2=42 >>> func(a1='foo', a2=42) a1='foo' a2=42 >>> func(a2=42, a1='foo') a1='foo' a2=42 >>> Have you read this section in the Python tutorial: "4.7 More on Defining Functions" (http://docs.python.org/tut/ node6.html#SECTION006700000000000000000) HTH, John From gert.cuykens at gmail.com Sat Jun 28 18:38:27 2008 From: gert.cuykens at gmail.com (gert) Date: Sat, 28 Jun 2008 15:38:27 -0700 (PDT) Subject: pxssh submit su commands = very very slow Message-ID: <39f89067-8ee6-470a-92ce-77b46a344f37@34g2000hsf.googlegroups.com> This works but after the su command you have to wait like 2 minutes before each command gets executed ? What did i do wrong ? import pxssh try: s = pxssh.pxssh() s.login ('127.0.0.1', 'gert', '123') s.sendline ('uptime') s.prompt() print s.before s.sendline ('ls -l') s.prompt() print s.before s.sendline ('df') s.prompt() print s.before s.sendline ('su') s.expect('Password:') s.sendline ('123') s.prompt() print s.before s.sendline ('df') s.prompt() print s.before s.sendline ('exit') s.logout() except pxssh.ExceptionPxssh, e: print "pxssh failed on login." print str(e) From tjreedy at udel.edu Wed Jun 25 19:26:00 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 25 Jun 2008 19:26:00 -0400 Subject: Newbie question about tuples and list comprehensions In-Reply-To: References: Message-ID: idiolect wrote: > Hi all - Sorry to plague you with another newbie question from a > lurker. Hopefully, this will be simple. > > I have a list full of RGB pixel values read from an image. I want to > test each RGB band value per pixel, and set it to something else if it > meets or falls below a certain threshold - i.e., a Red value of 0 > would be changed to 50. > > I've built my list by using a Python Image Library statement akin to > the following: > > data = list(image.getdata()) > > Which produces a very long list that looks like [(0,150,175), > (50,175,225),...]. I'm trying to figure out a fast and pythonic way > to perform my operation. The closest I've come so far to a succinct > statement is a list comprehension along the syntax of: Why are you trying to do this with a list comprehension? Learn the basics first. Perhaps you have read too many of the recent threads presenting diverting challenges for bored experienced programmers. Some of these were definitely not Pythonic code for real use. First question: do you really want to create a new 'very long list' or modify list 'data' in place. Let's assume the latter. for i,tup in enumerate(data): data[i] = replace(tup) where replace(tup) is an expression or function that produces a tuple meeting your criteria. Simplest is (max(tup[0],Rthresh), max(tup[1],Gthresh), max(tup[2],Bthresh)). If nearly all your pixels are ok, add the following before the assignment so you only make replacements when actually needed: if tup[0] < Rthresh or tup[1] < Gthresh or tup[2] < Bthresh: Terry Jan Reedy From kyrie at uh.cu Sun Jun 8 12:00:15 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Sun, 08 Jun 2008 12:00:15 -0400 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> Message-ID: <1212940815.484c020fa98ef@comuh.uh.cu> I don't know about Erlang (though I'd think it's behaviour sould be similar to prolog), but at least in Prolog, yes, _ and _ are different variables. The whole idea of "_" is that it is a placeholder that can bind to anything, but will be immediately discarded. It's just syntactic sugar so you don't have to create new names for things you don't care about, which could be a problem in prolog (once bound, cannot be bound again on the same branch) or erlang (once bound, bound forever). I just tried on erlang: f(0,_) -> 1+_; f(X,_) -> X*f(X-1,_). produces an error: ./t.erl:4: variable '_' is unbound ./t.erl:5: variable '_' is unbound (referring to the right side uses of the _ symbol) while the definition: f(0,Y)->1+Y; f(X,Y)->X*f(X-1,Y). produces a [very weird, just for testing purposes, don't use it at home] version of 'factorial'. So, you understood well. As I haven't been following this thread, I won't go offtopic talking about functional languages. But yes, on functional (and declarative?) languages, it makes a lot of sense to have a 'symbol' that represents a new variable any time you use it. Cheers, -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie Quoting Roy Smith : > In article , > Mark Wooding wrote: > > > * Prolog and Erlang distinguish atoms from variables by the case of > > the first letter; also `_' is magical and is equivalent to a new > > variable name every time you use it. > > Can you explain that in more detail? A literal reading of what you wrote > would mean that if you did (assuming this is even legal syntax): > > _ = 1; > y = _; > > the _'s are different variables, which is absurd enough to make me believe > I just misunderstood you. > -- > http://mail.python.org/mailman/listinfo/python-list > From jaywgraves at gmail.com Mon Jun 2 17:56:08 2008 From: jaywgraves at gmail.com (jay graves) Date: Mon, 2 Jun 2008 14:56:08 -0700 (PDT) Subject: Cast list of objects to list of strings References: <48546eb1-11f3-4a88-b1ac-97bd485a1823@k30g2000hse.googlegroups.com> Message-ID: <63d3d50d-0e9b-4682-b523-c2ff7d336c6a@m44g2000hsc.googlegroups.com> On Jun 2, 4:02 pm, Larry Bates wrote: > I think what you want is: > def write_err(*args): > from sys import stderr > stderr.write("\n".join([str(o) for o in args])) Slight nitpick. If you are using version >= 2.4 you could use a generator expression instead of a list comprehension to avoid building and throwing away a list. "\n".join(str(o) for o in args) http://www.python.org/dev/peps/pep-0289/ Very unlikely to yield a material time difference in this case but cleaner IMO. ... Jay Graves From michele.simionato at gmail.com Tue Jun 3 09:25:17 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 3 Jun 2008 06:25:17 -0700 (PDT) Subject: Webpy vs Django? References: <7db4dfb2-1e50-4a89-a47b-7356119b2741@r66g2000hsg.googlegroups.com> Message-ID: <33f44e6c-d08b-45f6-9512-2fd3d3ddac9b@m36g2000hse.googlegroups.com> On Jun 3, 3:14?pm, circularf... at yahoo.se wrote: > > what do you think of webpy for big projects that need performance? A better question would be: do you need features which are in Django and not in webpy? If webpy suits your needs and you are happy with it, keep it. OTOH, if you need more than webpy, consider a bigger framework (there are many of them, Django is not your only choice). I would expect the performance of all Python framework to be roughly the same, the difference is in the learning curve and in the features, not in the performance. Michele Simionato From likunarmstrong at gmail.com Mon Jun 23 03:48:25 2008 From: likunarmstrong at gmail.com (windstorm) Date: Mon, 23 Jun 2008 00:48:25 -0700 (PDT) Subject: Learning Python in a group References: Message-ID: <1820ab03-882c-4629-843c-ea9d6175d253@x19g2000prg.googlegroups.com> On Jun 23, 1:12?pm, Mensanator wrote: > On Jun 22, 5:43?am, "Jonathan Roberts" > wrote: > > > > > Hi all, > > > I'm looking to learn Python (as my first programming language) and I'm > > pretty sure I'd be more successful doing this with a group of other > > people. > > > I've currently got one other person to learn with me, and we plan to > > work remotely over the net using tools such as IM/VoiP/Gobby/WIkis > > etc. We'd still like a few others to work with us, with a group of > > about 5 or 6 being seen as ideal. We'd also like to find somebody to > > act as a mentor/guide who might be happy to meet with us once every > > couple of weeks to help keep us moving in the right direction and find > > solutions to problems when we get really stuck! > > > Wondered if there was anybody here who might be interested in working > > with us in either of these roles? We both have differing goals, but > > ultimately we'd just like to get more familiar so that we can provide > > some simple fixes to packages we maintain/scratch a few itches of our > > own. Any one is welcome, no matter what your own aim :) > > > Would love to hear feedback, especially from anyone who's interested > > in working with us... > > Have you considered creating your own Google Group? > > > > > Best, > > > Jon > > Yeah, set up your personal Google group, post the address here and ask people who want to join in sounds like a better idea rather than asking here. Considering time-zone, I don't know how you guys communicate with each other "real-time". So "post in group, get discuss and reply" may make more sense. From wuwei23 at gmail.com Thu Jun 5 12:43:14 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 5 Jun 2008 09:43:14 -0700 (PDT) Subject: Import text file References: <832784cb-08b0-46df-bf78-84051e27d498@k13g2000hse.googlegroups.com> Message-ID: <260fc576-11f1-473c-bc4f-a63873a21719@s21g2000prm.googlegroups.com> On Jun 6, 2:28 am, Franck Y wrote: > I have a text file where there is > > xxx=value > yyy=value > zzz=value > etc... > > I would like use the from myfile import xxxx > > Since it has not the extension py how can i read it ? > I know the way to do it with the open file but i think this one is > easier... I don't think you'll be able to use import unless you change the file extension to .py If you're in control of the text file and are confident it will only contain name=value pairs, try: execfile('your_file.txt') From gagsl-py2 at yahoo.com.ar Wed Jun 18 03:02:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Jun 2008 04:02:04 -0300 Subject: Buffer size when receiving data through a socket? References: <20080616202135.41c407de.johnjsal@NOSPAMgmail.com> <4857f4f7$0$28588$c3e8da3@news.astraweb.com> Message-ID: En Tue, 17 Jun 2008 14:32:44 -0300, John Salerno escribi?: > "Gabriel Genellina" wrote in message > news:mailman.547.1213684963.1044.python-list at python.org... >> Note that most of the time you want to use the sendall() method, because >> send() doesn't guarantee that all the data was actually sent. >> > > If I use sendall(), am I still recv'ing data with a given buffer size? What > if I send more data than the buffer size. Is my code as written not prepared > to handle that case? It seems like I might need to continue receiving data > until there is no more to receive (in a loop?)...is that right? send and recv are separate calls (they occur usually in different processes, even in different computers). Buffer sizes are separate too. It is posible to send 5K at once from one side, and require three recv calls on the other side to read it completely. On the other hand, if you try to read from a blocking socket (the default state) when no data is available, the read call will block (and the whole program freezes) until some data is received. There are several alternatives to avoid this, and surely they're explained in detail in a later chapter in your book... -- Gabriel Genellina From hniksic at xemacs.org Thu Jun 12 04:19:16 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 12 Jun 2008 10:19:16 +0200 Subject: ClassName.attribute vs self.__class__.attribute References: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> Message-ID: <87abhrdq0r.fsf@mulj.homelinux.net> Mike Orr writes: > There's a very good reason to use self.__class__: it makes it > possible to subclass your class. This really depends on the usage. In the OP's use case, he wanted the subclasses to share the same lock object defined in the superclass (because of synchronization), so it would have been wrong to use self.__class__ *because* of subclassing. Also note that for new-style classes, self.__class__ can be spelled as type(self), since there is no distinction between classes and types. > It's a little annoying that if you want to print a class's name in > some unknown object, you have to use obj.__class__.__name__ if it's > an instance, and obj.__name__ if it's a class. I sometimes wish > classes had a .__class__ attribute that's the class itself, but I > can see how that would cause its own confusion (and recursion). They do, the metaclass. :-) From sri_annauni at yahoo.co.in Thu Jun 19 03:58:41 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Thu, 19 Jun 2008 13:28:41 +0530 (IST) Subject: python socket programming Message-ID: <12884.73075.qm@web7914.mail.in.yahoo.com> HI, I want?to know the different kind of exceptions may occur in client-server? socket communication and the way to handle those scenarios. 1. What does the?server do when a socket error occurs at any point: accepting a connection, sending data to a client, receiving?data from a client, waiting for a?client to shut down. ?? 2. What does the?client do when a socket error occurs at any point: connecting to the server, receiving data, sending?data. If anyone knows answer for this qns, Can?you please explain me briefly about it?? Thanks, Srini Unlimited freedom, unlimited storage. Get it now, on http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/ From george.sakkis at gmail.com Thu Jun 19 20:31:50 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 19 Jun 2008 17:31:50 -0700 (PDT) Subject: Null pattern Message-ID: I'd like to extend the Null pattern from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205 to handle special methods (e.g. Null[3], del Null['key'], Null+1) but it's not always clear how to do it while keeping the behavior consistent and intuitive. For example, consider the container methods __len__, __iter__ and __contains__. The obvious choice for a null container is an empty one. When taking __getitem__ into account though, the behaviour looks inconsistent: >>> Null[3] Null >>> len(Null) 0 Another group of methods is rich comparisons: Should Null > x be allowed and if so, what it should return ? Then again, perhaps Null is an inherently domain-specific notion and there are no general answers to such questions, in which case it doesn't make sense trying to define an all-purpose Null object. George From M8R-yfto6h at mailinator.com Tue Jun 3 03:19:11 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Tue, 3 Jun 2008 00:19:11 -0700 Subject: =?GB2312?B?UmU6IHB5dGh0b24gtffTwyBzbyC5ss/tv+Kyu8Tc16q7u7LOyv3A4NDN?= References: Message-ID: "windwiny" wrote in message news:c2600a0a-6ff4-4e3d-bfa6-2edf7869c60d at a9g2000prl.googlegroups.com... > ???python ? ctypes, ?????? ubuntu 8.04, Python 2.5.2 > (r252:60911, > May 7 2008, 15:19:09) , gcc (GCC) 4.2.3 (Ubuntu 4.2.3-2ubuntu7) > ?????? so ??? > --------------------- > #include > double myfd(double x) { return x * 2;} > float myff(float x) { return x * 3;} > int myfi(int x) { return x * 4 ;} > --------------------- > ? gcc -shared a.c -o liba.so ?????? liba.so , > ??? c ???????????????????? > ?????python ?? > --------------------- > # coding:utf-8 > import ctypes as dll > p = dll.cdll.LoadLibrary("./liba.so") p.myfd.argtypes = [dll.c_double] p.myfd.restype = dll.c_double p.myff.argtypes = [dll.c_float] p.myff.restype = dll.c_float > print p.myfi(8) # ?32,?? > try: > print p.myfd(0.3) # ?? > except: > print "except myfd()" > try: > print p.myff(0.4) # ?? > except: > print "except myff()" > --------------------- > ????? ctypes.ArgumentError: argument 1: 'exceptions.TypeError'>: > Don't know how to convert parameter 1 > > ??????? --Mark ???) From gagsl-py2 at yahoo.com.ar Tue Jun 17 20:26:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 17 Jun 2008 21:26:00 -0300 Subject: Does '!=' equivelent to 'is not' References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> <20080617120941.GE7349@dragontoe.org> Message-ID: En Tue, 17 Jun 2008 09:09:41 -0300, Derek Martin escribi?: > On Tue, Jun 17, 2008 at 04:33:03AM -0300, Gabriel Genellina wrote: >> > Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)' >> > and 'not(id(a) == id(b))' >> >> No. > > Sure it is... he said "similar"... not identical. They are not the > same, but they are similar. 'equality' and 'identity' are similar too, so the whole answer would make no sense in that case. You can't explain identity based on things that aren't identical. A fine grained question for a fine grained difference requires a fine grained answer. > Saying a flat "no" alone, without qualifying your statement is > generally interpreted as rude in English... It's kind of like how you > talk to children when they're too young to understand the explanation. > Yucky. I didn't meant to be rude at all - and I apologize to Mr. Lie. The explanation for such strong "No" was in the paragraph below it (the idea was to say: "No to this, yes to that") -- Gabriel Genellina From jazle at nospam.log.web.id Mon Jun 16 07:11:24 2008 From: jazle at nospam.log.web.id (Jaimy Azle) Date: Mon, 16 Jun 2008 18:11:24 +0700 Subject: Python GC does not work as it should be References: Message-ID: Jean-Paul Calderone wrote: > > A system exception? What's that? C doesn't have exceptions. > How could I determine it? I dont know GCC implementation, and others, but C on MSVC does have it. My application were not written in C, an exception raised was something like "access violation at address xxxx on module python25.dll", and MSVC debugger shows collecting state were not reset (1), that is why GC would never happen. Salam, -Jaimy. From gh at ghaering.de Wed Jun 11 07:38:07 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 11 Jun 2008 13:38:07 +0200 Subject: Python regex question In-Reply-To: References: Message-ID: Tim van der Leeuw wrote: > Hi, > > I'm trying to create a regular expression for matching some particular > XML strings. I want to extract the contents of a particular XML tag, > only if it follows one tag, but not follows another tag. Complicating > this, is that there can be any number of other tags in between. [...] Sounds like this would be easier to implement using Python's SAX API. Here's a short example that does something similar to what you want to achieve: import xml.sax test_str = """ """ class MyHandler(xml.sax.handler.ContentHandler): def __init__(self): xml.sax.handler.ContentHandler.__init__(self) self.ignore_next = False def startElement(self, name, attrs): if name == "ignore": self.ignore_next = True return elif name == "foo": if not self.ignore_next: # handle the element you're interested in here print "MY ELEMENT", name, "with", dict(attrs) self.ignore_next = False xml.sax.parseString(test_str, MyHandler()) In this case, this looks much clearer and easier to understand to me than regular expressions. -- Gerhard From tjreedy at udel.edu Mon Jun 16 20:13:19 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 16 Jun 2008 20:13:19 -0400 Subject: 'string'.strip(chars)-like function that removes from the middle? In-Reply-To: <200806161839.13647.omer@no-log.org> References: <48569B9E.6030206@admailinc.com> <200806161839.13647.omer@no-log.org> Message-ID: C?dric Lucantis wrote: > I don't see any string method to do that >>> 'abcde'.translate(str.maketrans('','','bcd')) 'ae' I do not claim this to be better than all the other methods, but this pair can also translate while deleting, which others cannot. From thomasmallen at gmail.com Tue Jun 3 14:44:20 2008 From: thomasmallen at gmail.com (tmallen) Date: Tue, 3 Jun 2008 11:44:20 -0700 (PDT) Subject: Picking apart strings Message-ID: <7e5b2c51-a1a0-45aa-9b53-547482747292@x41g2000hsb.googlegroups.com> Is there a way to pick apart this text without resorting to regular expressions? p { color: black; } p -> element color -> property black -> value From rw.segaar at xs4all.nl Sat Jun 14 15:27:19 2008 From: rw.segaar at xs4all.nl (Robert) Date: Sat, 14 Jun 2008 21:27:19 +0200 Subject: Configuration files Message-ID: <485419f0$0$5958$e4fe514c@dreader16.news.xs4all.nl> What is the most Pythonic way to maintain a configuration file? Are there any libraries mimicking registry / ini file writing that many windows programming languages/environments offer? Robert From fuzzyman at gmail.com Mon Jun 9 16:52:25 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 9 Jun 2008 13:52:25 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <6e6df35e-e641-44d9-9f56-c0732306eec2@q27g2000prf.googlegroups.com> Message-ID: On Jun 9, 9:20?pm, Rhamphoryncus wrote: > On Jun 9, 5:33 am, Antoon Pardon wrote: > > > > > On 2008-06-07, Rhamphoryncus wrote: > > > > On Jun 6, 12:44 pm, The Pythonista wrote: > > >> It's always been my understanding that you can't forcibly kill a thread > > >> in Python (at least not in a portable way). ?The best you can do is > > >> politely ask it to die, IIRC. > > > > Inherently, the best you can do in most languages is ask them politely > > > to die. ?Otherwise you'll leave locks and various other datastructures > > > in an inconvenient state, which is too complex to handle correctly. > > > The exception is certain functional languages, which aren't capable of > > > having threads and complex state in the same sense. > > > Well it would of course depend on what is considered asking politely? > > > If one thread could cause an exception being thrown in an other thread, > > would this be considered a polite way to ask? Would it be considered > > an acceptable way? > > The exception must not be raised until a point explicitly designed as > safe is hit. ?Otherwise, any function that manipulates data you'll > still use will potentially be buggered. ?Consider sys.stdout: codecs, > buffering, lots to go wrong. Java and .NET both have ways of killing threads. They both work by raising a 'ThreadAbort' (or similar) exception in the target thread. In early implementations they both suffered from a similar problem. You could protect locks (etc) by having a finally block that would release all resources as needed - but what happens if the thread abort exception is raised *inside* the finally block? Java responded by deprecating thread aborting. .NET responded by ensuring that a thread abort exception would never be raised inside a finally block - if that happened the exception would only be raised once the code has left the finally block. Aborting threads in .NET can be extremely useful. Politely asking a thread to die is no good if the task the thread is executing is extremely coarse grained - it may not be able to respond to the request for some time. If your code is structured correctly (performing a long running background calculation for example) then you may *know* that you can kill it without problems, but Python has no native API to do this. Michael Foord http://www.ironpythoninaction.com/ From jeffrey at fro.man Thu Jun 26 11:42:46 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 26 Jun 2008 08:42:46 -0700 Subject: automatically import modules upon interpreter invocation References: Message-ID: Daniel Fetchinson wrote: > Is there a way of making python execute the above whenever it starts > up so that I don't have to type it all the time? Create a script containing these statements, and specify its location with the PYTHONSTARTUP environment variable. Your script will run whenever python starts. Jeffrey From circularfunc at yahoo.se Fri Jun 27 22:58:40 2008 From: circularfunc at yahoo.se (defn noob) Date: Fri, 27 Jun 2008 19:58:40 -0700 (PDT) Subject: Pygame, how to show window without loop? no loop=popupand close... References: <8ecb6375-356a-4e73-be21-18ffe0f5c4f2@r66g2000hsg.googlegroups.com> Message-ID: right. im an idiot anyway. i can just draw the lines before entering the loop, problem solved... From kyosohma at gmail.com Sun Jun 1 09:00:03 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sun, 1 Jun 2008 06:00:03 -0700 (PDT) Subject: Good grid + calendar, etc.? References: Message-ID: <9c80b15f-791e-4933-984b-fd8bf0bafef1@m36g2000hse.googlegroups.com> On Jun 1, 6:59?am, Gilles Ganault wrote: > Hello > > ? ? ? ? Since Python is such a productive language, I'd really like to be > able to use it to write GUI apps for Windows, but business apps > require rich widgets like (DB)grids, calendars, etc. > > The ones available in wxWidgets looked a bit too basic compared to > what's available for eg. Delphi or .Net, and don't seem to be under > active development (lots of "1.0", "Last updated 2005", etc.) > > For instance, here's wxGrid and DevExpress' grid for Delphi:http://www.simpol.com/guiimages/wxgrid.jpghttp://community.devexpress.com/blogs/thinking/PrintingXtraPivotGridF... > > Is it hopeless, or did I overlook things? Are ?there other solutions I > should look at (FLTK, etc.)? For those of you writing business apps in > Python for Windows, how do things go as far as GUI widgets are > concerned? > > Thank you. The wxPython GUI is updated much more often than the Tkinter toolkit. I recall that there is an advanced calendar widget that's been made by one of the regulars on the wxPython list, but it's not a part of the official distribution at this time. You'll have to ask about calendar widgets and such there though. The grid can be quite advanced. Did you look at the wxPython demo? Or Dabo? Mike From victor.herasme at gmail.com Thu Jun 5 09:26:08 2008 From: victor.herasme at gmail.com (victor.herasme at gmail.com) Date: Thu, 5 Jun 2008 06:26:08 -0700 (PDT) Subject: Tuples part 2 References: <295215b0-83b4-46a7-ac94-ed94be57ccad@27g2000hsf.googlegroups.com> Message-ID: On Jun 5, 1:37 am, bearophileH... at lycos.com wrote: > victor.hera... at gmail.com: > > Do you mean something like this? (notice the many formatting > differences, use a formatting similar to this one in your code) > > coords = [] > > for i in xrange(1, 5): > for j in xrange(1, 5): > for k in xrange(1, 2): > coords.append( (i, j, k) ) > > coords *= 10 > print coords > > Bye, > bearophile Hi, the result i would like is similar to a set of n tuples: tuple_1, tuple_2,...,tuple_n. I use h in order to enumerate the tuples and i,j,k would be the coordinates. Maybe something like: tuple_1=((a,b,c),..,(n,n,n)) . . . tuple_n=((d,e,f),..,(n,n,n)) I hope u can help me with that. Victor From eliben at gmail.com Sat Jun 28 04:37:10 2008 From: eliben at gmail.com (eliben) Date: Sat, 28 Jun 2008 01:37:10 -0700 (PDT) Subject: problem compiling extensions with mingw References: <4973972a-e510-49b1-86bf-4ee4294842cd@m44g2000hsc.googlegroups.com> <73f6d268-252e-4de8-9839-4bab4c256d62@k13g2000hse.googlegroups.com> Message-ID: <43089036-0701-4311-a128-786921c2a47a@i76g2000hsf.googlegroups.com> On Jun 28, 8:20 am, John Machin wrote: > On Jun 28, 3:41 pm, eliben wrote: > > > > > On Jun 27, 3:10 pm, eliben wrote: > > > > Hello, > > > I'm trying to compile the minimal example fromhttp://en.wikibooks.org/wiki/Python_Programming/Extending_with_Cwith > > > MinGW (latest version) and Python 2.5 (latest ActiveState binary > > > install). When running the setup file, the following happens: > > > > running build > > > running build_ext > > > building 'hello' extension > > > writing build\temp.win32-2.5\Release\hello.def > > > d:\mingw\bin\gcc.exe -mno-cygwin -shared -s build > > > \temp.win32-2.5\Release\hellomo > > > dule.o build\temp.win32-2.5\Release\hello.def -LC:\Python25\libs -LC: > > > \Python25\P > > > Cbuild -lpython25 -lmsvcr71 -o build\lib.win32-2.5\hello.pyd > > > build\temp.win32-2.5\Release\hellomodule.o:hellomodule.c:(.text+0x3e): > > > undefined > > > reference to `_imp___Py_NoneStruct' > > > build\temp.win32-2.5\Release\hellomodule.o:hellomodule.c:(.text+0x46): > > > undefined > > > reference to `_imp___Py_NoneStruct' > > > collect2: ld returned 1 exit status > > > error: command 'gcc' failed with exit status 1 > > > > What's more, compiling the same extension with Visual Studio 2005 > > > (without using distutils) works fine, the extension is loaded and ran > > > successfully from Python. Any ideas about this error ? > > > > Eli > > > Problem solved:http://eli.thegreenplace.net/2008/06/28/compiling-python-extensions-w... > > libpython2?.a is now *supplied* with the official CPython distribution > fromwww.python.org. > I'm using ActiveState's distribution, because I was told that it comes with more precompiled win32 goodies out of the box. > The procedure that you followed is described in the manual:http://docs.python.org/inst/tweak-flags.html#SECTION00062200000000000... > Thanks, I didn't notice it :-) Eli From stef.mientki at gmail.com Mon Jun 30 15:05:10 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 30 Jun 2008 21:05:10 +0200 Subject: list extension ? In-Reply-To: <4868b0ba$0$17063$426a34cc@news.free.fr> References: <4868b0ba$0$17063$426a34cc@news.free.fr> Message-ID: <48692E66.4080406@gmail.com> thanks guys, > >> def __init__ ( self, value = [] ) : > > Gotcha : default argument values are eval'd only once. Also, it would > make more sense IMHO to follow the parent's class initializer's > behaviour: > > def __init__(self, *args) > >> list.__init__ ( self, value ) > > list.__init__(self, *args) > that's even better, except the call must be list.__init__ ( self, args ) cheers, Stef From ptmcg at austin.rr.com Wed Jun 11 20:25:51 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 11 Jun 2008 17:25:51 -0700 (PDT) Subject: Simple and safe evaluator References: Message-ID: On Jun 11, 3:25?pm, bvdp wrote: > Is there a simple/safe expression evaluator I can use in a python > program. I just want to pass along a string in the form "1 + 44 / 3" or > perhaps "1 + (-4.3*5)" and get a numeric result. > > I can do this with eval() but I really don't want to subject my users to > the problems with that method. > > In this use I don't need python to worry about complex numbers, > variables or anything else. Just do the math on a set of values. Would > eval() with some restricted list of permitted operators do the trick? > > I'm feeling too lazy to write/debug my own parser for this :) > > Thanks, Bob. This example ships with pyparsing, and can be extended to support built-in functions: http://pyparsing.wikispaces.com/space/showimage/fourFn.py. -- Paul From johnjsal at gmailNOSPAM.com Sat Jun 14 21:39:15 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sat, 14 Jun 2008 21:39:15 -0400 Subject: Creating a TCP/IP connection on already-networked computers In-Reply-To: References: <4853f269$0$11615$607ed4bc@cv.net> <4854123f$0$5017$607ed4bc@cv.net> <485413d0$0$4997$607ed4bc@cv.net> <485425b2$0$11631$607ed4bc@cv.net> Message-ID: <485472c9$0$11612$607ed4bc@cv.net> Dennis Lee Bieber wrote: > Is there any possibility you are confusing a Windows Workgroup or > Domain in this... (Assuming anyone still runs such) Or other Windows > convenience features to automatically detect computers in a local area > network and display them in "network neighborhood". What I have is a desktop PC connected via ethernet cable to my cable modem. I also use a router and my laptop uses a wireless connection. This alone, of course, doesn't connect the computers, AFAIK. It's just an internet connection. What I did next was go to My Network Places > Set up a home or small office network, and follow the wizard through the steps that would allow me to share files and folders between the two computers. It's possible I'm using the wrong terminology when I say this is a "home network," because all it is is the two computers being able to access each other's hard drive. From subhabrata.iisc at hotmail.com Fri Jun 27 03:23:17 2008 From: subhabrata.iisc at hotmail.com (subhabrata.iisc at hotmail.com) Date: Fri, 27 Jun 2008 00:23:17 -0700 (PDT) Subject: Question on time module References: <2c7d4ffa-496d-4a0b-8c14-628decbfd4ae@a9g2000prl.googlegroups.com> Message-ID: <389efb92-9710-46ff-bfab-a2fb525a3b5b@z24g2000prf.googlegroups.com> This problem is solved with time.gmtime subhabrata.i... at hotmail.com wrote: > Dear Members of the group, > I have one function > def sum1(n): > a1=5 > a2=6 > a3=a1+a2 > a4=a3+8 > print "The First sum is" > print a3 > print "The Second sum is" > print a4 > > Now, I want to do it in a way, a4 is calculated after a given time > interval of a3 -this is easy but if I want to check after how much > time a4 is calculated from a3 how can I do? > If any one can help it. > Best Regards, > Subhabrata. From gherron at islandtraining.com Thu Jun 5 03:41:08 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 05 Jun 2008 00:41:08 -0700 Subject: os.path.walk -- Can You Limit Directories Returned? In-Reply-To: <65971e97-09eb-4295-a090-517341a86065@e53g2000hsa.googlegroups.com> References: <65971e97-09eb-4295-a090-517341a86065@e53g2000hsa.googlegroups.com> Message-ID: <48479894.8060205@islandtraining.com> Jeff Nyman wrote: > Greetings all. > > I did some searching on this but I can't seem to find a specific > solution. I have code like this: > > ========================================= > def walker1(arg, dirname, names): > DC_List.append((dirname,'')) > > os.path.walk('\\\\vcdcflx006\\Flex\\Sites', walker1, 0) > ========================================= > > The Sites\ directory is set up like this: > > Sites\ > Baltimore > Birmingham > .... > > And so forth. Each of the city directories has directories under it as > well. The problem is that my code grabs every single directory that is > under the various city directories when what I really want it to do is > just grab the directories that are under Sites\ and that's it. I don't > want it to recurse down into the sub-directories of the cities. > > Is there a way to do this? Or is os.path.walk not by best choice here? > Yes. But first, use the more modern iterator os.walk instead of the older function calling os.path.walk. Then in either case (or at least for the os.walk -- I'm a little rusty on the older os.path.walk) you can modify in-place the subdirectory listing that was passed to you, thereby controlling which subdirectories the walk follows. Here's some examples: for path, dirs, files in os.walk(root): if 'etc' in dirs: dirs.remove('etc') # Skip any directory named 'etc' if path == 'whatever': del dirs[:] # Clearing dirs means recurse into NO subdirectory of path ... process the files of directory path... Gary Herron > Any help and/or advice would be appreciated. > > - Jeff > -- > http://mail.python.org/mailman/listinfo/python-list > From goldnery at gmail.com Tue Jun 17 12:45:36 2008 From: goldnery at gmail.com (Gandalf) Date: Tue, 17 Jun 2008 09:45:36 -0700 (PDT) Subject: text alignment References: <39d1c620-9923-46e7-999d-ed86c8b465ff@34g2000hsh.googlegroups.com> Message-ID: On Jun 17, 6:43?pm, Gandalf wrote: > Hi every one. What is the similar python WX style property for CSS > text-align? > > I need this item text to start from the right direction: > > aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60)) > ? ? ? ? aaa.LoadPage('../../aa.html') > > Thanks! *right to the left direction... And I'm using pythin 2.5 on XP (I forget to mention...) From haraldarminmassa at gmail.com Tue Jun 10 16:36:47 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Tue, 10 Jun 2008 13:36:47 -0700 (PDT) Subject: Instructions on how to build py2exe 0.6.8 (or an installer would be nice, too!) References: <5426baaf-2ba6-41b0-a0ec-1070429b5195@x35g2000hsb.googlegroups.com> Message-ID: <5eddd91e-e3c5-4bd6-8aa6-77223b7cdf82@a70g2000hsh.googlegroups.com> Evan, > I hear this problem is fixed in 0.6.8, but unfortunately there's no > standalone installer for py2exe 0.6.8 - the most recent version that Maybe you can solve your problem via updating the build_exe.py after installing py2exe 0.6.6 So: a) use the 0.6.6 installer b) update the build_exe.py from 0.6.8 Possible? Best wishes, Harald From rossgk at gmail.com Thu Jun 5 11:42:44 2008 From: rossgk at gmail.com (RossGK) Date: Thu, 5 Jun 2008 08:42:44 -0700 (PDT) Subject: mod_python installer fails Message-ID: <9c92c071-cbc4-402d-9184-be9f28679dc0@x35g2000hsb.googlegroups.com> I've been running python 2.5 for a while on WinXP, working fine. I code and compile in PyDev/Eclipse. I wanted to start playing with Django, but when I go to install mod_python for Apache 2.2 I get the error: python version 2.5 required, which was not found in the registry from the installer: mod_python-3.3.1.win32-py2.5-Apache2.2.exe I've confirmed that I'm running python25, apache2.2. I thought maybe I could point to my python, but the next screen that comes up with blank locating fields takes the cursor but does not allow any text input. Does anyone know the solution to this one? Thanks Ross. From pfreixes at gmail.com Thu Jun 19 17:31:23 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Thu, 19 Jun 2008 23:31:23 +0200 Subject: [Python-Dev] C API for gc.enable() and gc.disable() In-Reply-To: References: Message-ID: <207312b70806191431g2f52af9bg53299e1e6b9ec909@mail.gmail.com> Sorry for my ignorance, gc it's garbage collector ? On Thu, Jun 19, 2008 at 11:23 PM, Alexandre Vassalotti < alexandre at peadrop.com> wrote: > On Sun, Jun 1, 2008 at 12:28 AM, Adam Olsen wrote: > > On Sat, May 31, 2008 at 10:11 PM, Alexandre Vassalotti > > wrote: > >> Would anyone mind if I did add a public C API for gc.disable() and > >> gc.enable()? I would like to use it as an optimization for the pickle > >> module (I found out that I get a good 2x speedup just by disabling the > >> GC while loading large pickles). Of course, I could simply import the > >> gc module and call the functions there, but that seems overkill to me. > >> I included the patch below for review. > > > > I'd rather see it fixed. It behaves quadratically if you load enough > > to trigger full collection a few times. > > > > Do you have any idea how this behavior could be fixed? I am not a GC > expert, but I could try to fix this. > > -- Alexandre > _______________________________________________ > Python-Dev mailing list > Python-Dev at python.org > http://mail.python.org/mailman/listinfo/python-dev > Unsubscribe: > http://mail.python.org/mailman/options/python-dev/pfreixes%40gmail.com > -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From jarausch at igpm.rwth-aachen.de Thu Jun 19 06:07:54 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Thu, 19 Jun 2008 12:07:54 +0200 Subject: Python-3.0b1 build fails on Linux : _gestalt Message-ID: <6bupftF3d2d0kU1@mid.dfncis.de> Hi, trying to build Python-3.0b1 on my Gentoo Linux box fails with Failed to find the necessary bits to build these modules: _gestalt Looking at setup.py it seems that module '_gestalt' is only needed on Darwin but my build on Linux fails nevertheless. Thanks for any hints, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From Lie.1296 at gmail.com Thu Jun 19 11:15:39 2008 From: Lie.1296 at gmail.com (Lie) Date: Thu, 19 Jun 2008 08:15:39 -0700 (PDT) Subject: Simple Python class questions References: Message-ID: <8549940b-e909-4bc6-b9a1-ea7d14284785@z16g2000prn.googlegroups.com> On Jun 19, 7:21?pm, Ulrich Eckhardt wrote: > John Dann wrote: > > Let's say I define the class in a module called comms.py. The class > > isn't really going to inherit from any other class (except presumably > > in the most primitive base-class sense, which is presumably automatic > > and implicit in using the class keyword). Let's call the class > > serial_link. So in comms.py I have: > > > class serial_link: > > ? ? def __init__(self): > > ? ? ? ? Try > > ? ? ? ? ? ? Import serial # the pyserial library > > Stop, this can't work. Other than VB, Python actually is case sensitive, so > you must write 'try' and not 'Try' and also 'import' and not 'Import'. > Further, many (all?) statements that cause an indention are usually > terminated with a colon, so like with 'class ..:' and 'def ..:' you also > must use 'try:' and not just 'try'. Fix all these and try again, I guess > this will already help a lot. > > One more thing: you are abusing exceptions. Typically, in such a short > program you only have one try-except pair in the main entry function and > all other code only throws the exceptions. In particular the __init__ > function of a class should always signal errors using exceptions. However, > this is not a strict yes/no question but rather a stylistic one. > > Uli > > -- > Sator Laser GmbH > Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 I think it's not that hard to see that it's just a pseudo code From cwitts at gmail.com Tue Jun 10 02:47:14 2008 From: cwitts at gmail.com (Chris) Date: Mon, 9 Jun 2008 23:47:14 -0700 (PDT) Subject: How to find the first space? References: <7a91cc8f-2e93-46e9-8360-a01da9170187@m44g2000hsc.googlegroups.com> Message-ID: On Jun 9, 5:02?pm, Johny wrote: > How can I find the first space using regex? > > For example I have text > Text=' This is a sample ' > > The last space I can remove by > Text=re.sub(r"\s(?!\w)",'',Text) > > but I do not know how to remove the first space. > Can anyone help? > > Thanks > L. If it's leading spaces you're worried about you can use the .lstrip() method, if you want to find the first space you can use .index(' ') to get the position of it and do with what you want. From connect2shashi at gmail.com Thu Jun 26 06:48:20 2008 From: connect2shashi at gmail.com (ShashiGowda) Date: Thu, 26 Jun 2008 03:48:20 -0700 (PDT) Subject: Urllib(1/2) how to open multiple client sockets? Message-ID: Hey there i made a script to download all images from a web site but it runs damn slow though I have a lot of bandwidth waiting to be used please tell me a way to use urllib to open many connections to the server to download many pics simultaneously.... Any off question suggestions are also ok... From asmodai at in-nomine.org Thu Jun 19 08:10:06 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 19 Jun 2008 14:10:06 +0200 Subject: Extending Python with C: Cannot find MPI library In-Reply-To: References: Message-ID: <20080619121006.GJ97799@nexus.in-nomine.org> -On [20080619 13:53], Spectrum (spectrumdt at gmail.com) wrote: > ImportError: /big/School/Cluster/Opgave03/ctest.so: undefined >symbol: ompi_mpi_comm_world > [ore at localhost Opgave03]$ > > Can anyone suggest anything? Can I get MPI to work in Python? Sounds like a typical case of not specifying any -L and/or -l options. In this case the ctest.so module has an undefined reference to the symbol ompi_mpi_comm_world and cannot resolve it. So either it was not linked properly or the loader cannot find the required library. Apply nm -D and ldd to the .so and see what ails. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B Under this standard shalt thou conquer... From kirk at daycos.com Tue Jun 17 11:14:45 2008 From: kirk at daycos.com (Kirk Strauser) Date: Tue, 17 Jun 2008 10:14:45 -0500 Subject: Pattern Matching Over Python Lists References: <21a9c996-75ff-4f7c-b7e9-c94247f65674@c58g2000hsc.googlegroups.com> Message-ID: <87ej6w6ql6.fsf@internal.daycos.com> At 2008-06-17T05:55:52Z, Chris writes: > Is anyone aware of any prior work done with searching or matching a > pattern over nested Python lists? I have this problem where I have a > list like: > > [1, 2, [1, 2, [1, 7], 9, 9], 10] > > and I'd like to search for the pattern [1, 2, ANY] so that is returns: > > [1, 2, [1, 2, [6, 7], 9, 9], 10] > [1, 2, [6, 7], 9, 9] Hint: recursion. Your general algorithm will be something like: def compare(list, function): if function(list): print list for item in list: if item is a list: compare(item, function) def check(list): if list starts with [1, 2] and length of the list > 2: return True else: return False -- Kirk Strauser The Day Companies From cwitts at gmail.com Mon Jun 2 17:40:25 2008 From: cwitts at gmail.com (Chris) Date: Mon, 2 Jun 2008 14:40:25 -0700 (PDT) Subject: Formatting Output References: <6e94b4dc-5920-447e-9971-96ec6a48b9ce@c58g2000hsc.googlegroups.com> <6ea2e85a-d00c-4228-98be-431205fceb7b@34g2000hsf.googlegroups.com> <650fca09-a6de-4d81-a19b-687c63ad429b@l64g2000hse.googlegroups.com> Message-ID: On Jun 2, 11:34?pm, Chris wrote: > On Jun 2, 9:43?pm, Doug Morse wrote: > > > > > On Mon, 2 Jun 2008 12:42:12 -0700 (PDT), Mensanator wrote: > > > ?On Jun 2, 3:38?am, Chris wrote: > > > > On Jun 2, 9:34?am, "victor.hera... at gmail.com" > > > > > wrote: > > > > > Hi, > > > > > > i am building a little script and i want to output a series of columns > > > > > more or less like this: > > > > > > 1 ?5 ?6 > > > > > 2 ?2 ?8 > > > > > 2 ?9 ?5 > > > ... > > > I have a related question: > > > Does Python have (or can emulate) the formatted output capability found in > > Perl? > > > For example, all I have to do to get nicely formatted (i.e., aligned) output > > is provide values for special STDOUT variables (i.e., STDOUT_TOP, STDOUT, > > STDOUT_BOTTOM, etc.), exemplified by: > > > ? format STDOUT_TOP = > > ? ------------------------------------------------------------------------------ > > ? ~ > > ? . > > > ? format STDOUT = > > ? @<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<< > > ? $res->{'full_name'}, ?$res->{'phone_1'}, ? ? ? ? $res->{'phone_1_type'} > > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > > ? $res->{'address_1a'}, ? ? ? ? ? ? ? ?$res->{'address_2a'} > > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > > ? $res->{'address_1b'}, ? ? ? ? ? ? ? ?$res->{'address_2b'} > > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > > ? $res->{'address_1c'}, ? ? ? ? ? ? ? ?$res->{'address_2c'} > > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > > ? $city_1 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?$city_2 > > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > > ? $res->{'email_1'}, ? ? ? ? ? ? ? ? ? $res->{'email_2'} > > ? ------------------------------------------------------------------------------ > > ? ~ > > ? . > > > Then, all I have to do is populate my $res object/hash as desired -- in this > > example simple the results of a SQL query -- and lastly just call the "write" > > function: > > > ? write; > > > and Perl will produce very nicely formatted results. ?This is useful not only > > for producing human readable output, but also fixed-column-width data files, > > etc. ?I'd love to learn the Pythonistic way of doing the same thing. > > > Thanks! > > Doug > > Can't seem to do this with dictionaries but... > > preformatted_string = """ > %s %20s %20s > %s %30s > %s %30s > """ > > print preformatted_string % ('first name'[:20], 'contact num 1'[:20], > ? ? ? ? 'contact num type'[:20], 'address line 1'[:30], 'address line > 2'[:30] > ? ? ? ? 'address line 3'[:30], 'address line 4'[:30]) > > You could do something like that. ?the "[:20]" etc @ the end of the > inputs is ofc to trim the strings to a max length. ?The string > formatter supports "%s" so > you can use that for alignment. ?It's a bit late so maybe I buggered > up when I tried to use dictionary assignment with it, but who knows :p Actually just realised I had the number on the wrong side... :D preformatted_string = """ %(first_name)s %(contact_num)20s %(contact_type)20s """ print preformatted_string % {'first_name':'Chris', 'contact_num':'555-5555', 'contact_type':'Home'} From duncan.booth at invalid.invalid Thu Jun 12 04:12:00 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jun 2008 08:12:00 GMT Subject: ClassName.attribute vs self.__class__.attribute References: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> Message-ID: Mike Orr wrote: > That's a misunderstanding of classes vs instances. If you have an > instance of MyClass(Superclass), there is one instance but several > classes. The instance is of MyClass; there is no instance of > Superclass. 'self' has a .__class__ attribute because it's an > instance, but MyClass and Superclass do not because they're already > classes. Classes are also instances, usually they are instances of the type 'type' (and even 'type' is an instance of itself): >>> class SuperClass(object): pass >>> SuperClass.__class__ >>> type(SuperClass) >>> type.__class__ Old style classes don't have a class attribute, but you shouldn't be using old style classes anyway and so long as you use type(x) to access its class rather than accessing the __class__ attribute directly that doesn't particularly matter. -- Duncan Booth http://kupuguy.blogspot.com From deets at nospam.web.de Wed Jun 11 10:01:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 11 Jun 2008 16:01:31 +0200 Subject: Does the python library of Google Data API is truly free? References: <3ac654b2-61b4-44ce-8e03-75f2344d5869@s50g2000hsb.googlegroups.com> <6fb57ab1-b0d2-4b7d-93c1-b919ca0e51a0@i36g2000prf.googlegroups.com> <3a296d00-d4e0-4f03-b6b3-bef4c5d628dd@x35g2000hsb.googlegroups.com> <6b5mloF3aeui4U1@mid.uni-berlin.de> <18115776-edf7-41b8-a5e9-639847c57a6a@x41g2000hsb.googlegroups.com> Message-ID: <6ba472F3anud0U1@mid.uni-berlin.de> > I understand very well that a service is a software which is accessed > through a network. No, you obviously don't understand. A service is something that is offered to you, for free or not, and that you might use on the terms the service provider lays down. Some examples? Pizza delivery service Shoe cleaning service Car wash service Online software store Google search engine/mail/groups/other services All these are services. You are free to use them, on their terms and conditions. Some require you to pay money. Some take your data, enrich/recombine or do whatever with it, and provide you added value - for the cost of you giving away the data for free and agreeing on using it, and for having to look at advertisements when using the service. > And the description given on Wikipedia [1] is "A 'Web service' (also > Web Service) is defined by the W3C as "a software system designed to > support interoperable Machine to Machine interaction over a network." A webservice is a technical term for software interoperation. It has *nothing* to do with a service in the above sense. It defines an interface, it might come with a example implementation under a FOSS license. > Now, to ending with this. I understand that (almos) everybody is pro > Google (and anti Microsoft), thinking that they have given a lot of > services for free. And it's very hard that people understand my > thinking. because it is obviously skewed. Just because the term "service" is used in two meanings does not mean they are the same... > All that "free service" has a great price, that are the rights > about those data, and when Google want can to disable the free access > to that information. Yes, they can. That are their conditions. But this has *NOTHING* to do with them offering a piece of software under a FOSS license. > People don't realize that it's one more a company and like so it has > only an end, that is to obtain the greater number of benefits which > will be distributed between his shareholders. Within any years Google > will be as hated as Microsoft. Maybe, maybe not. > At least I try to use the less possible those services than limit my > freedoms about data that has been contributed by me and another users. You are free to do so, and I can't say a single word against it. But you say """ There is certain deceit because they have used a free license as Apache 2.0 so that people think that it is a free program, but it stops of being it when there are terms/conditions of this style. They use to the community to get information as data about geo- localization. You haven't any right about its *free software* but they get all rights about your content. And they could cancel the service when they want. In addition these terms are more restrictive that the owner software, because you could not duplicate any service. Please read well those terms and conditions before of use that library because *IT IS NOT FREE SOFTWARE*. """ It is FREE SOFTWARE. You can take the software ,manipulate it, redestribute it under the terms of the GPL and so forth. That has NOTHING to do with the service offered by google HOSTED AT THEIR SITE, PROGRAMMED AT THEIR EXPENSE, OPERATED AT THEIR COSTS to be something they put out for free. They do gather your data to make a richer experience for others, including yourself, and cashing in on advertisements or whatever business-model they like. If you don't like that, fine. But that has *nothing* to do with free software they might offer to access that service. Diez From aahz at pythoncraft.com Mon Jun 16 19:44:15 2008 From: aahz at pythoncraft.com (Aahz) Date: 16 Jun 2008 16:44:15 -0700 Subject: We are all consenting adults here References: <2cca4335-1162-4d61-b115-1f17d368721d@d1g2000hsg.googlegroups.com> Message-ID: In article <2cca4335-1162-4d61-b115-1f17d368721d at d1g2000hsg.googlegroups.com>, David Hughes wrote: > >Who coined this originally? AFAICT, none other than Guido. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From nagle at animats.com Tue Jun 3 12:19:49 2008 From: nagle at animats.com (John Nagle) Date: Tue, 03 Jun 2008 09:19:49 -0700 Subject: Continuous Timer In-Reply-To: References: <496954360805301850u4ce63746vc8fcc84ad1b72824@mail.gmail.com> Message-ID: <48456b96$0$17165$742ec2ed@news.sonic.net> Gabriel Genellina wrote: > En Fri, 30 May 2008 22:50:13 -0300, Robert Dailey > escribi?: > >> Reading through the Python 2.5 docs, I'm seeing a Timer class in the >> threading module, however I cannot find a timer object that will >> continuously call a function of my choice every XXXX amount of >> milliseconds. >> For example, every 1000 milliseconds I want a function named Foo to be >> called. This would continue to happen until I terminate the timer in >> my main >> thread. Thanks for the help. > > Use an Event object; its wait() will provide the sleep time, and when it > is set() the thread knows it has to exit. > > import threading > import time > > def repeat(event, every, action): > while True: > event.wait(every) > if event.isSet(): > break > action() Actually, to do this right, it's necessary to account for the time used by "action". The code above will run no sooner than the time "every" after the COMPLETION of action. I've done this sort of thing under QNX, the real-time operating system, which has better timing primitives, and seen the action executed within a few microseconds of the correct time, every time. But that was in C++. If you're trying to do hard real time in Python on Linux or Windows, don't expect reliable timing. Remember, Python isn't really preemptive, because of the global interpreter lock and the lack of thread priorities. John Nagle From prabhuragav.b at gmail.com Fri Jun 6 12:04:27 2008 From: prabhuragav.b at gmail.com (BABLU) Date: Fri, 6 Jun 2008 09:04:27 -0700 (PDT) Subject: EARN DOLLARS WIYH OUT INVESTMENT Message-ID: <1fc408cd-c95f-4a73-80b2-d1b6db4ec7c8@x19g2000prg.googlegroups.com> Hi, I am doing home based business and earning a good amount of money and found that business through internet is amazing to earn during leisure.Its just easy and relaxing. Just login in the link below and register yourself. register is free. then they will promote job for you. I have provided three site links for you so that you can earn money in which you want. Every job is genuine, good easy and interesting too. Make a try and fill your pockets with dollars. FREE ! FREE ! FULLY GENUINE HOME BASED ? CLICK HERE http://www.ezinfocenter.com/10122618/CB http://Prabhiya.dubaimlm.com? http://www.CashBlasterPro.com/earndollars http://www.webupgrade7.com/earndollars http://www.webupgrade9.com/earndollars http://www.webupgrade10.com/earndollars http://www.www2upgrade.com/earndollars http://www.BizOpSpace.com/earndollars http://www.BizOpBuilder.com/earndollars http://www.MyWebToo.com/earndollars http://www.Web2Wow.com/earndollars While you've been reading the above, thousands of people all over the world have been working. I even make money while I sleep! By this time next week, so could YOU. Get full info here http://www.ezinfocenter.com/10122618/CB http://Prabhiya.dubaimlm.com http://www.CashBlasterPro.com/earndollars http://www.webupgrade7.com/earndollars http://www.webupgrade9.com/earndollars http://www.webupgrade10.com/earndollars http://www.www2upgrade.com/earndollars http://www.BizOpSpace.com/earndollars http://www.BizOpBuilder.com/earndollars http://www.MyWebToo.com/earndollars http://www.Web2Wow.com/earndollars Network Marketing is BOOMING on the Web! Learn how we're sponsoring OVER 100,000 monthly worldwide without mailing anything, without faxing anything, without calling anyone! Totally Internet and system- driven and we've only scratched the surface. Get started FREE! Sign up as an affiliate at: http://www.ezinfocenter.com/10122618/CB ?http://Prabhiya.dubaimlm.com http://www.CashBlasterPro.com/earndollars http://www.webupgrade7.com/earndollars http://www.webupgrade9.com/earndollars http://www.webupgrade10.com/earndollars http://www.www2upgrade.com/earndollars http://www.BizOpSpace.com/earndollars http://www.BizOpBuilder.com/earndollars http://www.MyWebToo.com/earndollars http://www.Web2Wow.com/earndollars For More Details : Contact us at: Priya Prabhu No.75/31,Ist Floor , Subramanianm Swamy Koil Street West Saidapet chennai-600015 prabhuragav.b at gmail.com http://www.ezinfocenter.com/10122618/CB http://Prabhiya.dubaimlm.com http://www.CashBlasterPro.com/earndollars http://www.webupgrade7.com/earndollars http://www.webupgrade9.com/earndollars http://www.webupgrade10.com/earndollars http://www.www2upgrade.com/earndollars http://www.BizOpSpace.com/earndollars http://www.BizOpBuilder.com/earndollars http://www.MyWebToo.com/earndollars http://www.Web2Wow.com/earndollars From smmckay at broncs.utpa.edu Sun Jun 8 23:31:17 2008 From: smmckay at broncs.utpa.edu (Steve McKay) Date: Sun, 08 Jun 2008 22:31:17 -0500 Subject: sendKey In-Reply-To: <47d57426-3131-4252-8cee-086977f51b0b@2g2000hsn.googlegroups.com> References: <47d57426-3131-4252-8cee-086977f51b0b@2g2000hsn.googlegroups.com> Message-ID: Gandalf wrote: > I found some script that send keys , But I couldn't manage to send > CTRL+c with none of them > > can any one tell me what i'm doing wrong: > > import win32api > import win32com.client > > shell = win32com.client.Dispatch("WScript.Shell") > shell.Run("Notepad") > win32api.Sleep(100) > shell.AppActivate("Notepad") > win32api.Sleep(100) > shell.SendKeys("112435435") > win32api.Sleep(100) > > shell.SendKeys("^a") # that wouldn't select all > win32api.Sleep(100) > shell.SendKeys("^c")# that wouldn't copy > > > > > import SendKeys > SendKeys.SendKeys("""^c""") > > > Thank you! > Your code didn't work for me, either. But shell.SendKeys("^a^c") works...go figure. From hancock.robert at gmail.com Mon Jun 16 19:20:53 2008 From: hancock.robert at gmail.com (Robert Hancock) Date: Mon, 16 Jun 2008 16:20:53 -0700 (PDT) Subject: sqlite3 and Python 2.5.1 References: <612ed26a-c6cf-4133-af6c-f256484e3928@x41g2000hsb.googlegroups.com> <6bo3euF3c8etnU1@mid.uni-berlin.de> Message-ID: On Jun 16, 5:15 pm, Gerhard H?ring wrote: > milan_sanremo wrote: > > I have sqlite installed, but when I try to importsqlite3I receive: > > > Python 2.5.1 (r251:54863, Nov 3 2007, 02:54:36) [C] on sunos5 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> importsqlite3 > > Traceback (most recent call last): > > File "", line 1, in > > ImportError: No module namedsqlite3 > > > Yet: > > > # find /usr/local/python -name "sqlite*" -print > > /usr/local/python/lib/python2.5/sqlite3 > > > # /opt/csw/bin/sqlite3 > > SQLite version 3.2.2 > > Enter ".help" for instructions > > sqlite> > > > What is missing? > > You compiled Python yourself. During that, theSQLite3header files > could not be found, so thesqlite3module was not compiled/installed. > > -- Gerhard Thanks, I'll recompile. From leodp at yahoo.com Mon Jun 30 06:13:22 2008 From: leodp at yahoo.com (leodp) Date: Mon, 30 Jun 2008 03:13:22 -0700 (PDT) Subject: Getting sorting order References: <7cb9ebb7-e722-41e1-bdf2-693954a21b92@j22g2000hsf.googlegroups.com> Message-ID: <5ce855b0-e2fa-4323-b7b8-5b5dd11ef586@d1g2000hsg.googlegroups.com> > >>> master_index.sort(key=master.__getitem__) that was it! Thanks Peter, leodp From lotrpy at gmail.com Wed Jun 11 20:14:25 2008 From: lotrpy at gmail.com (lotrpy) Date: Wed, 11 Jun 2008 17:14:25 -0700 (PDT) Subject: How to make py2.5 distutil to use VC2005? References: Message-ID: <4b6be352-c119-4b20-a32d-f85863227cc8@n19g2000prg.googlegroups.com> On 6?4?, ??9?47?, "David Cournapeau" wrote: > On Wed, Jun 4, 2008 at 11:38 AM, ?? wrote: > > Well, IMO, the format of binary files generated by VC2003 and > > VC2005 is compatible in most cases. > > Problem arise with the C runtime, not with object file format. In > particular, python uses the C api for file handling, and the standard > C is definitely not ABI compatible within VS versions. > > I strongly advise you against using VS 2005 (with the binary python; > if you build python by yourself, then no problem; I don't know if it > is possible to build python with VS 2005). You *will* get crashes in > many cases. > > David My stupid question: if there is something between VS 2003 and VS 2005 incompatible, what about MINGW for python2.5(VS 2003)? Is it safe, or just as (un)safe as VS 2005? From nospam at nospam.com Sun Jun 1 08:43:06 2008 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 01 Jun 2008 14:43:06 +0200 Subject: [Business apps for Windows] Good grid + calendar, etc.? References: Message-ID: On Sun, 1 Jun 2008 21:27:30 +0900, "Ryan Ginstrom" wrote: >For your stated needs, I'd advise checking out IronPython or Python.NET >(which allow use of .NET GUI libraries). Thanks but I forgot to say that I'd rather not use .Net because deployment/updates are too problematic for our audience. .. that's assuming that a GUI Python can install/update itself as easily as eg. Delphi, which is where I could be wrong :-/ From tdahsu at gmail.com Fri Jun 13 11:11:16 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Fri, 13 Jun 2008 08:11:16 -0700 (PDT) Subject: Iterate creating variables? Message-ID: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> I have twenty-five checkboxes I need to create (don't ask): self.checkbox1 = ... self.checkbox2 = ... . . . self.checkbox25 = ... Right now, my code has 25 lines in it, one for each checkbox, since these are all variables. Is there a way to write a loop so that I can have fewer lines of code but still keep the variables? I've tried: for o in xrange(25): self.checkbox[o] = ... which didn't work, and for o in xrange(25): self.checkbox[''%d'%(o)] = ... which also didn't work. Both give the error message: "Attribute error: Main.App has no attribute "checkbox"", which clearly indicates that I'm not keeping the "variability" aspect I want. Is there a way? I appreciate any and all answers! Thanks! From gagsl-py2 at yahoo.com.ar Wed Jun 18 03:45:54 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Jun 2008 04:45:54 -0300 Subject: Does '!=' equivelent to 'is not' References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> Message-ID: En Tue, 17 Jun 2008 23:04:16 -0300, Asun Friere escribi?: > On Jun 17, 5:33 pm, "Gabriel Genellina" > wrote: >> En Tue, 17 Jun 2008 02:25:42 -0300, Lie escribi?: > >> >> > Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)' >> > and 'not(id(a) == id(b))' >> >> No. > ... >> ... The above statement is not. A counterexample: >> >> py> [] is [] >> False >> py> id([])==id([]) >> True >> > But that's not what he said, he used 'a' and 'b' which are names, not > anonymous objects. > Fairer would be, > a = [];b = [] > id(a) == id(b) If you limit yourself to interpret 'a' and 'b' as actual names, yes, the statement is true. But I thought of them as placeholders or metasyntactic names - like in "abs(x) returns the absolute value of x", where x may represent *any* expression, not just a single name. Under this general interpretation the statement is not true anymore. (This thread is getting way above 10000cp...) -- Gabriel Genellina From jarausch at igpm.rwth-aachen.de Mon Jun 23 04:38:01 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Mon, 23 Jun 2008 10:38:01 +0200 Subject: 2to3 bug and question Message-ID: <6c95nbF3euiugU1@mid.dfncis.de> Hi, is this the right group to ask / report problems with python3.0 ? The question: Is it possible to tell 2to3 to replace, say, #!/usr/bin/python by #!/usr/local/bin/python3.0 ? Here the bug: While 2to3 keeps the first line #!/usr/bin/python it removes the first line if it was #!/usr/bin/python -O Is this a bug or a feature? Thanks for hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From moneymakecash2 at gmail.com Tue Jun 10 14:51:23 2008 From: moneymakecash2 at gmail.com (MERLIN) Date: Tue, 10 Jun 2008 11:51:23 -0700 (PDT) Subject: BANKRUPTCY LAWYER Message-ID: <5638827c-d056-4b21-a0d4-c863c6c6dbe6@z16g2000prn.googlegroups.com> ****************************************** http://bankruptcylawyer1.blogspot.com From victor.herasme at gmail.com Thu Jun 5 10:19:07 2008 From: victor.herasme at gmail.com (victor.herasme at gmail.com) Date: Thu, 5 Jun 2008 07:19:07 -0700 (PDT) Subject: Tuples part 2 References: <6d3e6d40-63a6-40d1-8ea4-5ddf40238d8d@m44g2000hsc.googlegroups.com> Message-ID: On Jun 5, 3:49 pm, Ivan Illarionov wrote: > On 5 ???, 01:57, "victor.hera... at gmail.com" > wrote: > > > > > Hi Everyone, > > > i have another question. What if i wanted to make n tuples, each with > > a list of coordinates. For example : > > > coords = list() > > for h in xrange(1,11,1): > > for i in xrange(1, 5, 1) : > > for j in xrange(1, 5, 1) : > > for k in xrange(1,2,1) : > > coords.append((i,j,k)) > > lista+str(h)= tuple coords > > print tuple(coords) > > > so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do > > it the way i show you above but it is not working properly. I wish you > > could help me with that. Thanks again, > >>> from itertools import repeat, izip > >>> coords = tuple((i,j,k) for i in xrange(1,5) for j in xrange(1,5) for k in xrange(1,2)) > >>> locals().update(("tuple%s" % i, coord) for i, coord in izip(xrange(1,11), repeat(coords))) > >>> tuple1 > > ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (2, 1, 1), (2, 2, 1), (2, > 3, 1), (2 > , 4, 1), (3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1), (4, 1, 1), (4, 2, > 1), (4, 3 > , 1), (4, 4, 1)) > > Does this help? > > But I don't understand why you need this? > > Ivan Hi, What i need is, for example: tuple 1=((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)) tuple 2=((2, 1, 1), (2, 2, 1), (2, 3, 1), (2, 4, 1)) tuple 3=((3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1)) and so on. Please help me and sorry for not taking the time to post my questions properly. Victor From wmcbrine at users.sf.net Fri Jun 13 21:46:24 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Sat, 14 Jun 2008 01:46:24 GMT Subject: Python Socket programming References: Message-ID: On Fri, 13 Jun 2008 21:59:06 +0530, srinivasan srinivas wrote: > I am going to do some socket related programming in Python. Before that, > I wish to know the Gotchas of Python Scoket Programming. The only gotcha I see is that you won't want to go back to doing it in C. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From pavel.uvarov at gmail.com Tue Jun 3 11:28:38 2008 From: pavel.uvarov at gmail.com (pavel.uvarov at gmail.com) Date: Tue, 3 Jun 2008 08:28:38 -0700 (PDT) Subject: ThreadPoolingMixIn References: <3d9dac72-ce4d-4ce5-9213-4bb17aff2f9e@r66g2000hsg.googlegroups.com> <1c4d113e-b375-471d-9d54-1401c8844352@t12g2000prg.googlegroups.com> <03ba6980-55d6-433a-a41f-f36a2edb4d72@f36g2000hsa.googlegroups.com> <4804d404-6d74-4391-a073-aaa7f51a7dc9@z66g2000hsc.googlegroups.com> Message-ID: <7e4efa2e-6438-4d3f-b996-c52859e65715@k37g2000hsf.googlegroups.com> On Jun 3, 1:19 am, miller.pau... at gmail.com wrote: > On Jun 2, 12:41 pm, pavel.uva... at gmail.com wrote: > > > > > On Jun 2, 7:15 pm, Michael Str?der wrote: > > > Here are benchmarks for FreeBSD 6.2, amd64 > > > packet_size x y > > 0 499.57 1114.54 > > 1024 499.29 1130.02 > > 3072 500.09 1119.14 > > 7168 498.20 1111.76 > > 15360 499.29 1086.73 > > 31744 500.04 1036.46 > > 64512 499.43 939.60 > > 130048 499.28 737.44 > > 261120 498.04 499.03 > > 523264 307.54 312.04 > > 1047552 173.57 185.32 > > 2096128 93.61 94.39 > > > x = ThreadingMixIn replies/s > > y = ThreadPoolingMixIn replies/s > > Well, I'd say you've got yourself a winner. Performance (at least on > FreeBSD) seems as good or better for your ThreadPoolingMixin than > ThreadingMixin. Is this with the default values of min=5 and max=5 > worker threads? No, I initialized thread pool with min_threads=2, max_threads=200 and min_spare_threads=20. For Linux (2.6.22, amd64) I got even more dramatic improvement: packet_size x y 0 249.97 2014.63 1024 249.98 1782.83 3072 240.09 1859.00 7168 249.98 1900.61 15360 249.98 1787.30 31744 238.96 1808.17 64512 249.85 1561.47 130048 237.26 1213.26 261120 249.98 841.96 523264 249.97 595.40 1047552 236.40 351.96 2096128 216.26 218.15 x = ThreadingMixIn replies/s y = ThreadPoolingMixIn replies/s From cwitts at gmail.com Mon Jun 2 17:34:52 2008 From: cwitts at gmail.com (Chris) Date: Mon, 2 Jun 2008 14:34:52 -0700 (PDT) Subject: Formatting Output References: <6e94b4dc-5920-447e-9971-96ec6a48b9ce@c58g2000hsc.googlegroups.com> <6ea2e85a-d00c-4228-98be-431205fceb7b@34g2000hsf.googlegroups.com> Message-ID: <650fca09-a6de-4d81-a19b-687c63ad429b@l64g2000hse.googlegroups.com> On Jun 2, 9:43?pm, Doug Morse wrote: > On Mon, 2 Jun 2008 12:42:12 -0700 (PDT), Mensanator wrote: > > ?On Jun 2, 3:38?am, Chris wrote: > > > On Jun 2, 9:34?am, "victor.hera... at gmail.com" > > > > wrote: > > > > Hi, > > > > > i am building a little script and i want to output a series of columns > > > > more or less like this: > > > > > 1 ?5 ?6 > > > > 2 ?2 ?8 > > > > 2 ?9 ?5 > > ... > > I have a related question: > > Does Python have (or can emulate) the formatted output capability found in > Perl? > > For example, all I have to do to get nicely formatted (i.e., aligned) output > is provide values for special STDOUT variables (i.e., STDOUT_TOP, STDOUT, > STDOUT_BOTTOM, etc.), exemplified by: > > ? format STDOUT_TOP = > ? ------------------------------------------------------------------------------ > ? ~ > ? . > > ? format STDOUT = > ? @<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<< > ? $res->{'full_name'}, ?$res->{'phone_1'}, ? ? ? ? $res->{'phone_1_type'} > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $res->{'address_1a'}, ? ? ? ? ? ? ? ?$res->{'address_2a'} > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $res->{'address_1b'}, ? ? ? ? ? ? ? ?$res->{'address_2b'} > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $res->{'address_1c'}, ? ? ? ? ? ? ? ?$res->{'address_2c'} > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $city_1 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?$city_2 > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $res->{'email_1'}, ? ? ? ? ? ? ? ? ? $res->{'email_2'} > ? ------------------------------------------------------------------------------ > ? ~ > ? . > > Then, all I have to do is populate my $res object/hash as desired -- in this > example simple the results of a SQL query -- and lastly just call the "write" > function: > > ? write; > > and Perl will produce very nicely formatted results. ?This is useful not only > for producing human readable output, but also fixed-column-width data files, > etc. ?I'd love to learn the Pythonistic way of doing the same thing. > > Thanks! > Doug Can't seem to do this with dictionaries but... preformatted_string = """ %s %20s %20s %s %30s %s %30s """ print preformatted_string % ('first name'[:20], 'contact num 1'[:20], 'contact num type'[:20], 'address line 1'[:30], 'address line 2'[:30] 'address line 3'[:30], 'address line 4'[:30]) You could do something like that. the "[:20]" etc @ the end of the inputs is ofc to trim the strings to a max length. The string formatter supports "%s" so you can use that for alignment. It's a bit late so maybe I buggered up when I tried to use dictionary assignment with it, but who knows :p From martin.nordstrom87 at gmail.com Tue Jun 24 15:59:52 2008 From: martin.nordstrom87 at gmail.com (martin.nordstrom87 at gmail.com) Date: Tue, 24 Jun 2008 12:59:52 -0700 (PDT) Subject: Wrap Numpy with Cython? Message-ID: Hi! I'm trying to wrap numpy with Cython and I've tried to use this guide to manage this: http://wiki.cython.org/WrappingNumpy However when I send an array to mysum() it gives me the right answer only when dtype of the array is float, otherwise it gives me random answers. The problem may be that the array is converted to a C double which is just as long as float for Numpyarrays and therefore it works only when the dtype is float. How do I make a Numpywrapper that works with an arbitrary dtype? I've also tried to convert a tuple or list with only numbers in it to a C array with Cython but I've failed. Does anyone have an example of how to do this? Thanks! Martin From jeff at jmcneil.net Wed Jun 11 14:58:52 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 11 Jun 2008 14:58:52 -0400 Subject: Programming question In-Reply-To: <31C3FE622274D44A8FE8E8D649AE178805E738D4@exch1.wni.com> References: <31C3FE622274D44A8FE8E8D649AE178805E738D4@exch1.wni.com> Message-ID: <82d28c40806111158x542000f0n5a99c39e4eacd9ec@mail.gmail.com> Have a look at os.listdir and os.stat. I've never worked with 1.5, so I don't know what will work with it and what won't,. but I'd imagine the following ought to be fine, though. stat_list = [] for dirent in os.listdir('your_directory'): stat_list.append(os.stat(dirent)) Jeff On Wed, Jun 11, 2008 at 2:33 PM, Brad Navarro wrote: > Greetings, > > > > Being extremely new to Python, I haven't got the experience to figure this > one out on my own and frankly I am not sure I would know where to look. > > > > Basically, what I am trying to do is get a list of each file's attributes > within a directory. Basically, the information that the 'ls ?l' command > would give you in a linux shell, except the results for each file in the > directory are stored as a list. > > > > I am presently using version 1.5 on a linux machine. I have kindly requested > my system administrator to upgrade to 2.5.2, but until then I am afraid I am > stuck with 1.5. > > > > > > Thanks, > > Brad > > -- > http://mail.python.org/mailman/listinfo/python-list > From userprogoogle-139 at yahoo.co.uk Thu Jun 26 05:41:03 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Thu, 26 Jun 2008 02:41:03 -0700 (PDT) Subject: Mobile Devices References: <549d4fcd-7c89-47dc-9a44-8e3e6ac92ed2@d77g2000hsb.googlegroups.com> Message-ID: <9d18a9fb-eac8-47bb-8b68-e65a64957f1e@e53g2000hsa.googlegroups.com> Thanks for your reply, I may dig out my really old Symbian phone and try it out. rod From arslanburney at gmail.com Fri Jun 13 01:32:23 2008 From: arslanburney at gmail.com (arslanburney at gmail.com) Date: Thu, 12 Jun 2008 22:32:23 -0700 (PDT) Subject: Plotting Graphs + Bestfit lines Message-ID: <1a919a2b-6430-4e2e-a190-2e00e43a6138@25g2000hsx.googlegroups.com> Hello. Ive got two functions here. Somehow the program does not go in to the second function wehn i call it. The bestfit function. Could some1 help me identify the problem. Heres the code: import Gnuplot def bestfit(uinput): if not isinstance(uinput, list): return False else: sigmax = sigmay = sigmaxy = sigmaxwhl = sigmaxsq = 0 for i in range(len(uinput)): n = len(uinput) sigmax = uinput[i][0] + sigmax sigmay = uinput[i][1] + sigmay sigmaxy = uinput[i][0] * uinput [i][1] + sigmaxy sigmaxwhl = sigmax * sigmax sigmaxsq = uinput[i][0] * uinput[i][0] + sigmaxsq sigmaxsigmay = sigmax * sigmay num = sigmaxsigmay - (n * sigmaxy) den = sigmaxwhl - (n* sigmaxsq) num2 = (sigmax * sigmaxy) - (sigmay * sigmaxsq) gradient = num / den intercept = num2 / den m = gradient c = intercept p = Gnuplot.Gnuplot() p.plot ('%f * x+%f'%(m,c)) return p def plot(original, expected, actual): if not isinstance(original, list): return False else: gp = Gnuplot.Gnuplot() gp('set data style lines') # Make the plot items plot1 = Gnuplot.PlotItems.Data(original, title="Original") plot2 = Gnuplot.PlotItems.Data(expected, title="Expected") plot3 = Gnuplot.PlotItems.Data(actual, title="Acutal") gp.plot(plot1, plot2, plot3) bestfit(expected) bestfit(actual) return gp ------- import Combine #The name of my file... gp = Combine.plot( [(2,3), (4,8), (5,9), (6,2)], [(1,7), (3,3), (4,5), (5,6)], [(1,3), (3,10), (4,8), (7,9) ] ) raw_input() From jaywgraves at gmail.com Tue Jun 3 09:49:52 2008 From: jaywgraves at gmail.com (jay graves) Date: Tue, 3 Jun 2008 06:49:52 -0700 (PDT) Subject: Cast list of objects to list of strings References: <48546eb1-11f3-4a88-b1ac-97bd485a1823@k30g2000hse.googlegroups.com> <63d3d50d-0e9b-4682-b523-c2ff7d336c6a@m44g2000hsc.googlegroups.com> Message-ID: On Jun 2, 8:36 pm, "Gabriel Genellina" wrote: > Still nitpicking: using a generator expression in this case has no > advantage. The first thing that str.join does is to create a list out of > its argument (unless it is already a list or a tuple). In fact, a list > comprehension is faster here. Really! I stand corrected. I'm not a C programmer but I peeked at the source. I see that it makes a pass to calculate the total size and then another pass to catenate the items, which makes sense from a memory allocation standpoint. To compare and contrast, I looked up the 'sum' built in and saw that it used the iterator protocol, (PyObject_GetIter). I assume that the other similar functions (min,max, etc) would do the same. Thanks for setting me straight. ... Jay From roy at panix.com Thu Jun 5 15:20:15 2008 From: roy at panix.com (Roy Smith) Date: Thu, 05 Jun 2008 15:20:15 -0400 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> <4847d203$0$32733$426a74cc@news.free.fr> Message-ID: In article , "Russ P." wrote: > In C++ (and > Java?), on the other hand, the "protected" keyword *really* prevents > the client from accessing the data or method, but it allows access to > derived classes. The "private" keyword goes further and prevents > access even by derived classes. In C++, it does no such thing. Consider this class declaration in MySecretClass.h: class MySecretClass { private: int foo; }; All somebody has to do to get at the private data is: #define private public # include #undef private If playing preprocessor games isn't your thing, there's a whole multitude of other tricks you can play with pointers and typecasts that will get you access to foo in other ways. But, you protest, you're not supposed to do that! Well, of course not. But you're not supposed to ignore the leading underscore convention in Python either. That's the nice thing about freedom of religion; you get to pick which particular sins you want to get freaked out about. I'm pretty weak on Java, but my understanding is that it's in better shape here, since it has neither textual inclusion of header files, nor pointers. You might have to resort to JNI :-) From no.spam at spam.no Mon Jun 9 07:23:22 2008 From: no.spam at spam.no (Thin Myrna) Date: Mon, 09 Jun 2008 13:23:22 +0200 Subject: Access to CAN-Bus References: <484cd469$0$28520$3b214f66@aconews.univie.ac.at> Message-ID: <484d12aa$0$11610$3b214f66@aconews.univie.ac.at> Thin Myrna wrote: Thanks for all your answers. I've just contacted the vendor for Linux support. If I went for an other vendor (I'm on a notebook, so USB-hardware is needed): Does anyone have especially good experiences with a particular one? Anyone I should stay away from? Kind regards Thin > I'd like to access some drive hardware via CAN bus from Python under Linux > (sending rec'ing PDOs). Googling around I couldn't find a Python package, > but people who said that they are doing this, though. I guess they are > using their home brewn software. > > Any pointer to > - such software (anyone willing to share his experience?) > - how to write such software? > > Under Windows, I guess, I could use some COM or ctypes functionality to > access the hardware vendor's hardware. What if I wanted to access such > hardware from Linux? Is there a package that allows that in a vendor (who > doesn't support Linux) independent way? > > Many thanks in advance > Thin From Robert.Bossy at jouy.inra.fr Wed Jun 18 08:35:28 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 18 Jun 2008 14:35:28 +0200 Subject: dict order In-Reply-To: References: Message-ID: <48590110.2060600@jouy.inra.fr> Peter Otten wrote: > Robert Bossy wrote: > > >> I wish to know how two dict objects are compared. By browsing the >> archives I gathered that the number of items are first compared, but if >> the two dict objects have the same number of items, then the comparison >> algorithm was not mentioned. >> > > If I interpret the comments in > > http://svn.python.org/view/python/trunk/Objects/dictobject.c?rev=64048&view=markup > > correctly it's roughly > > def characterize(d, e): > return min(((k, v) for k, v in d.iteritems() if k not in e or e[k] != v), > key=lambda (k, v): k) > > def dict_compare(d, e): > result = cmp(len(d), len(e)) > if result: > return result > try: > ka, va = characterize(d, e) > except ValueError: > return 0 > kb, vb = characterize(e, d) > return cmp(ka, kb) or cmp(va, vb) Thanks, Peter! That was exactly what I was looking for. Quite clever, I might add. RB From bruno.desthuilliers at gmail.com Fri Jun 20 17:39:33 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 20 Jun 2008 14:39:33 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> <8711b1fe-8256-4f6f-a3d7-f99f44eb23b0@e53g2000hsa.googlegroups.com> Message-ID: <44e5837c-42f9-49b3-9a92-0560ddcda8ba@z66g2000hsc.googlegroups.com> On 20 juin, 21:44, eliben wrote: > On Jun 20, 3:19 pm, George Sakkis wrote: > (snip) > > It's still not clear why the generic version is so slower, unless you > > extract only a few selected fields, not all of them. Can you post a > > sample of how you used to write it without exec to clarify where the > > inefficiency comes from ? > > > George > > The generic version has to make a lot of decisions at runtime, based > on the format specification. > Extract the offset from the spec, extract the length. import operator transformers = [] transformers.append(operator.itemgetter(slice(format.offset,format.offset +format.length))) > Is it msb- > first ? Then reverse. if format.msb_first: transformer.append(reverse) > Are specific bits required ? If so, do bit > operations. etc.... Python functions are objects, you can define your own callable (ie: function like) types, you can define anonymous single-expression functions using lambda, functions are closures too so they can carry the environment they were defined in, implementing partial application (using either closures or callable objects) is trivial (and is in the stdlib functools module since 2.5 FWIW), well... Defining a sequence of transormer functionals is not a problem neither. And applying it to your data bytestring is just trivial: def apply_transformers(data, transormers) : for transformer in transformers: data = transformer(data) return data ... and is not necessarily that bad performance-wide (here you'd have to benchmark both solutions to know for sure). > A dynamically generated function doesn't have to make any decisions - No, but neither does a sequence of callable objects. The decisions are taken where you have the necessary context, and applied somewhere else. Dynamically generating/compiling code is one possible solution, but not the only one. > I guess this is not much different from Lisp macros The main difference is that Lisp macro are not built as raw string, but as first class objects. I've so found this approach more flexible and way easier to maintain, but here again, YMMV. Anyway, even while (as you may have noticed by now) I'm one of these "there's-a-better-way-than-eval-exec" peoples, I'd think you may (depending on benchmarks with both solutions and real-life data) have a valid use case here - and if you encapsulate this part correctly, you can alway start with your current solution (so you make it work), then eventually switch implementation later if it's worth the extra effort... Just my 2 cents. Truth is that as long as it works and is maintainable, then who cares... From goldnery at gmail.com Tue Jun 17 17:49:34 2008 From: goldnery at gmail.com (Gandalf) Date: Tue, 17 Jun 2008 14:49:34 -0700 (PDT) Subject: text alignment References: <39d1c620-9923-46e7-999d-ed86c8b465ff@34g2000hsh.googlegroups.com> <114f3f4c-4004-488b-86c5-4bf6416e15bd@l42g2000hsc.googlegroups.com> <8d563101-53f0-41d3-a544-ee0ba1d58db5@m36g2000hse.googlegroups.com> <657c1cb2-cfeb-4806-960c-15b3f25f6575@w7g2000hsa.googlegroups.com> <39ae3cec-c231-4196-8f9a-b567b9a47b5c@c65g2000hsa.googlegroups.com> Message-ID: On Jun 17, 8:43?pm, Mike Driscoll wrote: > On Jun 17, 1:20?pm, Gandalf wrote: > > > since you brought up this issue, please tell me where can I fine > > menual for this library? > > You want the manual for wxPython? Go to the download page on the > Official wxPython page and get the Docs & Demos package:http://wxpython.org/download.php > > That include the wxWidgets Reference. Also see:http://wxpython.org/onlinedocs.php > > > can i generate dynamic GUI from it? > > Not sure what you mean by this. If you know how to create a "dynamic > GUI" with html/ajax or some such based on the user's interactions with > your website, than it should work in the embedded browser just as well > as it would in a non-embedded one. > > > If not, Is there any way to generate dynamic GUI (one that can change > > according to the user input) with HTML-CSS- javascript similar > > environment? > > Mike Hi Mike, I was referring to the ActiveX_IEHtmlWindow which you talked about, when I asked you for a tutorial. I have lots of experience on developing web application so if I could implement some of my knowledge for developing none web application it can save me trouble thanks From martin at v.loewis.de Thu Jun 5 16:36:00 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 05 Jun 2008 22:36:00 +0200 Subject: How to make py2.5 distutil to use VC2005? In-Reply-To: References: <5b8d13220806040647o1148bf90x6b2b546e9cb339b5@mail.gmail.com> <5b8d13220806050134s3e6ad9dfn15bd4c5924551bdc@mail.gmail.com> Message-ID: <48484e30$0$9694$9b622d9e@news.freenet.de> > I really really wonder how to *force* distutil to use my specified compile. > eg: (pseudo) You need to make sure that both MSSdk and DISTUTILS_USE_SDK are set, see http://docs.python.org/dist/module-distutils.msvccompiler.html Regards, Martin From 42flicks at gmail.com Tue Jun 10 07:03:20 2008 From: 42flicks at gmail.com (Mike) Date: Tue, 10 Jun 2008 23:03:20 +1200 Subject: TWITTER API and urllib2 In-Reply-To: <2b54d4370806100342h7a34f5f3p13ba81a6e873f14f@mail.gmail.com> References: <2b54d4370806100342h7a34f5f3p13ba81a6e873f14f@mail.gmail.com> Message-ID: <2b54d4370806100403k3a65df23nde52d100a5d580ca@mail.gmail.com> On Tue, Jun 10, 2008 at 10:42 PM, Mike <42flicks at gmail.com> wrote: > Hello, > > I've spent the last couple of nights hacking away at a Python wrapper for > the Twitter API that I can use for various things. > > I'm having trouble with one of the methods: user_timeline. ( > http://groups.google.com/group/twitter-development-talk/web/api-documentation#HelpMethods > ). > > This is the only method that is returning a HTTP 401. It seems strange and > I'm not sure how to debug it further as the other methods requring > authentication work. > > Please keep in mind the code is missing alot of polish :) - Though I'm open > to suggestions on improvements. > > If anyone is familiar with this I'd really appreciate a hint as it has me > stumped! (I really need this method for my functionality too!) > > --- > > import urllib2, urllib, urlparse > > class TwitterMethods(object): > def __init__(self): > pass > > def url_request(self,uri,authentication=None): > auth = urllib2.HTTPBasicAuthHandler() > netlock = urlparse.urlparse(uri) > if authentication: > passwdMgr = urllib2.HTTPPasswordMgrWithDefaultRealm() > > passwdMgr.add_password(None,netlock[1],authentication.username,authentication.password) > > auth = urllib2.HTTPBasicAuthHandler(passwdMgr) > req = urllib2.Request(uri) > o = urllib2.build_opener(auth) > try: > f = o.open(req) > print f.readlines([0]) > except o.error: > print "error" > #except: > # print "unknown error" > return > > def UserTimeline(self,authentication): > self.url_request("http://twitter.com/statuses/user_timeline.xml > ",authentication) > > class TwitterAuth(object): > def __init__(self,username,password): > self.username = username > self.password = password > > p = TwitterMethods() > auth = TwitterAuth('email at gmail.com','password') > p.UserTimeline(auth) > > > I did come across this post: http://twitterpatter.wordpress.com/2008/02/11/twitterpatter-update-making-progress-accessing-twitter-timelines/Which only mentions it, does not offer a solution. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Lie.1296 at gmail.com Mon Jun 9 11:41:37 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 9 Jun 2008 08:41:37 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> Message-ID: <49356862-86a6-4df4-886a-cd57827c1b1e@w8g2000prd.googlegroups.com> On Jun 9, 7:20?pm, Antoon Pardon wrote: > On 2008-06-07, BJ?rn Lindqvist wrote: > > > On Wed, Jun 4, 2008 at 2:02 PM, Antoon Pardon wrote: > >> Now of course noone would defend such a limitation on the grounds > >> that one doesn't need the general case and that the general case > >> will only save you some vertical space. > > >> But when it came to the ternary operator that was exactly the > >> argument used, to defend the lack of it. > > > As far as I remember, the primary motivation was developers experience > > with the ternary operator in other languages, especially C, where it > > was found to hurt readability. At least in my experience, it is much > > much more common to see the ternary operator making code more > > obfuscated than easing readability. Time will tell if Python's if-else > > expression will be abused in the same way. > > That seems strange to me. The and-or simulation that was offerd in the > FAQ allowed for about the same kind of structures as the ternary > operator in C and was used in the standard library IIRC. > > So the same unreadable was already possible to write, plus that it > could cause bugs and had to be made even more unreadable in order > to work correctly. Considering this it I find it odd that hurting > readability was a motivation not to have it. In case you didn't notice, the and-or simulation is a hack, it is not to be used by anyone writing real code (instead of for an entry to Obfuscated Python Code Contest) to substitute it for inline if. If inline if is "formalized", that means the language encourages the use of inline if, which we don't want to have. From kyrie at uh.cu Tue Jun 10 01:29:43 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Tue, 10 Jun 2008 01:29:43 -0400 Subject: PEP on breaking outer loops with StopIteration In-Reply-To: References: Message-ID: <1213075783.484e11471be98@comuh.uh.cu> Quoting Kris Kowal : > I had a thought that might be pepworthy. Might we be able to break > outer loops using an iter-instance specific StopIteration type? > > This is the desired, if not desirable, syntax:: > > import string > letters = iter(string.lowercase) > for letter in letters: > for number in range(10): > print letter, number > if letter == 'a' and number == 5: > raise StopIteration() > if letter == 'b' and number == 5: > raise letters.StopIteration() > I must say, I don't even like the idea of having a 'break', but I kind of like this proposal. However, it may be ambiguous [is that a word?] if the outer and inner for loop over the same object. Weird/unlikely situation, I know... but so is having a deep break :D. -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie From maric at aristote.info Tue Jun 24 01:35:55 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 24 Jun 2008 07:35:55 +0200 Subject: Fwd: xml to mysql (vice versa ) too In-Reply-To: References: Message-ID: <200806240735.56237.maric@aristote.info> Le Tuesday 24 June 2008 07:08:46 swapna mudavath, vous avez ?crit?: > can anybody help me in this.... > > -swapna > > ---------- Forwarded message ---------- > From: swapna mudavath > Date: Mon, Jun 23, 2008 at 5:27 PM > Subject: xml to mysql (vice versa ) too > To: Python-list at python.org > > > Hi, > > I need to write a python script to store data which is in XML to MYSQL and > even vice versa.... > what should be the approach? > i am able to establish a connection,create tables and insert data ..... > but how to read an xml file and store in MYSQL.... > my XML structure is like > > > > > > > . > .... > ... > This is not valid xml, there is no commas in attribute list in xml. > can somebody please help me......i am really confused!!!!!! > > thanks in advance :) You could try with minidom if your xml stream isn't too large, else sax parser is to be considered, but minidom is pretty easy to use. Give it a try and come back with more specific questions. In [82]: from xml.dom.minidom import parseString In [83]: xml = """ """ In [89]: def print_nodes(node) : print node if node.attributes : for n, v in node.attributes.items() : print n, v for i in node.childNodes : print_nodes(i) ....: ....: In [94]: dom = parseString(xml) In [95]: print_nodes(dom) id 1 title xyz name abc pos 1 name hgdf pos 3 -- _____________ Maric Michaud From kyosohma at gmail.com Tue Jun 10 13:15:09 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 10 Jun 2008 10:15:09 -0700 (PDT) Subject: problems with opening files due to file's path References: <17759531.post@talk.nabble.com> Message-ID: On Jun 10, 11:45?am, Alexnb wrote: > Gerhard H?ring wrote: > > > Alexnb wrote: > >> Okay, so what I want my program to do it open a file, a music file in > >> specific, and for this we will say it is an .mp3. Well, I am using the > >> system() command from the os class. [...] > > >> system("\"C:\Documents and Settings\Alex\My Documents\My > >> Music\Rhapsody\Bryanbros\Weezer\(2001)\04 - Island In The Sun.wma\"") > >> [...] > > > Try os.startfile() instead. It should work better. > > > -- Gerhard > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > No, it didn't work, but it gave me some interesting feedback when I ran it > in the shell. Heres what it told me: > > >>> os.startfile("C:\Documents and Settings\Alex\My Documents\My > >>> Music\Rhapsody\Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm > >>> Yours.wma") > > Traceback (most recent call last): > ? File "", line 1, in > ? ? os.startfile("C:\Documents and Settings\Alex\My Documents\My > Music\Rhapsody\Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm Yours.wma") > > WindowsError: [Error 2] The system cannot find the file specified: > "C:\\Documents and Settings\\Alex\\My Documents\\My > Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\x01 - I'm > Yours.wma" > > See it made each backslash into two, and the one by the parenthesis and the > 0 turned into an x.... > -- > View this message in context:http://www.nabble.com/problems-with-opening-files-due-to-file%27s-pat... > Sent from the Python - python-list mailing list archive at Nabble.com. Yeah. You need to either double all the backslashes or make it a raw string by adding an "r" to the beginning, like so: os.startfile(r'C:\path\to\my\file') HTH Mike From mdw at distorted.org.uk Thu Jun 19 11:39:05 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Thu, 19 Jun 2008 15:39:05 +0000 (UTC) Subject: advanced listcomprehenions? References: <717129b5-d92f-4be2-ae6a-037870bfa407@2g2000hsn.googlegroups.com> Message-ID: Duncan Booth wrote: > [['Fizz', 'Buzz', 'FizzBuzz', str(i)][62/(pow(i, 4, 15) + 1)%4] for i in > xrange(1, 101)] Cute! ;-) -- [mdw] From inq1ltd at inqvista.com Sat Jun 14 12:00:20 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Sat, 14 Jun 2008 12:00:20 -0400 Subject: sorting a file In-Reply-To: References: Message-ID: <200806141200.20767.inq1ltd@inqvista.com> On Saturday 14 June 2008 03:15, Beema shafreen wrote: > Hi all, > > I have a file with three columns i need > to sort the file with respect to the third > column. How do I do it uisng python. I > used Linux command to do this. Sort but i > not able to do it ? can any body ssuggest > me I have used this method to solve similar problems. This is a consept of how to do what you want, but you will have to work a little to get it right. You might try something like this; Dict = {} ##create a dictionary make a list of all column3 values for loop colum3 values Make these values the key in a dictionary If the values are long, you can use the first 7 to 15 characters if you want. use this key to equal all the values in the other columns on the same row. Dict[column3] = column1, column2, column3 once the dictionary is made get the dictionary key x = Dict.keys() ## get the keys from Dict x.sort() # produce a sorted list of keys of column3 Loop these sorted keys to extract from the dictionary the values related to each jim-on-linux http://:inqvista.com From workitharder at gmail.com Mon Jun 9 01:41:50 2008 From: workitharder at gmail.com (bukzor) Date: Sun, 8 Jun 2008 22:41:50 -0700 (PDT) Subject: Q re documentation Python style References: Message-ID: On Jun 8, 2:17?pm, kj wrote: > I'm a Perlhead trying to learn the Way of Python. ?I like Python > overall, but every once in a while I find myself trying to figure > out why Python does some things the way it does. ?At the moment > I'm scratching my head over Python's docstrings. ?As far as I > understand this is the standard way to document Python code. ?I > think that's fine for simple functions, but I have some functions > that require a very long docstring to document, and somehow I find > it a bit disconcerting to stick a few screenfuls of text between > the top line of a function definition and its body. ?I guess I'm > still a lot more comfortable with Perl's POD, which allows more > flexibility on the placement of the documentation relative to the > source code. > > I expect that the reply to this quibble about very long docstrings > will be something like: if your function requires several screenfuls > of text to document, then it is too complex or it is doing too > much; refactor it into a collection of simpler functions that will > have shorter docstrings. > > Fair enough. ?In general I agree with this sentiment, except that > I think that sometimes even simple functions require a lot of > documentation. ?For example, I want to document a function that > takes a dictionary as argument, and this dictionary is expected to > have 5 keys. ?(When the number of mandatory arguments gets above > 4, I find that it's too difficult to remember their order, so I > resort to using a dictionary as the single argument.) ?The semantics > for each of these keys needs to be described. ?Plus, of course, I > need to describe what the function returns. ?That's a few screenfuls > right there... > > I guess this is a rambling way to ask: are docstrings *it* as far > Python documentation goes? ?Or is there a second, more flexible > system? > > Then again, I suppose that Python's relative formal rigidity is > considered by many to be a strength. ?Which means that, to be > comfortable with Python, one has to learn to like this (relatively) > rigid structure... > > But I thought I'd ask. ?:) > > Kynn > > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. you can assign a documentation string to the function's .__doc__ attribute. This allows you to place your documentation lower in the script, or higher if you use an extra variable. From Code4Hunter at gmail.com Tue Jun 24 21:30:26 2008 From: Code4Hunter at gmail.com (CodeHunter) Date: Tue, 24 Jun 2008 18:30:26 -0700 (PDT) Subject: how to convert '8868' to u'\u8868' Message-ID: <5268385d-04c7-4726-ab55-0f729ce8d883@a9g2000prl.googlegroups.com> a = '8868' b = u'\u8868' I want to convert a to b who can help me ? thank you very much! From casevh at gmail.com Wed Jun 18 01:08:18 2008 From: casevh at gmail.com (casevh) Date: Tue, 17 Jun 2008 22:08:18 -0700 (PDT) Subject: Multiprecision arithmetic library question. References: Message-ID: <183f26a3-26a2-4cf3-8b21-6e2bff4b9c63@a32g2000prf.googlegroups.com> On Jun 17, 5:13?pm, Michael Press wrote: > I already compiled and installed the GNU multiprecision library > on Mac OS X, and link to it in C programs. > How do I link to the library from Python? > I do not want to download and install redundant material. > (I am new to Python) > > -- > Michael Press GMPY provides the interface between Python and GMP. It is available at http://code.google.com/p/gmpy/downloads/list casevh From fairloophole at gmail.com Thu Jun 5 05:11:35 2008 From: fairloophole at gmail.com (Fair Loophole) Date: Thu, 5 Jun 2008 02:11:35 -0700 (PDT) Subject: BetFair Loophole Message-ID: "How Our Simple Betfair System Turned ?100 Into ?1,123 in Just 7 Days..." Over 1,000 customers can't be wrong: the Only System For 9-to-5ers With Little Capital and Time... Fellow Punter, Have you ever felt that it's impossible to make good money from Betfair? Well, I'm here to tell you that it is possible - but only if you abandon everything you know and focus on a "hidden" Betfair market that 90% of punters have never even noticed existed. You're about to discover how you can clone my "hands-off" Betfair formula, proven to generate as much as ?1100 in 7 days, and designed specifically for Betfair punters who have very little starting capital and full-time jobs. I'm also going to explain to you why 90% of the current systems on the market just don't work for the "average Betfair punter". You see, it took me nearly 3 years of sweat, toil, money and time but it paid off... I finally found and fine tuned a Betfair system that has been proven to generate daily profits of upto ?180: Prove it to yourself 100% risk free - you can paper trade the system first to test it out and if you don't like it or it doesn't do everything we say it does you get your money back, no quibbles, no questions, no hard feelings. A system that fits in perfectly with your 9-5 and can generate profits from a starting bank as small as ?25 - you choose how you much you want to make and when. A system that works because it takes advantage of a "hidden" market on Betfair - you work the system for 10 minutes, and siphon off your daily tax-free profits. It's as simple as that. You need to forget everything you've heard about betting systems because I am about to expose a massive underexploited opportunity that is happening right now on Betfair - an opportunity so significant that it could enable you to earn a second income from home by copying an easy step-by-step blueprint... stay with me.. I'm about to reveal it to you... " 3,000 Students, The Secret to Betfair Success ..." My name is Chris and I have trained up over 3,000 Betfair Punters over the last 3 years, beginner and Betfair pro's alike - using my famed Easy Trader Pro System. Through my EasyTrader site, I have interacted with thousands of punters, allowing me to refine my methods and constantly distil what works on Betfair and why. In short, I understand better than anyone what stands between you and a consistent second income from Betfair. Experience has taught me a few very important things about Betfair (stuff that 90% of punters aren't privvy to) - and so when I say I have discovered the ultimate Betfair opportunity, you should listen closely... Please click below for further details:- http://tubeurl.com/ntkwoy From Scott.Daniels at Acm.Org Mon Jun 23 23:09:32 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 23 Jun 2008 20:09:32 -0700 Subject: Passing arguments to subclasses In-Reply-To: <2tlv54d9efp5tngf51oeadin5e0crh3kai@4ax.com> References: <7pgv54l0pfaa2l05c4l8f3bld1rskd4dtf@4ax.com> <2tlv54d9efp5tngf51oeadin5e0crh3kai@4ax.com> Message-ID: <6K6dnSv0d_qH_v3VnZ2dnUVZ_tvinZ2d@pdx.net> John Dann wrote: > ... the answer might have been of the 'yes, but' kind. Well, if you really care, there is a 'yes, but' answer, but it only has to do with multiple inheritance, and hence is a bit esoteric for the issues you are currently addressing. This is not meant to be a tease; I think it would take pages to address the issue in a comprehensible way for someone who hasn't thought about the issues. If you are curious enough to pursue it, image some issues, design experiments, and see if you can ask a coherent question; if not, "YAGNI" (You Aint Gonna Need It). --Scott David Daniels Scott.Daniels at Acm.Org From tamim.shahriar at gmail.com Mon Jun 2 23:31:57 2008 From: tamim.shahriar at gmail.com (subeen) Date: Mon, 2 Jun 2008 20:31:57 -0700 (PDT) Subject: python blogs References: <19d5037f-837d-4f6b-9e56-d4e6d84b277d@y22g2000prd.googlegroups.com> Message-ID: <40851745-15d0-4963-8219-4f0e93953c03@m45g2000hsb.googlegroups.com> On Jun 3, 8:43 am, Benjamin wrote: > On Jun 2, 1:49 pm, pythonbl... at gmail.com wrote: > > > Hello! > > > It seems like Python blogs are gaining popularity. It seems to me that > > they play a crucial role in promoting Python as a language. > > Do you agree with that? > > > Just a few days ago I've finished setting up a dedicated Python > > blogging environment at:http://www.pythonblogs.com > > Do you think it will be useful for Python community? > > By the way, everyone is welcome to join. > > Thanks very much, but the extension says it's written in PHP! > > > > > Sincerely yours, > > ~pyblog A separate place for python blog - the idea is good. I also think that python blog will help python to be more popular. You can also take a look at my blog: http://love-python.blogspot.com/ and suggest me how to make it better. regards, Subeen. From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 9 05:22:12 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 09 Jun 2008 11:22:12 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <4847d39d$0$7614$426a74cc@news.free.fr> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> Message-ID: <484cf5f6$0$15495$426a74cc@news.free.fr> Russ P. a ?crit : > On Jun 6, 8:25 am, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: > >>>>> I also realize, by the way, that Python allows a client of a class to >>>>> define a new class member from completely outside the class >>>>> definition. Obviously, that cannot be declared private. >>>> Why so ? >>> Why should the client of a class not be able to declare a *private* >>> member of the class? You're kidding, right? >> I'm dead serious. I often add implementation attributes to either a >> class or an instance. These *are* implementation parts, not API. > > If a client accesses a data member of a class, Please stop thinking in C++. This is Python, and all you have are attributes. Whether they're callable of not doesn't change much here. > then by definition that > member is not really private, Who cares about it being "private" ? The important point is that it's *implementation*, not *interface*. > so letting the client create a new data > member and declare it as private seems a bit silly to me. There are two ways to decorate a class or instance object (nb: Python's classes are objects too): the "static" way where you wrap the object in a decorator class or instance and use delegation, and the "dynamic" way where you just modify the original class or object at runtime. The fact that an attribute is added (or replaced) outside the class statement doesn't mean it has to be part of the interface. You sometime have pretty legitimate reason to modify the implementation at runtime. > Actually, > just letting the client create the new data member, private or not, > seems like a bit of a stretch to me, but I'll leave that be. You're way too much in the Java/C++ way of thinking. >>> For the record, I have made it abundantly clear that I don't think >>> Python should not have as rigorous an encapsulation regime as C++ or >>> Java. The worst that could happen with my proposition is that you >>> would need to use a "mangled" name to access private data or methods. >> That's already the case - when you use __name_mangling. And if there's >> no effective access restriction, then what the point of having this >> 'priv' keyword ? >> >>> But you will be using the name many times, you can reassign your own >>> name, of course, so the mangled name need not appear more than once >>> where it is needed. >> Once again, I just don't see the point. Either you want effective access >> restriction in Python, or you don't. And if you don't, what would this >> 'priv' keyword be useful to ? > > In the end, I suppose it boils down to aesthetics and personal > preference. > > The leading-underscore convention bothers me for two reasons: (1) like > the OP, I don't like the way it makes my code look, and (2) it is a > signal to a person reading the code, but it has no actual effect in > the interpreter. Indeed. The target of the signal is definitively the person reading the code. > I think the concept of private data and methods is important enough to > be implemented with more than just a tacky naming convention. The concept of "private" attributes is not important. What's important is the concept of implementation attributes. > That is > why I suggested the "priv" keyword. At the same time, I realize that > people will occasionally be frustrated if they are rigorously denied > access to all private data, which is why I suggested an "indirect" > method of access through mangled names. We already have all this. Either you want language-enforced access restriction - then you might be happier with another language - or you just want to have a clear way to know whether an attribute is part of the API or not - in which case a naming convention is not only enough, but even better. > You can argue that such indirect access defeats the whole idea of > private data, but at least it alerts the client to the fact that he > (or she or it) is accessing private data So does the naming convention, with much less work. > -- and it does so without > using Hungarian notation. I wouldn't label this "hungarian notation" - or at least, not the way "hungarian notation" is now commonly understood. > I would let the "priv" keyword also be used for data or functions at > file scope. It just seems logical to me. Again, some name mangling > convention could be concocted for those who think they really need > access. > > Actually, the whole objection to denied access baffles me a bit. Free your mind from the very peculiar, restricted and IMHO braindead conception of "OO" they taught you with Java and C++. Python is older than Java, it's by now a very very commonly used language on all major platforms, and experience prooves that you just don't need anything more than a simple naming convention. > Does > anyone object to not having access from outside a function to local > variables within the function? I doubt it. The other thing is that the > vast majority of Python software, I would guess, is provided with > source code. How many Python applications or libraries are provided > without source code? If you have the source code, you can obviously > just delete the "priv" keyword anywhere or everywhere it appears. Yes, fine. And then have to maintain a fork of the source code, and distribute it with the application. Honking great idea. doh :-( > And > if you have a major client who insists on access to all the internals, > just delete all occurrences of "priv" before you ship the code (or > don't use it to start with). Or don't even bother about this useless access restriction stuff. Which will save you quite a lot of valuable time. From schickb at gmail.com Tue Jun 24 18:29:52 2008 From: schickb at gmail.com (schickb) Date: Tue, 24 Jun 2008 15:29:52 -0700 (PDT) Subject: Sequence iterators with __index__ Message-ID: I think it would be useful if iterators on sequences had the __index__ method so that they could be used to slice sequences. I was writing a class and wanted to return a list iterator to callers. I then wanted to let callers slice from an iterator's position, but that isn't supported without creating a custom iterator class. Are there reasons for not supporting this generally? I realize not all iterators would have the __index__ method, but that seems ok. In Python 3, maybe this could be called a SequenceIterator -Brad From tjreedy at udel.edu Wed Jun 11 16:51:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Jun 2008 16:51:28 -0400 Subject: My fight with classes :) References: <484fde63_1@news.tm.net.my> Message-ID: "TheSaint" wrote in message news:484fde63_1 at news.tm.net.my... | Hi, | I'm very new with classes. I still reading something around ;) | | I got started to try a concatenation of 2 type of string, which have a | particular property to start with A or D. | | My class here: | """ Small class to join some strings according to the leading first | letter""" You left out the class statement. | def __init__(self): | self.valueA= '' | self.valueD= '' | | def __add__(self, value): I agree with P. Pearson that 'add' methods should generaly not be used for mutation. Certainly, they are generally used to combine two objects of the same or compatible classes, even if the result replaces one of them. This method is equivalent to list.append. | if not isinstance(value, str): return Do you really want to just return None when there is bad input? | if value.lower().startswith('a'): | self.valueA += value | if value.lower().startswith('d'): | self.valueD += value | return self.valueA ,self.valueD List mutation methods return None so one cannot forget that they mutate. In any case, the alternative is to return self. You seem to be returning this tuple because you did not write an __str__ method. Doing two different things in one method is what got you in trouble. So return None or self and add def __str__(self): return self.valueA + ', ' + self.valueB | __call__= __add__ | __iadd__= __add__ This requires that __add__ return self. Better to use .append() and def __iadd__(self, val): self.append(val) return self | my test on the shell: [snip good tests] | >>> k += 'liu' k is now a tuple! Hence the below | >>> k += 'aliu' | Traceback (most recent call last): | File "", line 1, in | TypeError: can only concatenate tuple (not "str") to tuple | >>> k | ('aksaboi', 'daksdhksduboi') | Do I miss something? That augmented assignment is assigment. Always. You are not the first ;-)/ | I'd rather like to avoid class, but a function won't allow me to store so | easily data between several call. Classes are the general mechanism for bundling stored data and functions. You can easily bundle *one* function and stored data with a nested function. def makeappender(): data = ['',''] def appender(val): return appender For multiple functions, use classes. | Mostly I'd expect to pass to the built instance in a more elaborated | function. Then I mean call will be the primer goal. __call__ can be an alias for append just as well as for __add__. Terry Jan Reedy From rentlong at gmail.com Sat Jun 14 03:19:17 2008 From: rentlong at gmail.com (rent) Date: Sat, 14 Jun 2008 00:19:17 -0700 (PDT) Subject: How to sort very large arrays? References: Message-ID: <4e596cda-8f84-46c5-a5df-b7e8d4ab7942@p25g2000pri.googlegroups.com> On Jun 14, 1:54 am, kj wrote: > I'm downloading some very large tables from a remote site. I want > to sort these tables in a particular way before saving them to > disk. In the past I found that the most efficient way to do this > was to piggy-back on Unix's highly optimized sort command. So, > from within a Perl script, I'd create a pipe handle through sort > and then just print the data through that handle: This is a python clone of your code from a python rookie :) from os import popen p = popen("sort -t '\t' -k1,1 -k2,2 -u > %s" % out_file) for line in data: print >> p, line there is no "die $!" here, I think it is good to let python throw the exception to your console > > open my $out, "|$sort -t '\t' -k1,1 -k2,2 -u > $out_file" or die $!; > print $out $_ for @data; > > But that's distinctly Perlish, and I'm wondering what's the "Python > Way" to do this. > > TIA! > > kynn > > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. From arazak73 at yahoo.com.my Wed Jun 25 00:54:13 2008 From: arazak73 at yahoo.com.my (ajak_yahoo) Date: Wed, 25 Jun 2008 12:54:13 +0800 Subject: Send output to printer Message-ID: <013c01c8d67f$869bfea0$1f01a8c0@RAZAK> Need some help from you all, I already manage to write a program to print a packaging label. The output on screen is as below, Part Number : PWEE1111AA Quantity : 100 pcs Lot Number : 10A2008 Customer : ABC Pte. Ltd. My questions is how can I send this output to my Panasonic KX-P1121 dot matric printer, Is it a module that i can used, previously i wrote my program using foxpro 2.6, i have no experience in python. Regards, Ajak -------------- next part -------------- An HTML attachment was scrubbed... URL: From bob at mellowood.ca Mon Jun 16 23:32:57 2008 From: bob at mellowood.ca (bvdp) Date: Mon, 16 Jun 2008 20:32:57 -0700 Subject: Simple and safe evaluator References: <1de31143-7d8e-42e9-ae9d-8b0a0274ddc3@e53g2000hsa.googlegroups.com> Message-ID: sweeneym at acm.org wrote: > On Jun 17, 8:02 am, bvdp wrote: > >> Thanks. That was easy :) >> >>> The change to the _ast version is left as an exercise to the reader ;) >> And I have absolutely no idea on how to do this. I can't even find the >> _ast import file on my system. I'm assuming that the _ast definitions >> are buried in the C part of python, but that is just a silly guess. >> >> Bob. > > If you just need numeric expressions with a small number of functions, > I would suggest checking the expression string first with a simple > regular expression, then using the standard eval() to evaluate the > result. This blocks the attacks mentioned above, and is simple to > implement. This will not work if you want to allow string values in > expressions though. > > import re > def safe_eval( expr, safe_cmds=[] ): > toks = re.split( r'([a-zA-Z_\.]+|.)', expr ) > bad = [t for t in toks if len(t)>1 and t not in safe_cmds] > if not bad: > return eval( expr ) > Yes, this appears to be about as good (better?) an idea as any. Certainly beats writing my own recursive decent parser for this :) And it is not dependent on python versions. Cool. I've run a few tests with your code and it appears to work just fine. Just a matter of populating the save_cmds[] array and putting in some error traps. Piece of cake. And should be fast as well. Thanks!!! Bob. From madhurrajn at gmail.com Mon Jun 9 10:33:06 2008 From: madhurrajn at gmail.com (Madhur) Date: Mon, 9 Jun 2008 07:33:06 -0700 (PDT) Subject: _POSIX_C_SOURCE Message-ID: Hi, I would like to know the difference between using the C_INCLUDE_PATH and using the -I option with compilers. How are they different? The problem which I am facing is that I am having a source base which uses python. I am currently enabling compile time option _POSIX_C_SOURCE in my Makefile. The compilaiton fails if i include -I option to /usr/include/python2.4 /usr/include/python2.4/pyconfig-32.h:838:1: error: "_POSIX_C_SOURCE" redefined but if i do export C_INCLUDE_PATH=/usr/include/python2.4 I do not face any compilation issues. I would like to know if there is anything i am missing on this. Regards, Madhur From python at rcn.com Sun Jun 15 06:16:10 2008 From: python at rcn.com (Raymond Hettinger) Date: Sun, 15 Jun 2008 03:16:10 -0700 (PDT) Subject: marshal.dumps quadratic growth and marshal.dump not allowing file-like objects References: Message-ID: On Jun 15, 1:04?am, bkus... at gmail.com wrote: > However it seems that marshal.dumps() for large objects has a > quadratic performance issue which I'm assuming is that it grows its > memory buffer in constant increments. Looking at the source in http://svn.python.org/projects/python/trunk/Python/marshal.c , it looks like the relevant fragment is in w_more(): . . . size = PyString_Size(p->str); newsize = size + size + 1024; if (newsize > 32*1024*1024) { newsize = size + 1024*1024; } if (_PyString_Resize(&p->str, newsize) != 0) { . . . When more space is needed, the resize operation over-allocates by double the previous need plus 1K. This should give amortized O(1) performance just like list.append(). However, when that strategy requests more than 32Mb, the resizing becomes less aggressive and grows only in 1MB blocks and giving your observed nasty quadratic behavior. Raymond From brian_vanderburg2 at yahoo.com Mon Jun 30 23:09:45 2008 From: brian_vanderburg2 at yahoo.com (Allen) Date: Mon, 30 Jun 2008 23:09:45 -0400 Subject: PyPy questions Message-ID: I read the website of some information about PyPy, and how a translator translates the RPython code to C/CLI/Java/etc to be compiled to a native executable or something like that. Would it be possible, in PyPy, to write such an extension that could easily be compiled to native code from Python code? Is this functionality planned in a future release of it? Also, how is the source distributed (If I opt to use it I will end up compiling it on a system without an initial python install (a scratch linux system)), so does the source include the generated C code? B. Vanderburg II From david at hlacik.eu Wed Jun 4 14:49:32 2008 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Wed, 4 Jun 2008 20:49:32 +0200 Subject: python: error , ('No module named py', ), No module named py Message-ID: Hello, what this beautifull mesage which is messing me whole day means : *python: error , ('No module named py',), No module named py* as a result of class pdg.py which is called from nnrpd_auth.py. To be detailed ... news server inn is calling that when doing autentification , it calls nnrpd_auth.py where instance of my class is hooked into inn , when authentification begins it calls method authenticate(arguments) from pdg. I will provide as many information as needed to solve this mistery, becouse i really need to solve it. Thanks! #!/usr/bin/env python import ldap from nnrpd import syslog class news: server = 'ldap://dev01.net.hlacik.eu' user_dn = 'cn=pdg,ou=Operators,o=Polarion' user_pw = 'Pdg1' connectcodes = { 'READPOST':200, 'READ':201, 'AUTHNEEDED':480, 'PERMDENIED':502 } authcodes = { 'ALLOWED':281, 'DENIED':502 } def newsauth(self,match_username,match_password): base_dn = 'ou=Users,o=Polarion' filter = "(uid=" + match_username + ")" attrs = ['userPassword'] try : l = ldap.initialize(self.server) l.bind_s(self.user_dn, self.user_pw) raw_res = l.search_s( base_dn, ldap.SCOPE_SUBTREE, filter, attrs ) l.unbind() except ldap.SERVER_DOWN: print "Error, server down" return 2 except ldap.INVALID_CREDENTIALS: print "Error, invalid credentials" return 2 except ldap.LDAPError, e: print "Error, %s" % e for results in raw_res: (cn,search) = results for password in search["userPassword"]: if password == match_password: return 1 return 0 def authenticate(self, attributes): # just for debugging purposes syslog('notice', 'nnrpd_auth authenticate() invoked: hostname %s, ipaddress %s, interface %s, user %s' % (\ attributes['hostname'], \ attributes['ipaddress'], \ attributes['interface'], \ attributes['user'])) try: syslog('notice', "result %s" % self.newsauth('boss','bbbb')) except Exception, msg: syslog('notice', "error %s, %s, %s" % (type(msg),msg.args,msg)) # do username passworld authentication #if self.newsauth(attributes['user'], str(attributes['pass'])): # syslog('notice', 'authentication by username succeeded') # return ( self.authcodes['ALLOWED'], 'No error' ) #else: # syslog('notice', 'authentication by username failed') # return ( self.authcodes['DENIED'], 'Access Denied!') ------------------- nnrpd_auth_py : # # This is a sample authentication and authorization module for python # nnrpd hook # # For details, see the file doc/hook-python that came with INN. # # # This file is loaded when one of the python_* readers.conf parameters # is encountered. An instance of AUTH class is passed to nnrpd via # set_auth_hook() function imported from nnrpd. The following methods # of that class are known to nnrpd: # # __init__() - Use this method to initilalize your # general variables or open a common # database connection. May be omitted. # access_init() - Init function specific to access # control. May be omitted # access(attributes) - Called when a python_access # statement is reached in the # processing of readers.conf. Returns # a dictionary of values representing # statements to be included in an # access group. # access_close() - Called on nnrpd termination. Save # your state variables or close a # database connection. May be omitted # authen_init() - Init function specific to # authentication. May be omitted # authenticate(attributes) - Called when a python_auth statement # is reached in the processing of # readers.conf. Returns a response # code, an error string and an # optional string to appear in the # logs as the username. # authen_close() - Called on nnrpd termination. Save # your state variables or close a database # connection. May be omitted # dynamic_init() - Init function specific to # authentication. May be omitted # dynamic(attributes) - Called whenever a reader requests either # read or post access to a # newsgroup. Returns None to grant # access, or a non-empty string (which # will be reported back to reader) # otherwise. # dynamic_close() - Called on nnrpd termination. Save # your state variables or close a database # connection. May be omitted # # If there is a problem with return codes from any of these methods then nnrpd # will die and syslog the exact reason. # # There are also a few Python functions defined in nnrpd: # # set_auth_hook() - Called by nnrpd as this module is loaded. # It is used to pass a reference to an # instance of authentication class to nnrpd. # syslog() - An equivalent replacement for regular syslog. # One consideration for using it is to # uniform nnrpd logging. # # Sample authentication and authorization class. It defines all methods known # to nnrpd. # # Import functions exposed by nnrpd. This import must succeed, or nothing # will work! from nnrpd import * from pdg import * myauth = news() # ...and try to hook up on nnrpd. This would make auth object methods visible # to nnrpd. try: set_auth_hook(myauth) syslog('notice', "authentication module successfully hooked into nnrpd") except Exception, errmsg: syslog('error', "Cannot obtain nnrpd hook for authentication method: %s" % errmsg[0]) -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhamph at gmail.com Mon Jun 9 05:14:53 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 9 Jun 2008 02:14:53 -0700 (PDT) Subject: Trying out safethread patch References: Message-ID: <849dc1ee-ab31-4b85-a521-7406534d6529@x1g2000prh.googlegroups.com> On Jun 8, 9:55 am, s... at pobox.com wrote: > I'd like to take the python-safethread code out for a spin, but I'm not sure > where to start. I downloaded the latest diff: > > http://python-safethread.googlecode.com/files/safethread-bzr-36020.diff > > checked out Python 3.0 from the bzr mirror, then ran patch in the typical > way. That doesn't apply cleanly at all (too much water under the bridge > since this the patch was made). I was thinking if I back up my bzr > repository to r36020, apply the patch then sync with the latest bzr revision > that might work, but I have no bzr experience. I haven't any idea how to do > that. Any suggestions? Yeah, the 36020 in the file name indicates the bzr revision that matches. Going into the branch and using "bzr pull -r 36020" should be sufficient. However, do *not* sync with the latest upstream version after patching - there WILL be conflicts. Dealing with a merge isn't congruent with taking it for a spin. ;) From eatrnr at gmail.com Sat Jun 7 16:05:18 2008 From: eatrnr at gmail.com (eatrnr at gmail.com) Date: Sat, 7 Jun 2008 13:05:18 -0700 (PDT) Subject: Need help porting Perl function References: Message-ID: On Jun 7, 2:42?pm, "Daniel Fetchinson" wrote: > > Hi. ?I'd like to port a Perl function that does something I don't > > know how to do in Python. ?(In fact, it may even be something that > > is distinctly un-Pythonic!) > > > The original Perl function takes a reference to an array, removes > > from this array all the elements that satisfy a particular criterion, > > and returns the list consisting of the removed elements. ?Hence > > this function returns a value *and* has a major side effect, namely > > the target array of the original argument will be modified (this > > is the part I suspect may be un-Pythonic). > > > Can a Python function achieve the same effect? ?If not, how would > > one code a similar functionality in Python? ?Basically the problem > > is to split one list into two according to some criterion. > > This function will take a list of integers and modify it in place such > that it removes even integers. The removed integers are returned as a > new list (disclaimer: I'm 100% sure it can be done better, more > optimized, etc, etc): > > def mod( alist ): > ? ? old = alist[:] > ? ? ret = [ ] > ? ? for i in old: > ? ? ? ? if i % 2 == 0: > ? ? ? ? ? ? ret.append( alist.pop( alist.index( i ) ) ) > > ? ? return ret > > x = range(10,20) > > print x > r = mod( x ) > print r > print x > > HTH, > Daniel > -- > Psss, psss, put it down! -http://www.cafepress.com/putitdown def mod( alist ): return [ alist.pop( alist.index( x ) ) for x in alist if x % 2 == 0 ] alist = range(10,20) blist = mod( alist ) print alist print blist The same thing with list comprehensions. From socyl at 987jk.com.invalid Fri Jun 6 18:00:36 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 6 Jun 2008 22:00:36 +0000 (UTC) Subject: How to send a POST request? Message-ID: Hi. Sorry for this very clueless question, but how does one write in Python an HTTP client that can send a POST request? The modules I've found (e.g. urllib, urllib2), as far as I can tell, seem to be limited to GET requests. (I could be wrong though; please correct me if this is so.) TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From lists at cheimes.de Fri Jun 27 11:47:24 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 27 Jun 2008 17:47:24 +0200 Subject: Use of the "is" statement In-Reply-To: <4865098A.3070502@islandtraining.com> References: <4865098A.3070502@islandtraining.com> Message-ID: Gary Herron wrote: > In short: *never* use "is". Never use "is" unless you want to check "if something is None or something is not None" Christian From mensanator at aol.com Tue Jun 10 19:45:59 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 10 Jun 2008 16:45:59 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> <484ad07b$0$25721$607ed4bc@cv.net> <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> <484b3464$0$25724$607ed4bc@cv.net> <09d98480-c834-42bd-b97f-481133be9cb4@s50g2000hsb.googlegroups.com> <77d2d56a-7ab6-4d33-81d4-b15cc8fc63d6@u36g2000prf.googlegroups.com> Message-ID: On Jun 10, 6:09?pm, Lie wrote: > On Jun 8, 11:11?pm, Mensanator wrote: > > > > > > > On Jun 8, 4:04?am, Lie wrote: > > > > On Jun 8, 8:56?am, Mensanator wrote: > > > > > On Jun 7, 8:22?pm, John Salerno wrote: > > > > > > Mensanator wrote: > > > > > > What I DID say was that how the builtins actually > > > > > > work should be understood and it APPEARED that the > > > > > > OP didn't understand that. Maybe he understood that > > > > > > all along but his example betrayed no evidence of > > > > > > that understanding. > > > > > > Well, the truth is that I know zip truncates to the shorter of the two > > > > > arguments, > > > > > Ok, sorry I thought otherwise. > > > > > > and also in my case the two arguments would always be the > > > > > same length. > > > > > Yes, because you're controlling the source code. > > > > But since lists are mutable, source code literals > > > > don't always control the length of the list. > > > > Since when source code literals ever control the length of a list? > > > Isn't score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] > > considered a literal? > > Yep, but it's not the sole controller of the length of a list. There > are other things that might control the length of the list like del, > append, etc. I believe I just said that. Perhaps I should have said at the instant it's created, the length is determined by the literal. Remember, score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] is preceeded by range(11), so of course AT THAT INSTANT, the lengths match. But, as you say, there's no guarantee that the list lengths will remain unchanged. And that's why I'm saying it isn't necessarily a good idea to assume that. For the way it's used, the zip function IS assuming that. > > > > What controls the length of the list is the semantic meaning of the > > > list, > > > Wha do you mean by that? The list contains 11 objects. > > How could the length be any different? > > What I meant is in some cases (not all) the list might semantically be > nonsense if it is of different length (i.e. it have fixed length). Sure, but remember, the OP was asking how to do this in a list comprehension where he doesn't have the option of iterating through both lists like he does with zip. When I mentioned that could be solved by enumerate, I said it simultaneously guaratees that the index numbers automatically end up the same length as the target list and avoids the hypothetical case where the list lengths somehow don't match. Of course nothing can be done if the actual list length is semantically nonsense and you actually might need to exploit the truncating of the list to a fixed range. But there are many cases where you DON'T want that to happen (if you deposit 5 checks at the bank, you certainly want credit for ALL of them, not just some idiot's notion that only 4 can be deposited in a single transaction.) > > > > in some cases it just makes no sense that the list would ever > > > have different length. > > > And in such case there won't be any problem, will there? > > > Is that a good habit to teach a newbie? To write > > code that only works for special cases? > > I think it is up to the programmer to decide whether special case is > enough or a general case is necessary. Yes, he can certainly decide. Provided he knows what all the options are. There's no way to tell if the OP understands what the options are. I say it's always better to supply too much information than not enough. Assume the reader is clever enough to seperate the wheat from the chaff. If it turns out he's not, then I at least _I_ will be blameless. From socyl at 987jk.com.invalid Sat Jun 7 15:34:05 2008 From: socyl at 987jk.com.invalid (kj) Date: Sat, 7 Jun 2008 19:34:05 +0000 (UTC) Subject: Need help porting Perl function References: Message-ID: >This function will take a list of integers and modify it in place such >that it removes even integers. The removed integers are returned as a >new list Great! Thanks! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From omer at no-log.org Sun Jun 29 15:24:15 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Sun, 29 Jun 2008 21:24:15 +0200 Subject: Function to import module to namespace In-Reply-To: References: Message-ID: <200806292124.15811.omer@no-log.org> Le Sunday 29 June 2008 21:08:36 bvdp, vous avez ?crit?: > Is it possible to do this from a function: import a module and append > the defs in that module to an existing module/namesapce. > > So, in my code I have something like: > > # main code > import mods > > def loadmore(n): > import_module(n, mods) > > .... > # end of main > > this will permit the addition of the the stuff in file 'n.py' to 'mods'. > > Assuming that foo1() is defined in newmod, I should now be able to do > something like mods.foo1(). > You can dynamically add objects to a module: >>> import os >>> os.foo = 'bar' >>> os.foo 'bar' >>> setattr(os, 'foo2', 'bar2') >>> os.foo2 'bar2' and for the loading part you can use the __import__ builtin or maybe execfile (see the 'built-in functions' chapter of the library reference for more about these). -- C?dric Lucantis From __peter__ at web.de Thu Jun 12 10:03:39 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Jun 2008 16:03:39 +0200 Subject: Plotting Graphs using Gnuplot References: <17f71342-0cc4-4eea-b99a-668096302b8b@a70g2000hsh.googlegroups.com> Message-ID: arslanburney at gmail.com wrote: > Hello. Was trying to create a simple plotting function. Wasnt working > however. If i write the same code without putting it inside a function > it works. :S. Could some1 tell me the problem? Judging from the demo you have to keep a Gnuplot.Gnuplot instance alive. If you don't, the display window is immediately garbage-collected. > Heres the code: > > > # File name Plotting2 > > import Gnuplot > > def plot(original, expected, actual): > > > if type (original) != type([]): > return False > > else: > > gp = Gnuplot.Gnuplot() > gp('set data style lines') > > > # Make the plot items > plot1 = Gnuplot.PlotItems.Data(original, title="Original") > plot2 = Gnuplot.PlotItems.Data(expected, title="Expected") > plot3 = Gnuplot.PlotItems.Data(actual, title="Acutal") > > gp.plot(plot1, plot2, plot3) return gp > > > ---- > > import Plotting2 #The name of my file... > gp = Plotting2.plot( [(2,3), (3,4)], [(4,5), (5,6)], [(1,3), (4,8)] ) raw_input() By the way, I recommend that you raise an Exception instead of returning a special value when plot() cannot deal with the arguments passed to it. Peter From cmpython at gmail.com Sun Jun 8 23:24:50 2008 From: cmpython at gmail.com (CM) Date: Sun, 8 Jun 2008 20:24:50 -0700 (PDT) Subject: How to close app after x seconds. References: Message-ID: <6f16a047-32ea-4e72-9870-1f80f7673f55@8g2000hse.googlegroups.com> On Jun 8, 8:51 pm, ralphz wrote: > Hi > > I have small app that I want to close tself after x seconds. Basically > start show some message and close. > > I come up with something like this but it does not work. Can anyone help > me with it? > > #!/usr/bin/env python > > import wx > import time > > class MyFrame(wx.Frame): > def __init__(self, title, pos, size): > wx.Frame.__init__(self, None, -1, title, pos, size) > self.CreateStatusBar() > self.SetStatusText("Some message here") > > class MyApp(wx.App): > def OnInit(self): > > self.frame = MyFrame('TITLE', (100, 100), (400,100)) > self.frame.Show() > > self.SetTopWindow(self.frame) > self.ID_Timer = wx.NewEventType() > self.timer = wx.Timer(self, self.ID_Timer) > self.timer.Start(5000, False) > self.Bind(wx.EVT_TIMER, self.appclose, self.timer) > # wx.EVT_TIMER(self, self.ID_Timer, self.appclose) > return True > > def appclose(self, evt): > self.frame.Destroy() > > if __name__ == '__main__': > app = MyApp(0) > app.MainLoop() > > Ralphhttp://TheOrangeIT.org It works for me just fine. How is it not working for you? By the way, showing your message in the statusbar is not a good display method--it's small and it is only seen in conjunction with a frame above it that is doing something. You could just put the message as staticText. From mail at timgolden.me.uk Fri Jun 13 06:44:29 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 13 Jun 2008 11:44:29 +0100 Subject: How to set directory in save as combo box In-Reply-To: <000a01c8cd11$c5566210$2fc513ac@pwit.com> References: <000a01c8cd11$c5566210$2fc513ac@pwit.com> Message-ID: <48524F8D.4040406@timgolden.me.uk> Couple of things, Gopal, which you might want to remember when posting to mailing lists etc. One is that it's *much* better (and more considerate) to post in plain text, not in HTML. (You should be able to tell Outlook to use plain text). *Especially* when posting code. And even *more* especially when posting Python code where the layout is uber-important. The other thing is that top-posting is not the norm in this group, although it may be in others. The usual thing is to trim the email you're replying to (or the newsgroup post or GGroup entry) so that only the relevant text remains, and then put your replies beneath or interspersed depending on what makes sense. Now to the code itself: > I am trying to save a file, it is working fine. > > But if the file is not on the foreground while setting combo box > directory, changing the value in the combo box by setLookIn() appear on > the foreground window. [... snip code which finds a "Save As" window and sends it mouse messages ...] I'm honestly not sure what you're trying to achieve here. I assumed that *your* application was initiating the "Save As..." dialog. But this code looks as though you're trying to automate some *other* application's dialog box. Can you explain better what's going on? Trying to poke values into other application's windows is fragile at best, but if that's really what you want to do, have a look at a couple of projects which specialise in that kind of thing: + WATSUP: http://www.tizmoi.net/watsup/intro.html + PyWinAuto: http://pywinauto.openqa.org/ Trying to poke values into *your own* application's windows is entirely suspect: there's almost certainly a better way of doing it. TJG From nick at craig-wood.com Tue Jun 24 08:32:12 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 24 Jun 2008 07:32:12 -0500 Subject: calling a .exe from Python References: Message-ID: evidentemente.yo wrote: > Hi, i am trying to call a .exe from my .py file, i have found the exec > function, but i'm not sure of how to use it:S > > would it be f.e.: > > execl (mypath/myfile.exe,myfile,arg1,arg2,...) > > ???? > > Another question is, when i call my .exe with exec, i understand that > my .py file will stop running, and instead the new process will be > launched instead of it. Is it true? > Is there a way to launch my .exe without finishing my .py file?? > > thank you very much:) Probably what you want is this... from subprocess import call rc = call(["mypath/myfile.exe",arg1,arg2]) rc will contain the exit status See the subprocess module for more things you can do -- Nick Craig-Wood -- http://www.craig-wood.com/nick From fc14301589 at icqmail.com Wed Jun 11 10:28:04 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Wed, 11 Jun 2008 22:28:04 +0800 Subject: can't assign to literal References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> <1a244dc4-4d10-491d-8ec7-224f3a1f0df5@m73g2000hsh.googlegroups.com> <8264ea7d-50ce-4fac-9b59-1acbcbafcbb2@w7g2000hsa.googlegroups.com> Message-ID: <484fe17d_2@news.tm.net.my> On 16:47, mercoled? 11 giugno 2008 Chris wrote: > SciTE and Notepad++ Pype, spe, just to point it out. Jedit, but rather a bloatware. I'd like to know which is the litest multi platform and indipendent. Pype is very good when compiled in exe, but not doing in Linux in that way. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From apardon at forel.vub.ac.be Wed Jun 4 03:08:45 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Jun 2008 07:08:45 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <2930ad39-a3ef-49fa-9e37-26ada87f2d95@m44g2000hsc.googlegroups.com> Message-ID: On 2008-06-03, sturlamolden wrote: > On Jun 2, 12:40 pm, Antoon Pardon wrote: > >> I think you completed missed the point. >> >> This is just a proof of concept thing. In a real example there would >> of course no Set en Get methods but just methods that in the course >> of their execution would access or update the hidden attributes > > I have to agree with Banks here, you have not provided an example of > data hiding. It does not discriminate between attribute access from > within and from outside the class. You just assume that the attribute > named 'hidden' will be left alone. Also naming it hidden is stupid as > it is visible. No I don't assume that hidden wil be left alone. hidden is a free variable in a closure and thus simply can't be accessed except by local functions that were made accessible (and some mechanism dependant on the CPython implementation). > What you need is a mechanism that will thrown an exception whenever an > attribue is accessed from outside the class, but not from inside. And my example does this. It threw an AttributeError > The mechanism must also be impossible to override with additional > code. Which as far as I know it is. -- Antoon Pardon From george.sakkis at gmail.com Fri Jun 20 13:07:56 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 20 Jun 2008 10:07:56 -0700 (PDT) Subject: Python "is" behavior References: <02d58c63-f8d8-44a8-ac09-d483a0fa8c0f@v1g2000pra.googlegroups.com> <725bcf7a-3d6a-4a38-a906-bb397bdd447f@26g2000hsk.googlegroups.com> <03a030b7-1d47-4386-9826-435ce936c130@p39g2000prm.googlegroups.com> Message-ID: <537daeff-e283-47bf-b539-3e6c99aabe5a@m45g2000hsb.googlegroups.com> On Jun 20, 12:45 pm, michalis.avr... at gmail.com wrote: > On Jun 20, 9:42 am, George Sakkis wrote: > > > > > On Jun 20, 12:31 pm, michalis.avr... at gmail.com wrote: > > > > I am not certain why this is the case, but... > > > > >>> a = 256 > > > >>> b = 256 > > > >>> a is b > > > > True > > > > >>> a = 257 > > > >>> b = 257 > > > >>> a is b > > > > False > > > > Can anyone explain this further? Why does it happen? 8-bit integer > > > differences? > > > No, implementation-dependent optimization (caching). For all we know, > > the next python version may cache up to 1024 or it may turn off > > caching completely; do not rely on it. More generally, do not use 'is' > > when you really mean '=='. > > > George > > Thank you George. I am very curious about some of these internal > Python things that I keep stumbling upon through friends. And thank > you for all the help! As far it's plain curiosity it's ok, but it's a small implementation detail you shouldn't rely on. There's nothing magic about 256, just the size decided for 2.5. If you tried it on 2.4 you'd get: Python 2.4.2 (#1, Mar 8 2006, 13:24:00) [GCC 3.4.4 20050721 (Red Hat 3.4.4-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a=99 >>> b=99 >>> a is b True >>> a=100 >>> b=100 >>> a is b False I was more surprised by the following: Python 2.5.1 (r251:54863, May 8 2007, 14:46:30) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a= 123456; b=123456; a is b True For some reason, stacking multiple statements reuses the same object. George From rhamph at gmail.com Tue Jun 10 15:27:52 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Tue, 10 Jun 2008 12:27:52 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <6e6df35e-e641-44d9-9f56-c0732306eec2@q27g2000prf.googlegroups.com> Message-ID: <98ce48ed-c7c7-43c5-8c9c-f08628a2e98e@y22g2000prd.googlegroups.com> On Jun 10, 1:55 am, Antoon Pardon wrote: > On 2008-06-09, Rhamphoryncus wrote: > > > > > On Jun 9, 5:33 am, Antoon Pardon wrote: > >> On 2008-06-07, Rhamphoryncus wrote: > > >> > On Jun 6, 12:44 pm, The Pythonista wrote: > >> >> It's always been my understanding that you can't forcibly kill a thread > >> >> in Python (at least not in a portable way). The best you can do is > >> >> politely ask it to die, IIRC. > > >> > Inherently, the best you can do in most languages is ask them politely > >> > to die. Otherwise you'll leave locks and various other datastructures > >> > in an inconvenient state, which is too complex to handle correctly. > >> > The exception is certain functional languages, which aren't capable of > >> > having threads and complex state in the same sense. > > >> Well it would of course depend on what is considered asking politely? > > >> If one thread could cause an exception being thrown in an other thread, > >> would this be considered a polite way to ask? Would it be considered > >> an acceptable way? > > > The exception must not be raised until a point explicitly designed as > > safe is hit. Otherwise, any function that manipulates data you'll > > still use will potentially be buggered. Consider sys.stdout: codecs, > > buffering, lots to go wrong. > > I don't see the point. Exceptions are raised now without the ability > of an explicitly designed safe point. If something unexpected happens > your code can raise an exception and leave your data buggered too if > you didn't anticipate it propely. Although in theory you could get any exception at any point, in practise you shouldn't unless your program is broken. If it is broken the exceptions shouldn't be caught and should cause the program to terminate, so the harm is reduced. The exceptions that should happen (such as IOError) should be from predicted points, and anticipated. A notable exception is MemoryError, which can show up from anywhere at any time. Nobody's come up with a solution to that one, so we usually just let the program die. Cancelling a thread implies your program will continue. Otherwise you'd just exit the whole process (either via _exit() or via daemon threads.) From armin.ronacher at active-4.com Wed Jun 18 06:47:44 2008 From: armin.ronacher at active-4.com (Armin Ronacher) Date: Wed, 18 Jun 2008 10:47:44 +0000 (UTC) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <4856e80c$0$30401$9b622d9e@news.freenet.de> <2d1e9b84-3dc7-4822-9c61-73991a527c67@s50g2000hsb.googlegroups.com> <48574b41$0$30410$9b622d9e@news.freenet.de> <31defced-c60d-45dc-a32a-af01a2b84c89@2g2000hsn.googlegroups.com> <48583bf9$0$14752$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis v.loewis.de> writes: > > > I think I have lost the thread here, sorry. So I explain again what I > > mean. I think for this data structure it's important to keep all the > > normal dict operations at the same speed. If you use a C > > implementation vaguely similar to my pure python recipe you can > > perform the del in O(1) too, because pairs are joined in (double) > > linked list. But such data structure is O(n) to find the n-th item > > inserted into the sequence. > > Right. So byindex(n) would be O(n) then, right? If so, what's the > purpose of having that method in the first place? What's the purpose of having list.insert? > The PEP doesn't give a rationale, but just proposes that the method > be there. My guess is that it includes it for performance reasons. > However, I think the PEP (author) is misguided in assuming that > making byindex() a method of odict, you get better performance than > directly doing .items()[n] - which, as you say, you won't. Without byindex the only way to cherry pick an item is either doing something like i = od.iteritems() for idx in xrange(offset): value = idx.next() return value Or return od.items()[offset] One creates tons of unnecessary method calls, the other creates a full blown list object just to throw it away later. Both less than optimal solutions that can be implemented in a more efficient way on the C layer where one only has to iterate over the linked list offset times and return the item. And iteration for that linked list is most likely something like "for (n = 0; n != offset; ++n) iter = iter->next". Regards, Armin From ananth99899 at gmail.com Fri Jun 20 12:07:23 2008 From: ananth99899 at gmail.com (www.hollywoodpopstars.blogspot.com) Date: Fri, 20 Jun 2008 09:07:23 -0700 (PDT) Subject: secret WEB CAMS at LADIES HOTELS Message-ID: Hi....Friends, watch and enjoy SECRET WEB-CAMS at LADIES HOSTELS and INTERNET CAFE SEX SCANDALS VIDEOS... http://www.hollywoodpopstars.blogspot.com http://www.googlemobilesphones.blogspot.com From pfreixes at milnou.net Sun Jun 8 06:07:26 2008 From: pfreixes at milnou.net (Pau Freixes) Date: Sun, 8 Jun 2008 12:07:26 +0200 Subject: Different execution time in python code between embedded or standalone In-Reply-To: <207312b70806031258n68b9dfl942e098e5119c1dc@mail.gmail.com> References: <207312b70806031258n68b9dfl942e098e5119c1dc@mail.gmail.com> Message-ID: <207312b70806080307m92fa477s83e9e4d4521b444d@mail.gmail.com> HI list, I found the problem guys, when I embedded python code didn't call to PyEval_InitThreads(); This function initialize GIL and other data structures for do a python code thread safe. I believe the python traditional ( python name_script.py ) run always a thread safe interpreter. Therefore, it's normal found best performance in no thread safe environment and thread safe environment. But I have a small question, if I have a typical PyObject_CallObject environment and main code don't call to PyEval_InitThreads() after Py_Initialize(), if in python code function called launch some threads this interpreter will be prepare for handle more one thread with python thread safe environment, can everybody help me ? Thks On Tue, Jun 3, 2008 at 9:58 PM, Pau Freixes wrote: > Hi list, > > First Hello to all, this is my and hope not end message to the list :P > > This last months I have been writting a program in c like to mod_python > for embedding python language, it's a middleware for dispatch and execute > python batch programs into several nodes. Now I'm writing some python > program for test how scale this into several nodes and comparing with > "standalone" performance. > > I found a very strange problem with one application named md5challenge, > this aplication try to calculate the max number md5 digest in several > seconds, md5challenge use a simple signal alarm for stop program when time > has passed. This is the code of python script > > def handler_alrm(signum, frame): > global _signal > global _nrdigest > global _f > > > _signal = True > > def try_me(): > global _nrdigest > global _f > global _signal > > _f = open("/dev/urandom","r") > while _signal is not True: > buff = _f.read(_const_b) > md5.md5(buff).hexdigest() > _nrdigest = _nrdigest + 1 > > if _f is not None : > _f.close() > > def main( req ): > global _nrdigest > > > signal.signal(signal.SIGALRM, handler_alrm) > signal.alarm(req.input['time']) > > > try_me() > > req.output['count'] = _nrdigest > > return req.OK > > > if __name__ == "__main__": > > # test code > class test_req: > pass > > req = test_req() > req.input = { 'time' : 10 } > req.output = { 'ret' : 0, 'count' : 0 } > req.OK = 1 > > main(req) > > print "Reached %d digests" % req.output['count'] > > > When I try to run this program in standalone into my Pentium Dual Core > md4challenge reached 1.000.000 milion keys in 10 seconds but when i try to > run this in embedded mode md5challenge reached about 200.000 more keys !!! I > repeat this test many times and always wins embedded mode !!! What's > happen ? > > Also I tested to erase read dependencies from /dev/random, and calculate > all keys from same buffer. In this case embedded mode win always also, and > the difference are more bigger !!! > > Thks to all, can anybody help to me ? > -- > Pau Freixes > Linux GNU/User -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Mon Jun 2 00:38:29 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 02 Jun 2008 05:38:29 +0100 Subject: Better performance References: <14a9bf9c-1605-43a1-a6ad-8720c3df06d9@c58g2000hsc.googlegroups.com> Message-ID: Franck Y writes: > Hello Folks, > > I am facing a problem where i need to parse around 200 files, i have a > bit of knowledge in PHP/Perl/Python (the magic P :-P) > > Which one would you suggest me since i have to generate a web > interface ? > And each one has his area of 'work' > > > Thanks for your help ! Python, of course. -- Arnaud From duncan.booth at invalid.invalid Tue Jun 3 04:13:03 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Jun 2008 08:13:03 GMT Subject: Code correctness, and testing strategies References: Message-ID: jacob at cd.chalmers.se (Jacob Hallen) wrote: > The most important aspect of usnit testing is actually that it makes > the code testable. This may sound lik an oxymoron but it is actually a > really important property. Testable code has to have a level of > modularity as well as simplicity and clarity in its interfaces that > you will not achieve in code that lacks automated unit tests. Excellent clear description, thanks Jacob. I made the mistake at one point when I was trying to sell the concept of TDD telling the people I was trying to persuade that by writing the tests up front it influences the design of the code. I felt the room go cold: they said the customer has to sign off the design before we start coding, and once they've signed it off we can't change anything. I wish I'd had your words then. -- Duncan Booth http://kupuguy.blogspot.com From noreply at yahoo.com Wed Jun 25 11:20:04 2008 From: noreply at yahoo.com (Kirk) Date: 25 Jun 2008 15:20:04 GMT Subject: Freeze problem with Regular Expression Message-ID: <6cf614F3f8ocoU1@mid.individual.net> Hi All, the following regular expression matching seems to enter in a infinite loop: ################ import re text = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA) una ' re.findall('[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-z]*\s*(?:[0-9] *[A-Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$', text) ################# No problem with perl with the same expression: ################# $s = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA) una '; $s =~ /[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-z]*\s*(?:[0-9]*[A- Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$/; print $1; ################# I've python 2.5.2 on Ubuntu 8.04. any idea? Thanks! -- Kirk From frigoris.ma at gmail.com Wed Jun 18 21:01:55 2008 From: frigoris.ma at gmail.com (Cong) Date: Wed, 18 Jun 2008 18:01:55 -0700 (PDT) Subject: Looking for lots of words in lots of files References: Message-ID: <38ccf4ff-aa9e-4fda-8fce-bebf85ae96de@q27g2000prf.googlegroups.com> On Jun 18, 11:01?pm, Kris Kennaway wrote: > Calvin Spealman wrote: > > Upload, wait, and google them. > > > Seriously tho, aside from using a real indexer, I would build a set of > > thewordsI'mlookingfor, and then loop over each file, looping over > > thewordsand doing quick checks for containment in the set. If so, add > > to a dict of file names to list ofwordsfound until the list hits 10 > > length. I don't think that would be a complicated solution and it > > shouldn't be terrible at performance. > > > If you need to run this more than once, use an indexer. > > > If you only need to use it once, use an indexer, so you learn how for > > next time. > > If you can't use an indexer, and performance matters, evaluate using > grep and a shell script. ?Seriously. > > grep is a couple of orders of magnitude faster at pattern matching > strings infiles(and especially regexps) than python is. ?Even if you > are invoking grep multiple times it is still likely to be faster than a > "maximally efficient" single pass over the file in python. ?This > realization was disappointing to me :) > > Kris Alternatively, if you don't feel like writing shell scripts, you can write a Python program which auto-generate the desired shell script which utilizes grep. E.g. use Python for generating the file list which is passed to grep as arguments. ;-P From pavel.uvarov at gmail.com Mon Jun 2 11:09:35 2008 From: pavel.uvarov at gmail.com (pavel.uvarov at gmail.com) Date: Mon, 2 Jun 2008 08:09:35 -0700 (PDT) Subject: ThreadPoolingMixIn References: <3d9dac72-ce4d-4ce5-9213-4bb17aff2f9e@r66g2000hsg.googlegroups.com> <1c4d113e-b375-471d-9d54-1401c8844352@t12g2000prg.googlegroups.com> Message-ID: On May 31, 9:13 pm, Rhamphoryncus wrote: > On May 30, 2:40 pm, pavel.uva... at gmail.com wrote: > > > Hi, everybody! > > > I wrote a useful class ThreadPoolingMixIn which can be used to create > > fast thread-based servers. This mix-in works much faster than > > ThreadingMixIn because it doesn't create a new thread on each request. > > Do you have any benchmarks demonstrating the performance difference/ > To benchmark this I used a simple tcp server which writes a small (16k) string to the client and closes the connection. I started 100 remote clients and got 500 replies/s for ThreadingMixIn and more than 1500 replies/s for ThreadPoolingMixIn. I tested it on FreeBSD 6.2 amd64. I'm very curious about the exactness of the number 500 for ThreadingMixIn. It seems to be the same for various packet sizes. I suspect there is some OS limit on thread creating rate. Below I include a bugfixed ThreadPoolingMixIn and the benchmarking utility. The utility can be used to start clients on localhost, though the reply rate will be slower (around 1000 replies/s). To start benchmarking server with localhost clients use: python ./TestServer.py --server=threading --n-clients=100 or python ./TestServer.py --server=threadpooling --n-clients=100 #------- ThreadPoolingMixIn.py from __future__ import with_statement from SocketServer import ThreadingMixIn import threading import Queue class ThreadPoolingMixIn(ThreadingMixIn): """Mix-in class to handle requests in a thread pool. The pool grows and thrinks depending on load. For instance, a threadpooling TCP server class is created as follows: class ThreadPoolingUDPServer(ThreadPoolingMixIn, TCPServer): pass """ __author__ = 'Pavel Uvarov ' def init_thread_pool(self, min_workers = 5, max_workers = 100, min_spare_workers = 5): """Initialize thread pool.""" self.q = Queue.Queue() self.min_workers = min_workers self.max_workers = max_workers self.min_spare_workers = min_spare_workers self.num_workers = 0 self.num_busy_workers = 0 self.workers_mutex = threading.Lock() self.start_workers(self.min_workers) def start_workers(self, n): """Start n workers.""" for i in xrange(n): t = threading.Thread(target = self.worker) t.setDaemon(True) t.start() def worker(self): """A function of a working thread. It gets a request from queue (blocking if there are no requests) and processes it. After processing it checks how many spare workers are there now and if this value is greater than self.min_spare_workers then the worker exits. Otherwise it loops infinitely. """ with self.workers_mutex: self.num_workers += 1 while True: (request, client_address) = self.q.get() with self.workers_mutex: self.num_busy_workers += 1 self.process_request_thread(request, client_address) self.q.task_done() with self.workers_mutex: self.num_busy_workers -= 1 if (self.num_workers > self.min_workers and self.num_workers - self.num_busy_workers > self.min_spare_workers): self.num_workers -= 1 return def process_request(self, request, client_address): """Puts a request into queue. If the queue size is too large, it adds extra worker. """ self.q.put((request, client_address)) with self.workers_mutex: if self.q.qsize() > 3 and self.num_workers < self.max_workers: self.start_workers(1) def join(self): """Wait for all busy threads""" self.q.join() #------- TestServer.py from __future__ import with_statement from SocketServer import * import socket import sys import threading import time import os from ThreadPoolingMixIn import * class ThreadPoolingTCPServer(ThreadPoolingMixIn, TCPServer): pass class TestServer(ThreadingTCPServer): allow_reuse_address = True request_queue_size = 128 def __init__(self, server_address, RequestHandlerClass, packet_size): TCPServer.__init__(self, server_address, RequestHandlerClass) self.packet_size = packet_size self.sum_t = 0 self.total_num_requests = 0 self.num_requests = 0 self.t0 = time.time() self.lock = threading.Lock() def reset_stats(self): with self.lock: self.total_num_requests += self.num_requests self.num_requests = 0 self.sum_t = 0 self.t0 = time.time() def update_stats(self, t0, t1): with self.lock: self.num_requests += 1 self.sum_t += t1 - t0 n = self.num_requests sum_t = self.sum_t avg_t = sum_t / n rate = n / (t1 - self.t0) return (n, avg_t, rate) def handle_request(self): """Handle one request, possibly blocking.""" try: request, client_address = self.get_request() except KeyboardInterrupt: raise except socket.error: return if self.verify_request(request, client_address): try: self.process_request(request, client_address) except KeyboardInterrupt: raise except: self.handle_error(request, client_address) self.close_request(request) class TestServerThreadPool(ThreadPoolingMixIn,TestServer): def __init__(self, server_address, RequestHandlerClass, packet_size): TestServer.__init__(self, server_address, RequestHandlerClass, packet_size) self.init_thread_pool(2, 200, 20) class TestRequestHandler(StreamRequestHandler): def __init__(self, request, client_address, server): self.t0 = time.time() StreamRequestHandler.__init__(self, request, client_address, server) def handle(self): self.wfile.write('a'*(self.server.packet_size)) t1 = time.time() (n, avg_t, rate) = self.server.update_stats(self.t0, t1) if n % 10000 == 0: print('rate=%.2f ' % rate) self.server.reset_stats() from optparse import OptionParser def server(o): HandlerClass = TestRequestHandler if o.server == "threading": ServerClass = TestServer elif o.server == "threadpooling": ServerClass = TestServerThreadPool else: return server_address = ('', o.port) try: srv = ServerClass(server_address, HandlerClass, o.packet_size) sa = srv.socket.getsockname() print "Serving on", sa[0], "port", sa[1], "..." srv.serve_forever() except Exception, val: print "Exception: %s" % str(val) raise def client(o): for f in xrange(0,o.n_clients): if os.fork(): while True: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("localhost",o.port)) while len(sock.recv(4096)): pass sock.close() except Exception, val: print val time.sleep(1) if __name__ == '__main__': args = sys.argv[1:] usage = "usage: %prog [options]" parser = OptionParser(usage) parser.add_option( "-p", "--port", help="Server port", type="int", default=8123 ) parser.add_option( "", "--n-clients", help="Number of client forks", type="int", default=0 ) parser.add_option( "", "--server", help="Type of the server (threading or threadpooling)", type="string", default="" ) parser.add_option( "", "--packet-size", help="Packet size", type="int", default=16*1024 ) (o,a) = parser.parse_args(args) if os.fork() == 0: server(o) else: client(o) From martin at v.loewis.de Thu Jun 26 12:46:39 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 26 Jun 2008 18:46:39 +0200 Subject: Bind compiled code to name? In-Reply-To: References: <485e9aea$0$637$9b622d9e@news.freenet.de> Message-ID: <4863c7ef$0$25963$9b622d9e@news.freenet.de> >> d = {} >> exec source_code in d >> some_name = d['some_name'] > > This works quite well! I can't believe after googling for half on hour I > didn't notice this "exec ... in ..." syntax. > One more thing though, is there a way to access "some_name" as a > attribute, instead as a dictionary: > > some_name = d.some_name Sure: class D:pass d = D() exec source_code in d.__dict__ print d.some_name Notice that this will also give you d.__builtins__, which you might want to del afterwards. Regards, Martin From circularfunc at yahoo.se Fri Jun 27 22:17:35 2008 From: circularfunc at yahoo.se (defn noob) Date: Fri, 27 Jun 2008 19:17:35 -0700 (PDT) Subject: Pygame, how to show window without loop? no loop=popupand close... Message-ID: <8ecb6375-356a-4e73-be21-18ffe0f5c4f2@r66g2000hsg.googlegroups.com> Im using PyGame to draw images of graphs and trees. Howver right now i am looping using: while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() screen.fill(screencolor) pygame.draw.circle(screen, linecolor, (500, 20), 12, 0) draw((500, 20), 3) pygame.display.flip() if i do screen.fill(screencolor) pygame.draw.circle(screen, linecolor, (500, 20), 12, 0) draw((500, 20), 3) pygame.display.flip() it just pops up and closes. how can i make it stay until i close it without using a loop? From alexnbryan at gmail.com Fri Jun 27 19:28:56 2008 From: alexnbryan at gmail.com (Alexnb) Date: Fri, 27 Jun 2008 16:28:56 -0700 (PDT) Subject: using urllib2 In-Reply-To: References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> Message-ID: <18165634.post@talk.nabble.com> I have read that multiple times. It is hard to understand but it did help a little. But I found a bit of a work-around for now which is not what I ultimately want. However, even when I can get to the page I want lets say, "Http://dictionary.reference.com/browse/cheese", I look on firebug, and extension and see the definition in javascript,

    1.the curd of milk separated from the whey and prepared >> in >> >> many ways as a food.
    Jeff McNeil-2 wrote: > > > the problem being that if I use code like this to get the html of that > page in python: > > response = urllib2.urlopen("the webiste....") > html = response.read() > print html > > then, I get a bunch of stuff, but it doesn't show me the code with the > table that the definition is in. So I am asking how do I access this > javascript. Also, if someone could point me to a better reference than the > last one, because that really doesn't tell me much, whether it be a book > or anything. > > > > I stumbled across this a while back: > http://www.voidspace.org.uk/python/articles/urllib2.shtml. > It covers quite a bit. The urllib2 module is pretty straightforward > once you've used it a few times. Some of the class naming and whatnot > takes a bit of getting used to (I found that to be the most confusing > bit). > > On Jun 27, 1:41 pm, Alexnb wrote: >> Okay, I tried to follow that, and it is kinda hard. But since you >> obviously >> know what you are doing, where did you learn this? Or where can I learn >> this? >> >> >> >> >> >> Maric Michaud wrote: >> >> > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit : >> >> I have never used the urllib or the urllib2. I really have looked >> online >> >> for help on this issue, and mailing lists, but I can't figure out my >> >> problem because people haven't been helping me, which is why I am >> here! >> >> :]. >> >> Okay, so basically I want to be able to submit a word to >> dictionary.com >> >> and >> >> then get the definitions. However, to start off learning urllib2, I >> just >> >> want to do a simple google search. Before you get mad, what I have >> found >> >> on >> >> urllib2 hasn't helped me. Anyway, How would you go about doing this. >> No, >> >> I >> >> did not post the html, but I mean if you want, right click on your >> >> browser >> >> and hit view source of the google homepage. Basically what I want to >> know >> >> is how to submit the values(the search term) and then search for that >> >> value. Heres what I know: >> >> >> import urllib2 >> >> response = urllib2.urlopen("http://www.google.com/") >> >> html = response.read() >> >> print html >> >> >> Now I know that all this does is print the source, but thats about all >> I >> >> know. I know it may be a lot to ask to have someone show/help me, but >> I >> >> really would appreciate it. >> >> > This example is for google, of course using pygoogle is easier in this >> > case, >> > but this is a valid example for the general case : >> >> >>>>[207]: import urllib, urllib2 >> >> > You need to trick the server with an imaginary User-Agent. >> >> >>>>[208]: def google_search(terms) : >> > return >> urllib2.urlopen(urllib2.Request("http://www.google.com/search?" >> > + >> > urllib.urlencode({'hl':'fr', 'q':terms}), >> > headers={'User-Agent':'MyNav >> > 1.0 >> > (compatible; MSIE 6.0; Linux'}) >> > ).read() >> > .....: >> >> >>>>[212]: res = google_search("python & co") >> >> > Now you got the whole html response, you'll have to parse it to recover >> > datas, >> > a quick & dirty try on google response page : >> >> >>>>[213]: import re >> >> >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

    > class=r>.*?

    ', >> > res) ] >> > ...[229]: >> > ['Python Gallery', >> > 'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des Monty >> ...', >> > 'Re: os x, panther, python & co: msg#00041', >> > 'Re: os x, panther, python & co: msg#00040', >> > 'Cardiff Web Site Design, Professional web site design services ...', >> > 'Python Properties', >> > 'Frees < Programs < Python < Bin-Co', >> > 'Torb: an interface between Tcl and CORBA', >> > 'Royal Python Morphs', >> > 'Python & Co'] >> >> > -- >> > _____________ >> >> > Maric Michaud >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> -- >> View this message in >> context:http://www.nabble.com/using-urllib2-tp18150669p18160312.html >> Sent from the Python - python-list mailing list archive at Nabble.com. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/using-urllib2-tp18150669p18165634.html Sent from the Python - python-list mailing list archive at Nabble.com. From kirk at daycos.com Fri Jun 27 12:52:57 2008 From: kirk at daycos.com (Kirk Strauser) Date: Fri, 27 Jun 2008 11:52:57 -0500 Subject: Django or TurboGears for a new project Message-ID: <8763ru6cra.fsf@internal.daycos.com> We're looking to migrate a Zope site to Django, but before getting beyond the dreaming stage, I thought I'd see what others are doing these days. If you were going to start a fairly complex site today with lots of DB integration, would you begin with Django or TurboGears, or something else entirely? I'm more interested in social, rather than technical reasons (unless there's something you absolutely love or despise about one or the other). Popularity is actually a pretty big consideration because I'd like to work with an eager community who's doing cool new things. I know asking for comparisons like this is potentially flamebait-ish, but I really don't mean it that way. It's just that I don't have a lot of friends in the industry in this particular development niche who I can ask for recommendations, and this seems like as good a place as any to find subject matter experts. Thanks, -- Kirk Strauser The Day Companies From Russ.Paielli at gmail.com Sun Jun 8 15:27:14 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 8 Jun 2008 12:27:14 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> Message-ID: <5c617585-8664-4aa7-95bf-fa33f20d98c1@j1g2000prb.googlegroups.com> On Jun 8, 5:52 am, Mark Wooding wrote: > By enforcing your `data hiding', you're effectively telling me that I'm > too stupid to make rational decisions of this sort. And that's actually > extremely insulting. 1) I suggest you not take it personally. 2) Local data within functions is hidden. Should you have access to that too? Are you insulted that you don't? 3) I have suggested that "indirect" or "back door" access could be provided to private data and methods via some sort of name mangling rule akin to the current rule for leading double underscores. This would provide access in a pinch, but it would make sure the client is aware that he or she or it is accessing private data (and it would do so without leading underscores). 4) My understanding is that most Python software is released or shipped as source code (or at least with the source code included). That means that the client would need only to remove my suggested "priv" keyword to gain access. Have you ever actually had to use Python software for which you had no access to the source code? From dyamins at gmail.com Fri Jun 13 21:38:24 2008 From: dyamins at gmail.com (Dan Yamins) Date: Fri, 13 Jun 2008 21:38:24 -0400 Subject: A package import question In-Reply-To: References: <15e4667e0806131601r14759c54jac431a8fc531414d@mail.gmail.com> Message-ID: <15e4667e0806131838p7258b00by66db0fe8393ddfa5@mail.gmail.com> You have removed the "archive" attribute from the object to which the > "Operations" name is referring to. > > >>> import Operations.archive >> > > Python keeps a reference to all imported modules in sys.modules; if a > module was already imported, any subsequent imports of the same module just > return the existing reference. > If you want to force Python to re-read the module from file, use the reload > function. But please read the warnings at > http://docs.python.org/lib/built-in-funcs.html#l2h-61 > > Gabriel, thanks. I understood about the fact that import only loads the first time, but didn't realize that "del" only removes the bound reference to the object, not as I had hoped the thing from the namespace itself. Also, I did _try_ to use reload. however, that failed since .archive was no longer an attribute associated with Operations: >>> import Operations.archive >>> del Operations.archive >>> reload(Operations.archive) Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'archive' It seems unfortunately that the "del" operation on the one hand doesn't really remove the .archive from memory but just it's bound name, but nonetheless prevents me from reloading the object kept in memory. I guess I'm trying to find a clean way to remove all the attributes associated with a module when I reload it. Is there any way to do this? (The operation of recursively searching through the attributes of the module and deleting those first seems to be bad since when I did that and then try to _reload_ the module, the attributes I deleted are _not_ reloaded.) On Fri, Jun 13, 2008 at 9:09 PM, Gabriel Genellina wrote: > En Fri, 13 Jun 2008 20:01:56 -0300, Dan Yamins > escribi?: > > I'm having a problem importing a package in python, deleting some of >> what's >> been imported, and then reimporting. (I'm the sure the problem is >> trivial, >> but I just don't understand it.) >> >> I have a directory of python modules called Operations. It contains a >> python module called archive.py. Here's a import of the archive module >> via package import: >> >> Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) >> [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import Operations.archive >> >>> Operations.archive >> >> >> So far, so good. >> > > Note that if you execute dir() at this point, you'll see the Operations > name, *not* Operations.archive. > The statement "import Operations.archive" first tries to locate and load a > module named Operations - and *that* name is added to the current namespace, > not Operations.archive (which is an invalid name by itself). > > But now, suppose I want to delete Operations.archive. then, I can't >> reimport it. instead, I >> >> >>> del Operations.archive >> > > You have removed the "archive" attribute from the object to which the > "Operations" name is referring to. > > >>> import Operations.archive >> > > Python keeps a reference to all imported modules in sys.modules; if a > module was already imported, any subsequent imports of the same module just > return the existing reference. > If you want to force Python to re-read the module from file, use the reload > function. But please read the warnings at > http://docs.python.org/lib/built-in-funcs.html#l2h-61 > > >>> dir() >> ['Operations', '__builtins__', '__doc__', '__name__'] >> >>> >> >> Instead of getting 'Operations.archive', I just seem to get 'Operations'. >> > > You would never get a dotted name from dir(), unless you play tricks with > locals()/globals() > > I can't seem to be able to import Operations.archive without quitting the >> python interpreter and starting again. >> >> What's going on here, and how do I fix it? >> > > reload() may be what you need, but again, make sure you read the > documentation before using it. reload is not a magic wand. Remember that > names imported from the old module definition continue to be bound to the > old objects, and all instances of classes defined in the old module continue > to use the old class definitions, among other things. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From s0suk3 at gmail.com Wed Jun 18 20:23:16 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Wed, 18 Jun 2008 17:23:16 -0700 (PDT) Subject: Personal project announcement Message-ID: <0e423dc3-9a7c-4e46-bf3d-af7d8c77cd82@a70g2000hsh.googlegroups.com> Hi, Just wanted to announce a little project I've just uploaded. It's a web server written in Python. You can get it at http://code.google.com/p/sws-d/ . Any suggestions or comments are welcome! Regards, Sebastian From hyugaricdeau at gmail.com Fri Jun 13 09:37:36 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Fri, 13 Jun 2008 06:37:36 -0700 (PDT) Subject: Setting Focus References: <976f51d2-bbb2-4806-a1d0-9481f5aae887@d45g2000hsc.googlegroups.com> <2cf8ed15-e297-42d2-997e-7cf41993b0d9@m3g2000hsc.googlegroups.com> Message-ID: <1c39fb6c-f18c-4e48-9d2d-c4bbf590cc23@25g2000hsx.googlegroups.com> On Jun 13, 9:34 am, Hyuga wrote: > On Jun 12, 11:04 pm, Gandalf wrote: > > > You know these application like ICQ or winamp which stay at the front > > of the desktop as long as the user doesn't minimize it. I wont to do > > the same with my application in python. > > I still didn't manage to make pywinauto to auto set my window frame in > > focus reliability so I was hoping this will solve my problem. > > > I'm working with WX lib on 2.5 python on Microsoft Windows XP > > > I'm not sure if there's a way to do this purely in wx, as it's sort of > a Windows-specific functionality as far as I know. I know in win32 > you can use SetWindowPos() and pass it HWND_TOP (seehttp://msdn.microsoft.com/en-us/library/ms633545(VS.85).aspx). So you Sorry, I meant you actually want HWND_TOPMOST as the second argument to SetWindowPos(). That puts the window above all other windows and keeps it there. Erik From stefan_ml at behnel.de Fri Jun 27 11:20:32 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 27 Jun 2008 17:20:32 +0200 Subject: Design principles and architecture of an information transfer standard based on XML and SOAP In-Reply-To: <070a2cec-5c4b-44ab-93ff-a0811f7c226b@u6g2000prc.googlegroups.com> References: <070a2cec-5c4b-44ab-93ff-a0811f7c226b@u6g2000prc.googlegroups.com> Message-ID: <48650540.9080700@behnel.de> xkenneth wrote: > I'm looking for a bit of advice. There's an oilfield standard > called WITSML (Wellsite Information Transfer Standard Markup Language > - witsml.org), it's basically a collection of XML schemas and a spec For implementing XML languages, I (biasedly) advocate lxml's element class features. http://codespeak.net/lxml/dev/element_classes.html I'll give a tutorial on them at EuroPython, in case you're interested. Stefan From badmuthahubbard at gmail.com Sat Jun 7 10:53:50 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Sat, 7 Jun 2008 17:53:50 +0300 Subject: More than one element of list changing when only one should be Message-ID: <8200bab70806070753y69652e74v73a280cfacb23af2@mail.gmail.com> Hello. This program is clunky, I know; I'm not a programmer, but I need to use this program, so I'm writing it. The problem: I have a cursor following the mouse that shows frequency ratios of potential notes in relation to 1/1 (something like Middle C). At any time, the user may hit "t" to move 1/1 to wherever the cursor is. There is also the option to use many regions, so that some of the notes in the score, in region 0, for instance, can have 1/1 as their base, and others, in region 1 for instance, could have perhaps 3/2 as their base. The program starts out with 2 existing regions, region 0 = 1/1, and region 1 = 3/2. If the user hits r+NUM, the cursor switches to region NUM. If NUM is longer than the list of regions (self.regionlist), a new region is appended with the same base as the current one, and the cursor goes to that region. SO, if you start this program, then: 1) move the cursor around a little; 2) hit 'r' and '1' at the same time - now you are in region 1; 3) hit 'r' and '0', now region 0; 4) hit 'r' and '2', now a new region 2 is created with the same parameters as region 0, and self.regionlist is appended with the new info - now you're in region 2; 5) move the mouse until the fraction reads anything other than 1/1; 6) hit 't' to transpose the current region by that fraction; You can see by the output in the text window that self.regionlist[0] AND self.regionlist[2] have been updated. Only [2] should have been changed. 7) hit 'r' and '0', and see that region 0 has now changed its base to match region 2. I hope someone is curious enough to get through this and help me. I tried extracting the function in question into its own mini-file and the problem didn't happen. I can't think of any reason these lines: self.regionlist[self.hregion][0] = self.curnum self.regionlist[self.hregion][1] = self.curden self.regionlist[self.hregion][3] = self.octave11 = self.yadj should change self.regionlist[0] AND self.regionlist[2] in the same call, but they do. Also, if I add more regions in series, they all update each other. Thanks for your time. -Chuckk -- http://www.badmuthahubbard.com From tjreedy at udel.edu Tue Jun 24 14:52:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Jun 2008 14:52:34 -0400 Subject: sending executable data over network.. In-Reply-To: <19ac19520806240547m172941b2k52777e47b9a84711@mail.gmail.com> References: <19ac19520806232359r31f74c7bk9f5d47eb3540e457@mail.gmail.com> <200806241245.35047.omer@no-log.org> <19ac19520806240547m172941b2k52777e47b9a84711@mail.gmail.com> Message-ID: Piyush Anonymous wrote: > any idea or pointer how i could link it to running code in server? > for example, i get a new method definition for a method and i wish to > change it. > client sent new definition, i compile it in server. how can i link it to > old code? Code to be hot-updated (while running) must have update capability builtin. But please consider security. If a remote system can log in and *push* code, an attacker can potentially do the same. Notice that self-updating programs and systems generally log out to a hardwired location, ask if there are updates, and *pull* the new code. From srilyk at gmail.com Wed Jun 11 11:25:17 2008 From: srilyk at gmail.com (W W) Date: Wed, 11 Jun 2008 10:25:17 -0500 Subject: [Tutor] python gui In-Reply-To: <9d68e4e90806110818q18c57bd2v8b3219de9b2a1ca1@mail.gmail.com> References: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> <333efb450806110818g134b930cj6e36f7bd79a9083@mail.gmail.com> <9d68e4e90806110818q18c57bd2v8b3219de9b2a1ca1@mail.gmail.com> Message-ID: <333efb450806110825i376b9e45we2e6d98d6bdb0396@mail.gmail.com> On Wed, Jun 11, 2008 at 10:18 AM, Gabriela Soares wrote: > How ? That's an extremely broad question, and shows little initiative, and offers little information. Most of us are happy to help you solve problems for free, but few, if any, are willing to write your programs for free. > Any references ? www.google.com Norman linked to a fairly interesting project. Hope this helps, Wayne > On Wed, Jun 11, 2008 at 4:18 PM, W W wrote: >> >> On Wed, Jun 11, 2008 at 8:03 AM, Gabriela Soares >> wrote: >> > Greetings, >> > >> > I want to make a dynamic dashboard, something like: >> > >> > http://examples.adobe.com/flex3/labs/dashboard/main.html# >> > >> > but using python. Is it possible ? >> >> Yes. >> >> -Wayne > > > > -- > Gabriela Soares > > "I learned that courage was not the absence of fear, but the triumph over > it. The brave man is not he who does not feel afraid, but he who conquers > that fear." > Nelson Mandela -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From larry.bates at websafe.com` Thu Jun 5 15:50:24 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 05 Jun 2008 14:50:24 -0500 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <359a09bf-ffc4-403f-b19f-a4565eabcb44@l64g2000hse.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <7xhccbe5sr.fsf@ruckus.brouhaha.com> <359a09bf-ffc4-403f-b19f-a4565eabcb44@l64g2000hse.googlegroups.com> Message-ID: Russ P. wrote: > On Jun 2, 5:11 pm, Paul Rubin wrote: >> "Russ P." writes: >>> I also realize, by the way, that Python allows a client of a class to >>> define a new class member from completely outside the class >>> definition. Obviously, that cannot be declared private. >> This is bogus about 95% of the time though. For the cases where it is >> really desired, I think it's best to require the target class to be >> enable it specifically somehow, maybe by inheriting from a special >> superclass. That could let the compiler statically resolve member >> lookups the rest of the time. > > It did seem a bit odd to me when I realized that you can add data > members (or even a "methods") to a class from completely outside the > class definition. That can be risky, of course, and as you suggest, > perhaps it shouldn't even be allowed by default. > > I usually find that it's safer to initialize in the constructor all > (or nearly all) of the data members that will be needed in a class. If > I need a list that will be populated later, for example, I reserve the > name with an empty list in the constructor. Then, if for some reason > the list gets accessed before it is populated, I don't get an > exception. That is EXACTLY when I want an exception, I did something that shouldn't happen. You also are missing the nice ability of python to use hasattr() to find out if a class instance has a method/attribute. I use hasattr() to test for presence or absence of methods/attributes quite a lot. In the past I did what you describe, but found that to be limiting and a throwback to when I used languages that could not do introspection. I can test to see if the attribute exists, if it is empty, which can be two very different conditions that require two different actions. The only way you can do that is to initialize it to None. While this works it is a fictitious construct that we all learned when we were writing Fortran, Basic or Cobol years ago (oops I think I just revealed that I'm an 'old timer'). Now I just do: if hasattr(self, 'listInQuestion') and I can tell if it has been created (either by constructor) or by some other method. This works particularly well when I do caching of data in objects that are shared among methods. I can also do hasattr(object, 'methodInQuestion') to see if the object implements an interface that I require. May be a little off topic, but I think it is relevant. -Larry From alexnbryan at gmail.com Sun Jun 29 14:59:25 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sun, 29 Jun 2008 11:59:25 -0700 (PDT) Subject: using urllib2 In-Reply-To: <18184087.post@talk.nabble.com> References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> <25d97d35-6d28-43ef-9e54-d8ae7a03bc8f@b1g2000hsg.googlegroups.com> <27fbd1c7-6735-4fb0-9758-726b2fd8b86e@m3g2000hsc.googlegroups.com> <18184087.post@talk.nabble.com> Message-ID: <18184170.post@talk.nabble.com> Actually after looking at this, the code is preactically the same, except the definitions. So what COULD be going wrong here? Alexnb wrote: > > Okay, so i've hit a new snag and can't seem to figure out what is wrong. > What is happening is the first 4 definitions of the word "simple" don't > show up. The html is basicly the same, with the exception of noun turning > into adj. Ill paste the html of the word cheese, and then the one for > simple, and the code I am using to do the work. > > line of html for the 2nd def of cheese: > >
    1. the curd of milk separated from the whey and prepared in many ways as a food.
    2. valign="top">a definite mass of this substance, often in the shape of a > wheel or cylinder.
    > > line of html for the 2nd def of simple: > >
    2. valign="top">not elaborate or artificial; plain: a simple style. >
    > > code: > > import urllib > from BeautifulSoup import BeautifulSoup > > > def get_defs(term): > soup = > BeautifulSoup(urllib.urlopen('http://dictionary.reference.com/search?q=%s' > % term)) > > for tabs in soup.findAll('table', {'class': 'luna-Ent'}): > yield tabs.findAll('td')[-1].contents[-1].string > > word = raw_input("What word would you like to define: ") > > mainList = list(get_defs(word)) > > n=0 > q = 1 > > for x in mainList: > print str(q)+". "+str(mainList[n]) > q=q+1 > n=n+1 > > Now, I don't think it is the italics because one of the definitions that > worked had them in it in the same format. Any Ideas??! > > > Jeff McNeil-2 wrote: >> >> On Jun 29, 12:50?pm, Alexnb wrote: >>> No I figured it out. I guess I never knew that you aren't supposed to >>> split a >>> url like "http://www.goo\ >>> gle.com" But I did and it gave me all those errors. Anyway, I had a >>> question. On the original code you had this for loop: >>> >>> for tabs in soup.findAll('table', {'class': 'luna-Ent'}): >>> ? ? ? ? yield tabs.findAll('td')[-1].contents[-1].string >>> >>> I hate to be a pain, but I was looking at the BeautifulSoup docs, and >>> found >>> the findAll thing. But I want to know why you put "for tabs," also why >>> you >>> need the "'table', {'class': 'luna-Ent'}):" Like why the curly braces >>> and >>> whatnot? >>> >>> Jeff McNeil-2 wrote: >>> >>> > On Jun 27, 10:26?pm, Alexnb wrote: >>> >> Okay, so I copied your code(and just so you know I am on a mac right >>> now >>> >> and >>> >> i am using pydev in eclipse), and I got these errors, any idea what >>> is >>> >> up? >>> >>> >> Traceback (most recent call last): >>> >> ? File >>> >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", >>> >> line 14, in >>> >> ? ? print list(get_defs("cheese")) >>> >> ? File >>> >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", >>> >> line 9, in get_defs >>> >> ? ? dictionary.reference.com/search?q=%s' % term)) >>> >> ? File >>> >> >>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >>> lib.py", >>> >> line 82, in urlopen >>> >> ? ? return opener.open(url) >>> >> ? File >>> >> >>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >>> lib.py", >>> >> line 190, in open >>> >> ? ? return getattr(self, name)(url) >>> >> ? File >>> >> >>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >>> lib.py", >>> >> line 325, in open_http >>> >> ? ? h.endheaders() >>> >> ? File >>> >> >>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >>> plib.py", >>> >> line 856, in endheaders >>> >> ? ? self._send_output() >>> >> ? File >>> >> >>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >>> plib.py", >>> >> line 728, in _send_output >>> >> ? ? self.send(msg) >>> >> ? File >>> >> >>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >>> plib.py", >>> >> line 695, in send >>> >> ? ? self.connect() >>> >> ? File >>> >> >>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >>> plib.py", >>> >> line 663, in connect >>> >> ? ? socket.SOCK_STREAM): >>> >> IOError: [Errno socket error] (8, 'nodename nor servname provided, or >>> not >>> >> known') >>> >>> >> Sorry if it is hard to read. >>> >>> >> Jeff McNeil-2 wrote: >>> >>> >> > Well, what about pulling that data out using Beautiful soup? If you >>> >> > know the table name and whatnot, try something like this: >>> >>> >> > #!/usr/bin/python >>> >>> >> > import urllib >>> >> > from BeautifulSoup import BeautifulSoup >>> >>> >> > def get_defs(term): >>> >> > ? ? soup = BeautifulSoup(urllib.urlopen('http:// >>> >> > dictionary.reference.com/search?q=%s' % term)) >>> >>> >> > ? ? for tabs in soup.findAll('table', {'class': 'luna-Ent'}): >>> >> > ? ? ? ? yield tabs.findAll('td')[-1].contents[-1].string >>> >>> >> > print list(get_defs("frog")) >>> >>> >> > jeff at martian:~$ python test.py >>> >> > [u'any tailless, stout-bodied amphibian of the order Anura, >>> including >>> >> > the smooth, moist-skinned frog species that live in a damp or >>> >> > semiaquatic habitat and the warty, drier-skinned toad species that >>> are >>> >> > mostly terrestrial as adults. ', u' ', u' ', u'a French person or a >>> >> > person of French descent. ', u'a small holder made of heavy >>> material, >>> >> > placed in a bowl or vase to hold flower stems in position. ', u'a >>> >> > recessed panel on one of the larger faces of a brick or the like. >>> ', >>> >> > u' ', u'to hunt and catch frogs. ', u'French or Frenchlike. ', u'an >>> >> > ornamental fastening for the front of a coat, consisting of a >>> button >>> >> > and a loop through which it passes. ', u'a sheath suspended from a >>> >> > belt and supporting a scabbard. ', u'a device at the intersection >>> of >>> >> > two tracks to permit the wheels and flanges on one track to cross >>> or >>> >> > branch from the other. ', u'a triangular mass of elastic, horny >>> >> > substance in the middle of the sole of the foot of a horse or >>> related >>> >> > animal. '] >>> >>> >> > HTH, >>> >>> >> > Jeff >>> >>> >> > On Jun 27, 7:28?pm, Alexnb wrote: >>> >> >> I have read that multiple times. It is hard to understand but it >>> did >>> >> help >>> >> >> a >>> >> >> little. But I found a bit of a work-around for now which is not >>> what I >>> >> >> ultimately want. However, even when I can get to the page I want >>> lets >>> >> >> say, >>> >> >> "Http://dictionary.reference.com/browse/cheese", I look on >>> firebug, >>> >> and >>> >> >> extension and see the definition in javascript, >>> >>> >> >> >>> >> >> >>> >> >> >>> >> >> >>> >> >> >>> >>> >> >> Jeff McNeil-2 wrote: >>> >>> >> >> > the problem being that if I use code like this to get the html >>> of >>> >> that >>> >>> >> >> > page in python: >>> >>> >> >> > response = urllib2.urlopen("the webiste....") >>> >> >> > html = response.read() >>> >> >> > print html >>> >>> >> >> > then, I get a bunch of stuff, but it doesn't show me the code >>> with >>> >> the >>> >> >> > table that the definition is in. So I am asking how do I access >>> this >>> >> >> > javascript. Also, if someone could point me to a better >>> reference >>> >> than >>> >> >> the >>> >> >> > last one, because that really doesn't tell me much, whether it >>> be a >>> >> >> book >>> >> >> > or anything. >>> >>> >> >> > I stumbled across this a while back: >>> >> >> >http://www.voidspace.org.uk/python/articles/urllib2.shtml. >>> >> >> > It covers quite a bit. The urllib2 module is pretty >>> straightforward >>> >> >> > once you've used it a few times. ?Some of the class naming and >>> >> whatnot >>> >> >> > takes a bit of getting used to (I found that to be the most >>> >> confusing >>> >> >> > bit). >>> >>> >> >> > On Jun 27, 1:41 pm, Alexnb wrote: >>> >> >> >> Okay, I tried to follow that, and it is kinda hard. But since >>> you >>> >> >> >> obviously >>> >> >> >> know what you are doing, where did you learn this? Or where can >>> I >>> >> >> learn >>> >> >> >> this? >>> >>> >> >> >> Maric Michaud wrote: >>> >>> >> >> >> > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit : >>> >> >> >> >> I have never used the urllib or the urllib2. I really have >>> >> looked >>> >> >> >> online >>> >> >> >> >> for help on this issue, and mailing lists, but I can't >>> figure >>> >> out >>> >> >> my >>> >> >> >> >> problem because people haven't been helping me, which is why >>> I >>> >> am >>> >> >> >> here! >>> >> >> >> >> :]. >>> >> >> >> >> Okay, so basically I want to be able to submit a word to >>> >> >> >> dictionary.com >>> >> >> >> >> and >>> >> >> >> >> then get the definitions. However, to start off learning >>> >> urllib2, I >>> >> >> >> just >>> >> >> >> >> want to do a simple google search. Before you get mad, what >>> I >>> >> have >>> >> >> >> found >>> >> >> >> >> on >>> >> >> >> >> urllib2 hasn't helped me. Anyway, How would you go about >>> doing >>> >> >> this. >>> >> >> >> No, >>> >> >> >> >> I >>> >> >> >> >> did not post the html, but I mean if you want, right click >>> on >>> >> your >>> >> >> >> >> browser >>> >> >> >> >> and hit view source of the google homepage. Basically what I >>> >> want >>> >> >> to >>> >> >> >> know >>> >> >> >> >> is how to submit the values(the search term) and then search >>> for >>> >> >> that >>> >> >> >> >> value. Heres what I know: >>> >>> >> >> >> >> import urllib2 >>> >> >> >> >> response = urllib2.urlopen("http://www.google.com/") >>> >> >> >> >> html = response.read() >>> >> >> >> >> print html >>> >>> >> >> >> >> Now I know that all this does is print the source, but thats >>> >> about >>> >> >> all >>> >> >> >> I >>> >> >> >> >> know. I know it may be a lot to ask to have someone >>> show/help >>> >> me, >>> >> >> but >>> >> >> >> I >>> >> >> >> >> really would appreciate it. >>> >>> >> >> >> > This example is for google, of course using pygoogle is >>> easier in >>> >> >> this >>> >> >> >> > case, >>> >> >> >> > but this is a valid example for the general case : >>> >>> >> >> >> >>>>[207]: import urllib, urllib2 >>> >>> >> >> >> > You need to trick the server with an imaginary User-Agent. >>> >>> >> >> >> >>>>[208]: def google_search(terms) : >>> >> >> >> > ? ? return >>> >> >> >> urllib2.urlopen(urllib2.Request("http://www.google.com/search?" >>> >> >> >> > + >>> >> >> >> > urllib.urlencode({'hl':'fr', 'q':terms}), >>> >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? >>> >> >> ?headers={'User-Agent':'MyNav >>> >> >> >> > 1.0 >>> >> >> >> > (compatible; MSIE 6.0; Linux'}) >>> >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ).read() >>> >> >> >> > ? ?.....: >>> >>> >> >> >> >>>>[212]: res = google_search("python & co") >>> >>> >> >> >> > Now you got the whole html response, you'll have to parse it >>> to >>> >> >> recover >>> >> >> >> > datas, >>> >> >> >> > a quick & dirty try on google response page : >>> >>> >> >> >> >>>>[213]: import re >>> >>> >> >> >> >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

    >> >> >> >> class=r>.*?

    ', >>> >> >> >> > res) ] >>> >> >> >> > ...[229]: >>> >> >> >> > ['Python Gallery', >>> >> >> >> > ?'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie >>> des >>> >> Monty >>> >> >> >> ...', >>> >> >> >> > ?'Re: os x, panther, python & co: msg#00041', >>> >> >> >> > ?'Re: os x, panther, python & co: msg#00040', >>> >> >> >> > ?'Cardiff Web Site Design, Professional web site design >>> services >>> >> >> ...', >>> >> >> >> > ?'Python Properties', >>> >> >> >> > ?'Frees < Programs < Python < Bin-Co', >>> >> >> >> > ?'Torb: an interface between Tcl and CORBA', >>> >> >> >> > ?'Royal Python Morphs', >>> >> >> >> > ?'Python & Co'] >>> >>> >> >> >> > -- >>> >> >> >> > _____________ >>> >>> >> >> >> > Maric Michaud >>> >> >> >> > -- >>> >> >> >> >http://mail.python.org/mailman/listinfo/python-list >>> >>> >> >> >> -- >>> >> >> >> View this message in >>> >>> >> context:http://www.nabble.com/using-urllib2-tp18150669p18160312.html >>> >> >> >> Sent from the Python - python-list mailing list archive at >>> >> Nabble.com. >>> >>> >> >> > -- >>> >> >> >http://mail.python.org/mailman/listinfo/python-list >>> >>> >> >> -- >>> >> >> View this message in >>> >> >> >>> context:http://www.nabble.com/using-urllib2-tp18150669p18165634.html >>> >> >> Sent from the Python - python-list mailing list archive at >>> Nabble.com. >>> >>> >> > -- >>> >> >http://mail.python.org/mailman/listinfo/python-list >>> >>> >> -- >>> >> View this message in... >>> >>> read more ? >> >> The definitions were embedded in tables with a 'luna-Ent' class. I >> pulled all of the tables with that class out, and then returned the >> string value of td containing the actual definition. The findAll >> method takes an optional dictionary, thus the {}. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > -- View this message in context: http://www.nabble.com/using-urllib2-tp18150669p18184170.html Sent from the Python - python-list mailing list archive at Nabble.com. From armin.ronacher at active-4.com Mon Jun 16 04:37:44 2008 From: armin.ronacher at active-4.com (Armin Ronacher) Date: Mon, 16 Jun 2008 01:37:44 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections Message-ID: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> Abstract ======== This PEP proposes an ordered dictionary as a new data structure for the ``collections`` module, called "odict" in this PEP for short. The proposed API incorporates the experiences gained from working with similar implementations that exist in various real-world applications and other programming languages. Rationale ========= In current Python versions, the widely used built-in dict type does not specify an order for the key/value pairs stored. This makes it hard to use dictionaries as data storage for some specific use cases. Some dynamic programming languages like PHP and Ruby 1.9 guarantee a certain order on iteration. In those languages, and existing Python ordered-dict implementations, the ordering of items is defined by the time of insertion of the key. New keys are appended at the end, keys that are overwritten and not moved. The following example shows the behavior for simple assignments: >>> d = odict() >>> d['parrot'] = 'dead' >>> d['penguin'] = 'exploded' >>> d.items() [('parrot', 'dead'), ('penguin', 'exploded')] That the ordering is preserved makes an odict useful for a couple of situations: - XML/HTML processing libraries currently drop the ordering of attributes, use a list instead of a dict which makes filtering cumbersome, or implement their own ordered dictionary. This affects ElementTree, html5lib, Genshi and many more libraries. - There are many ordererd dict implementations in various libraries and applications, most of them subtly incompatible with each other. Furthermore, subclassing dict is a non-trivial task and many implementations don't override all the methods properly which can lead to unexpected results. Additionally, many ordered dicts are implemented in an inefficient way, making many operations more complex then they have to be. - PEP 3115 allows metaclasses to change the mapping object used for the class body. An ordered dict could be used to create ordered member declarations similar to C structs. This could be useful, for example, for future ``ctypes`` releases as well as ORMs that define database tables as classes, like the one the Django framework ships. Django currently uses an ugly hack to restore the ordering of members in database models. - Code ported from other programming languages such as PHP often depends on a ordered dict. Having an implementation of an ordering-preserving dictionary in the standard library could ease the transition and improve the compatibility of different libraries. Ordered Dict API ================ The ordered dict API would be mostly compatible with dict and existing ordered dicts. (Note: this PEP refers to the Python 2.x dictionary API; the transfer to the 3.x API is trivial.) The constructor and ``update()`` both accept iterables of tuples as well as mappings like a dict does. The ordering however is preserved for the first case: >>> d = odict([('a', 'b'), ('c', 'd')]) >>> d.update({'foo': 'bar'}) >>> d collections.odict([('a', 'b'), ('c', 'd'), ('foo', 'bar')]) If ordered dicts are updated from regular dicts, the ordering of new keys is of course undefined again unless ``sort()`` is called. All iteration methods as well as ``keys()``, ``values()`` and ``items()`` return the values ordered by the the time the key-value pair was inserted: >>> d['spam'] = 'eggs' >>> d.keys() ['a', 'c', 'foo', 'spam'] >>> d.values() ['b', 'd', 'bar', 'eggs'] >>> d.items() [('a', 'b'), ('c', 'd'), ('foo', 'bar'), ('spam', 'eggs')] New methods not available on dict: ``odict.byindex(index)`` Index-based lookup is supported by ``byindex()`` which returns the key/value pair for an index, that is, the "position" of a key in the ordered dict. 0 is the first key/value pair, -1 the last. >>> d.byindex(2) ('foo', 'bar') ``odict.sort(cmp=None, key=None, reverse=False)`` Sorts the odict in place by cmp or key. This works exactly like ``list.sort()``, but the comparison functions are passed a key/value tuple, not only the value. >>> d = odict([(42, 1), (1, 4), (23, 7)]) >>> d.sort() >>> d collections.odict([(1, 4), (23, 7), (42, 1)]) ``odict.reverse()`` Reverses the odict in place. ``odict.__reverse__()`` Supports reverse iteration by key. Questions and Answers ===================== What happens if an existing key is reassigned? The key is not moved but assigned a new value in place. This is consistent with existing implementations and allows subclasses to change the behavior easily:: class movingcollections.odict): def __setitem__(self, key, value): self.pop(key, None) odict.__setitem__(self, key, value) What happens if keys appear multiple times in the list passed to the constructor? The same as for regular dicts: The latter item overrides the former. This has the side-effect that the position of the first key is used because the key is actually overwritten: >>> odict([('a', 1), ('b', 2), ('a', 3)]) collections.odict([('a', 3), ('b', 2)]) This behavior is consistent with existing implementations in Python, the PHP array and the hashmap in Ruby 1.9. Why is there no ``odict.insert()``? There are few situations where you really want to insert a key at an specified index. To avoid API complication, the proposed solution for this situation is creating a list of items, manipulating that and converting it back into an odict: >>> d = odict([('a', 42), ('b', 23), ('c', 19)]) >>> l = d.items() >>> l.insert(1, ('x', 0)) >>> odict(l) collections.odict([('a', 42), ('x', 0), ('b', 23), ('c', 19)]) Example Implementation ====================== A poorly performing example implementation of the odict written in Python is available: `odict.py `_ The version for ``collections`` should be implemented in C and use a linked list internally. Other implementations of ordered dicts in various Python projects or standalone libraries, that inspired the API proposed here, are: - `odict in Babel`_ - `OrderedDict in Django`_ - `The odict module`_ - `ordereddict`_ (a C implementation of the odict module) - `StableDict`_ - `Armin Rigo's OrderedDict`_ .. _odict in Babel: http://babel.edgewall.org/browser/trunk/babel/util.py?rev=374#L178 .. _OrderedDict in Django: http://code.djangoproject.com/browser/django/trunk/django/utils/datastructures.py?rev=7140#L53 .. _The odict module: http://www.voidspace.org.uk/python/odict.html .. _ordereddict: http://www.xs4all.nl/~anthon/Python/ordereddict/ .. _StableDict: http://pypi.python.org/pypi/StableDict/0.2 .. _Armin Rigo's OrderedDict: http://codespeak.net/svn/user/arigo/hack/pyfuse/OrderedDict.py Future Directions ================= With the availability of an ordered dict in the standard library, other libraries may take advantage of that. For example, ElementTree could return odicts in the future that retain the attribute ordering of the source file. Copyright ========= This document has been placed in the public domain. From tjreedy at udel.edu Sun Jun 29 18:53:26 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 29 Jun 2008 18:53:26 -0400 Subject: UnboundLocalError problems In-Reply-To: <637159.47140.qm@web54507.mail.re2.yahoo.com> References: <637159.47140.qm@web54507.mail.re2.yahoo.com> Message-ID: Mr SZ wrote: > > Hi, > > I am writing a small script that changes my pidgin status to away when I > lock my screen.I'm using the DBUS API for pidgin and > gnome-screensaver.Here's the code: > > #!/usr/bin/env python > > import dbus, gobject > from dbus.mainloop.glib import DBusGMainLoop > dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) > bus = dbus.SessionBus() > > obj = bus.get_object("im.pidgin.purple.PurpleService", > "/im/pidgin/purple/PurpleObject") > purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface") > > > STATUS_AVAILABLE = 2 > STATUS_AWAY = 5 > > ORIG_TYPE = 0 > ORIG_MSG = "" > > > def my_func2(IsEnabled): you need global ORIG_TYPE,ORIG_MSG > if IsEnabled: > ORIG_TYPE,ORIG_MSG = get_current() because this otherwise marks them as local. [snip] > When I run it,it errors out at : > > set_status(ORIG_TYPE,ORIG_MSG) > > giving the error "UnboundLocalError: local variable 'ORIG_TYPE' > referenced before assignment" .This happens In the future, copy and paste the full traceback, which often has additional useful information -- like the line # of the call -- which is not so obvious to someone who has not read the code. > > Aren't ORIG_TYPE and ORIG_MSG global variables? Where am I going > wrong?Everything works fine if I set the arguments manually to the > set_status function. *Any* assignment to a name, including with def, class, import, and augmented assignment, even if the statement is unreachable and cannot be executed, marks the name as local -- unless you specify it as global (or nonlocal in 3.0). tjr From paul.hankin at gmail.com Mon Jun 9 04:54:31 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Mon, 9 Jun 2008 01:54:31 -0700 (PDT) Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: <54c6339a-9119-43b4-af39-3f3c2fb709f1@q24g2000prf.googlegroups.com> On Jun 9, 5:11?pm, Frank Millman wrote: > I have a standard requirement for a 'decimal' type, to instantiate and > manipulate numeric data that is stored in a database. I came up with a > solution long before the introduction of the Decimal type, which has > been working well for me. I know the 'scale' (number of decimal > places) of the number in advance. When I read the number in from the > database I scale it up to an integer. When I write it back I scale it > down again. All arithmetic is done using integers, so I do not lose > accuracy. > > There is one inconvenience with this approach. For example, if I have > a product quantity with a scale of 4, and a price with a scale of 2, > and I want to multiply them to get a value with a scale of 2, I have > to remember to scale the result down by 4. This is a minor chore, and > errors are quickly picked up by testing, but it does make the code a > bit messy, so it would be nice to find a solution. > > I am now doing some refactoring, and decided to take a look at the > Decimal type. My initial impressions are that it is quite awkward to > use, that I do not need its advanced features, and that it does not > help solve the one problem I have mentioned above. > > I therefore spent a bit of time experimenting with a Number type that > suits my particular requirements. I have come up with something that > seems to work, which I show below. > > I have two questions. > > 1. Are there any obvious problems in what I have done? > > 2. Am I reinventing the wheel unnecessarily? i.e. can I do the > equivalent quite easily using the Decimal type? Hi Frank, I don't know why you think Decimal is complicated: it has some advanced features, but for what you seem to be doing it should be easy to replace your 'Number' with it. In fact, it makes things simpler since you don't have to worry about 'scale'. Your examples convert easily: from decimal import Decimal qty = Decimal('12.5') price = Decimal('123.45') print price * qty print qty * price print (qty * price).quantize(Decimal('0.01')) -- Paul Hankin From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 30 10:57:50 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 30 Jun 2008 16:57:50 +0200 Subject: How do web templates separate content and logic? In-Reply-To: <4866ff46$0$7333$607ed4bc@cv.net> References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> Message-ID: <4868f46d$0$24451$426a74cc@news.free.fr> John Salerno a ?crit : > bruno.desthuilliers at gmail.com wrote: > >> For which definitions of "content" and "logic" ??? >> >> The point of mvc is to keep domain logic separated from presentation >> logic, not to remove logic from presentation (which just couldn't >> work). Templating systems are for presentation logic. Whether they >> work by embedding an existing complete programmation language or by >> providing they're own specialised mini-language (or a mix of both) is >> not the point here IMHO. > > No, I don't mean presentation logic at all. I mean something along the > lines of combining HTML (which is what I refer to as "content") and > Python (which is what I meant by "logic"). Some (if not most) templating systems use their own mini-language to handle presentation logic. > So for example, if you have > code like this (and this isn't necessarily proper code, I'm just making > this up, but you'll see what I mean): > > >

    Big Important Topic

    >

    This is where I say something important about

    >
      > % for topic in topics: >
    1. ${topic}
    2. >
    > In Django's template system, this would looks like:

    Big Important Topic

    This is where I say something important about

      {% for topic in topics %}
    1. {{ topic }}
    2. {% endfor %}
    In ZPT, it would be:

    Big Important Topic

    This is where I say something important about

    1. Yadda
    > Humph, I just made up that example to make the point that when you no > longer have pure HTML, but instead have programmatic logic (Python) > mixed in with the HTML, then you are mixing content and logic. > > However, as soon as I finished typing it out, it occurred to me that > even the so-called logic in this example is really only producing more > "content" to display. Indeed. > So maybe my question was a little premature. The meme "thou shall not mix domain logic with presentation" is very often misunderstood as "you must not have anything else than html in templates", which is just plain non-sense. Even declarative templating systems (cf Has's post) require some special (ie: non standard) stuff to work. > Or could it just be that > this is a *good* way to mix HTML and Python, and there are other ways > which may be bad? Bingo. > (For example, connecting to a database, like > Sebastian's example. That definitely seems out of place in an HTML file.) Yeps. From alexfama80 at gmail.com Mon Jun 23 13:39:13 2008 From: alexfama80 at gmail.com (AlexFama) Date: Mon, 23 Jun 2008 10:39:13 -0700 (PDT) Subject: Shop and make money Message-ID: <4276e2d1-41bb-4780-a294-3dd7f8c1eafe@r66g2000hsg.googlegroups.com> Shop and make money Wana get nice watches, Jewelleries, Coins and Medallions Or may be you are interested in Unique Wellness products How about holidays All of this and more valuable products in this website http://www.quest.net/products/en/ Then enter https://portal.quest.net/qnver14/verifyreferrer.aspx IR ID of my referrer * : HY865731 Country I live in * : (your country) Click Shop Now Processed and enjoy shopping Regards... From __peter__ at web.de Mon Jun 16 13:09:52 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Jun 2008 19:09:52 +0200 Subject: 'string'.strip(chars)-like function that removes from the middle? References: Message-ID: Ethan Furman wrote: > The strip() method of strings works from both ends towards the middle. > Is there a simple, built-in way to remove several characters from a > string no matter their location? (besides .replace() ;) >>> identity = "".join(map(chr, range(256))) >>> 'www.example.com'.translate(identity, 'cmowz.') 'exaple' Peter From cokofreedom at gmail.com Tue Jun 24 05:16:50 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 24 Jun 2008 02:16:50 -0700 (PDT) Subject: Python 3000 vs Perl 6 References: Message-ID: <89fbe834-68b7-49e6-8136-62dee53c2f40@t54g2000hsg.googlegroups.com> On Jun 24, 10:36 am, "Corey G." wrote: > What I meant, in terms of dealing with accurate or non-accurate rumors > is with speed, yes. There are plenty of comparisons where Perl is > 4-15x faster then Python for 'some' operations regarding regular > expressions, etc. > > For me personally, this means absolutely nothing because if I spend > 50x more time comprehending spaghetti, obfuscated Perl code it's > irrelevant. The main concern (my concern) is whether or not Perl 6 is > more like Java with pre-compiled byte code (did I say that right) and > whether or not individuals without the ability to see past the surface > will begin to migrate towards Perl 6 for its seemingly faster > capabilities. > > With Perl 6 taking 10+ years, if/when it actually gets released, will > it be technically ahead of Python 3000? Is Parrot worth the extra > wait the Perl 6 project is enduring? My own answer would be a > resounding no, but I am curious as to what others think. :) > > -Thanks! > >From a quick read of the Parrot Wiki page it would appear they hope to one day allow the compilation of BOTH Perl 6 and Python, which could be interesting. Towards the speed, http://shootout.alioth.debian.org/debian/benchmark.php?test=all&lang=all puts Python ahead of perl, and Python Psyco ahead of Parrot PIR. Though I haven't looked at each benchmark comparison so it is hard to tell. Towards what Perl 6 offers, the Wiki on it seems to indicate it will be a clean up of Perl 5 as well as adding of many features from other languages. It seems like Lary has gone for the TAKE IT ALL approach which could work out well in providing practically any format for creating Perl scripts. Or it could cause huge confusion as users ask for help and received a 1001 different approaches... Towards it being more advanced than Python 3k, time will tell. Both are still active and getting updated. So while I personally will stay with Python, others may move, or use both. From johnjsal at gmailNOSPAM.com Sat Jun 14 21:40:24 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sat, 14 Jun 2008 21:40:24 -0400 Subject: Creating a TCP/IP connection on already-networked computers In-Reply-To: References: <4853f269$0$11615$607ed4bc@cv.net> <4854123f$0$5017$607ed4bc@cv.net> <485413d0$0$4997$607ed4bc@cv.net> <485425b2$0$11631$607ed4bc@cv.net> Message-ID: <4854730e$0$11637$607ed4bc@cv.net> Grant Edwards wrote: > If the two computers are in no way connected via any type of > network, then the two programs won't be able to talk to each > other. > > The programs can't create a network, they can only use one that > already exists. But isn't that the point of the program, to create a network between the two computers? Isn't that what the host and port are used for, to open a connection? (Just to clarify, when I say "in no way connected", I don't mean not connected to the internet in general. I know they need access to the internet for any kind of networking program to work at all.) From shriphanip at gmail.com Sun Jun 1 09:25:09 2008 From: shriphanip at gmail.com (Shriphani) Date: Sun, 1 Jun 2008 06:25:09 -0700 (PDT) Subject: SPOJ, Problem Code: sumtrian, Reducing time taken to solve. Message-ID: Hi, I was trying to solve the sumtrian problem in the SPOJ problem set ( https://www.spoj.pl/problems/SUMTRIAN/ ) and this is the solution I submitted: http://pastebin.ca/1035867 The result was, "Your solution from 2008-06-01 15:13:06 to problem SUMTRIAN, written in Python, has exceeded the allowed time limit." I suspect that the first portion of my solution which looks at the input, figures out the number of triangles and forms a list that contains lists containing each row of the triangle, is wrong. I am not too sure how to optimize it. I would appreciate help. Thanks, Shriphani Palakodety From auch-ich-m at g-kein-spam.com Fri Jun 6 13:03:23 2008 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Fri, 06 Jun 2008 19:03:23 +0200 Subject: lots of futex_wait calls References: Message-ID: <26384647.rjfOZSXm3s@news.perlig.de> skunkwerk wrote: > I've got a python program written for the django web framework that > starts about 100 threads. When I start the server, it sometimes eats > up 100% of the CPU for a good minute or so... though none of the > threads are CPU-intensive > > doing a strace on the program, i found lots of calls like this: > > select(5, [4], [], [], {1, 0}) = 0 (Timeout) > futex(0x86a3ce0, FUTEX_WAIT, 0, NULL) = 0 > > i've read the man page for futex... but is this normal? More or less. Most of the futex calls (if not all) are grabbing or releasing the global interpreter lock (GIL). It's usually helpful to increase the thread-schedule-checkinterval in order to lessen the system load (especially the number of context switches). See sys.setcheckinterval. nd From circularfunc at yahoo.se Fri Jun 13 11:00:39 2008 From: circularfunc at yahoo.se (cirfu) Date: Fri, 13 Jun 2008 08:00:39 -0700 (PDT) Subject: weird iteration/assignment problem Message-ID: <61936860-de3f-4bb1-8806-08f9f21ad113@m36g2000hse.googlegroups.com> for i in xrange(0, len(texts)): texts[i] = "yes" for i in texts: i = "no" why is the first one working but not the second. i mean i see why the firts one works but i dont udnerstand why the second doesnt. From kurt.mueller at aerodynamics.ch Tue Jun 24 04:56:21 2008 From: kurt.mueller at aerodynamics.ch (Kurt Mueller) Date: Tue, 24 Jun 2008 10:56:21 +0200 Subject: String split with " and/or ' and/or \ Message-ID: <4860B6B5.3000902@aerodynamics.ch> How to (super)split a string (literal) containing " and/or ' and/or \. example: ' a " b b " c\ c '.supersplit(' ') -> ['a', ' b b ', 'c c'] Thanks and Gr?essli -- Kurt M?ller: kurt.mueller at aerodynamics.ch From george.sakkis at gmail.com Sun Jun 1 12:42:01 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 1 Jun 2008 09:42:01 -0700 (PDT) Subject: Conjunction List References: <2d1bbc53-0c98-4d6e-aedd-1bf4c966410b@v26g2000prm.googlegroups.com> Message-ID: On May 31, 8:01 pm, ccy56... at gmail.com wrote: > http://codepad.org/MV3k10AU > > I want to write like next one. > > def conjunction(number=a[1],name=b[1],size=c[1]): > flag = a[0]==b[0]==c[0] > if flag: > for e in zip(number,name,size): > print e > > conjunction(a,b,c) > > ----------------------------------------------------------------------------------------------------- > function args receive sequence element: > > def somefunc(name=elm1[1], size=elm2[1], color=elm3[1]): > for e in zip(name, size, color): > print e, > > conjunction(a,b,c) > ----------------------------------------------------------------------------------------------------- > > not like two case: > ----------------------------------------------------------------------------------------------------- > > def somefunc(elm1, elm2, elm3): > name = elm1[1]; size = elm1[1]; color = elm1[1] # best solution? > for e in zip(name, size, color): > print e, > > conjunction(a,b,c) > ----------------------------------------------------------------------------------------------------- > > def somefunc(elm1, elm2, elm3, **attr): > for e in zip(attr['name'], attr['size'], attr['color']): > print e, > > conjunction(a,b,c, name=a[1], size=b[1], color=c[1]) # many args... > ----------------------------------------------------------------------------------------------------- > > What's a good approach to get the conjunction nest-list-data? The one you comment with "best solution?" is ok for this example. If you dislike the repetitive part of setting the flag and getting the second element of each argument, or especially if you want to generalize it to more than three arguments, here's one way to do it: def conjunction(*args): if not args: return first = args[0][0] if all(arg[0]==first for arg in args): for e in zip(*(arg[1] for arg in args)): print e >>> conjuction(a,b,c) ('0', 'one', '0%') ('1', 'two', '50%') ('2', 'three', '100%') HTH, George From ptmcg at austin.rr.com Fri Jun 20 10:35:52 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 20 Jun 2008 07:35:52 -0700 (PDT) Subject: Strange re problem References: <2a0a6f87-f72e-4190-85f8-6e43821e313a@r66g2000hsg.googlegroups.com> Message-ID: <43b2c9ad-059a-4261-9b0c-715f86652469@m73g2000hsh.googlegroups.com> On Jun 20, 6:01?am, TYR wrote: > OK, this ought to be simple. I'm parsing a large text file (originally > a database dump) in order to process the contents back into a SQLite3 > database. The data looks like this: > > 'AAA','PF',-17.416666666667,-145.5,'Anaa, French Polynesia','Pacific/ > Tahiti','Anaa';'AAB','AU',-26.75,141,'Arrabury, Queensland, > Australia','?','?';'AAC','EG',31.133333333333,33.8,'Al Arish, > Egypt','Africa/Cairo','El Arish International';'AAE','DZ', > 36.833333333333,8,'Annaba','Africa/Algiers','Rabah Bitat'; > > which goes on for another 308 lines. As keen and agile minds will no > doubt spot, the rows are separated by a ; so it should be simple to > parse it using a regex. So, I establish a db connection and cursor, > create the table, and open the source file. Using pyparsing, you can skip all that "what happens if there is a semicolon or comma inside a quoted string?" noise, and get the data in a trice. If you add results names (as I've done in the example), then loading each record into your db should be equally simple. Here is a pyparsing extractor for you. The parse actions already do the conversions to floats, and stripping off of quotation marks. -- Paul data = """ 'AAA','PF',-17.416666666667,-145.5,'Anaa, French Polynesia','Pacific/ Tahiti','Anaa';'AAB','AU',-26.75,141,'Arrabury, Queensland, Australia','?','?';'AAC','EG',31.133333333333,33.8,'Al Arish, Egypt','Africa/Cairo','El Arish International';'AAE','DZ', 36.833333333333,8,'Annaba','Africa/Algiers','Rabah Bitat'; """.splitlines() data = "".join(data) from pyparsing import * num = Regex(r'-?\d+(\.\d+)?') num.setParseAction(lambda t: float(t[0])) qs = sglQuotedString.setParseAction(removeQuotes) CMA = Suppress(',') SEMI = Suppress(';') dataRow = qs("field1") + CMA + qs("field2") + CMA + \ num("long") + CMA + num("lat") + CMA + qs("city") + CMA + \ qs("tz") + CMA + qs("field7") + SEMI for dr in dataRow.searchString(data): print dr.dump() print dr.city,dr.long,dr.lat Prints: ['AAA', 'PF', -17.416666666666998, -145.5, 'Anaa, French Polynesia', 'Pacific/ Tahiti', 'Anaa'] - city: Anaa, French Polynesia - field1: AAA - field2: PF - field7: Anaa - lat: -145.5 - long: -17.4166666667 - tz: Pacific/ Tahiti Anaa, French Polynesia -17.4166666667 -145.5 ['AAB', 'AU', -26.75, 141.0, 'Arrabury, Queensland, Australia', '?', '?'] - city: Arrabury, Queensland, Australia - field1: AAB - field2: AU - field7: ? - lat: 141.0 - long: -26.75 - tz: ? Arrabury, Queensland, Australia -26.75 141.0 ['AAC', 'EG', 31.133333333332999, 33.799999999999997, 'Al Arish, Egypt', 'Africa/Cairo', 'El Arish International'] - city: Al Arish, Egypt - field1: AAC - field2: EG - field7: El Arish International - lat: 33.8 - long: 31.1333333333 - tz: Africa/Cairo Al Arish, Egypt 31.1333333333 33.8 ['AAE', 'DZ', 36.833333333333002, 8.0, 'Annaba', 'Africa/Algiers', 'Rabah Bitat'] - city: Annaba - field1: AAE - field2: DZ - field7: Rabah Bitat - lat: 8.0 - long: 36.8333333333 - tz: Africa/Algiers Annaba 36.8333333333 8.0 From ustrum at gmail.com Tue Jun 10 07:05:04 2008 From: ustrum at gmail.com (ustrum at gmail.com) Date: Tue, 10 Jun 2008 04:05:04 -0700 (PDT) Subject: DICOM library Message-ID: <8c79237c-4e75-4908-93f2-393f750d90fc@m36g2000hse.googlegroups.com> Hi everybody! I've been looking for a python library wich allows me to work with with DICOM files, for medical image processing. Finding nothing at first, evenctually i've find the gdcm library, wich is suposed to be for c developement, but they say that you can use it with python, as "It is automatically wrapped to python (using swig)". So, the cuestion is: how can I use this kind of library, wich is suposed to be used with c, in python? When I download the tarball there ae only 2 .py files. shall I install the whole library for using in C, and then try to import the gdcm module in python? becouse i'm afraid it won't work. Thanks in advance, and sorry for my english, wich is not very good actually. Sorry for asking for something before trying everything, but i'm almost desperate to find a library like that. From aweraw at gmail.com Thu Jun 12 10:45:46 2008 From: aweraw at gmail.com (Aidan) Date: Fri, 13 Jun 2008 00:45:46 +1000 Subject: Summing a 2D list In-Reply-To: References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <6bcokhF3b2mo7U1@mid.uni-berlin.de> <485131a1$0$11175$c3e8da3@news.astraweb.com> Message-ID: Aidan wrote: > Mark wrote: >> John, it's a QuerySet coming from a database in Django. I don't know >> enough about the structure of this object to go into detail I'm >> afraid. >> >> Aidan, I got an error trying your suggestion: 'zip argument #2 must >> support iteration', I don't know what this means! > > well, if we can create 2 iterable sequences one which contains the user > the other the scores, it should work > > the error means that the second argument to the zip function was not an > iterable, such as a list tuple or string > > can you show me the lines you're using to retrieve the data sets from > the database? then i might be able to tell you how to build the 2 lists > you need. > wait you already did... predictions = Prediction.objects.all() pairs = [(p.predictor.id,p.predictionscore) for p in predictions] those 2 lines will will build a list of user/score pairs. you can then replace the call to zip with pairs any luck? From kylotan at gmail.com Fri Jun 13 10:27:57 2008 From: kylotan at gmail.com (Ben Sizer) Date: Fri, 13 Jun 2008 07:27:57 -0700 (PDT) Subject: Create list from string References: Message-ID: On Jun 13, 3:15?pm, ericdaniel wrote: > Hi, > > I'm new to Python and I need to do the following: > > from this: ? s = "978654321" > to this : ? ? ?["978", "654", "321"] What are your criteria for splitting this string? Every 3 characters? If there isn't an even multiple of 3, which group should be shorter, the first, the last, or maybe some other? And do you even really need this as a string at all? Perhaps you really just wanted to format the output of an integer? (I think that may be done via the locale, but I am not sure.) Often it's best to specify why you want to do something, as when using a new language there is often a better way to achieve what you want than the first way that occurs to you. -- Ben Sizer From see.signature at no.spam Mon Jun 23 05:08:43 2008 From: see.signature at no.spam (Eric Brunel) Date: Mon, 23 Jun 2008 11:08:43 +0200 Subject: inheritance question... References: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> <09ec833f-7751-4991-8d09-45c200fb4c18@z72g2000hsb.googlegroups.com> Message-ID: Preamble: when posting a brand new question, you'd better not replying to an existing completely unrelated message. In most viewers, this will cause your message to appear in the thread for the original question and far less people will see it. So better create a brand new thread. On Fri, 20 Jun 2008 23:19:37 +0200, Hamish McKenzie wrote: > I have this class: > > class Vector(object): > TOL = 1e-5 > def __eq__( self, other, tolerance=TOL ): > print tolerance > > > shortened for clarity obviously. so I want to subclass this class like > so: > > class BigVector(Vector) > TOL = 100 > > > for example if I was working with large vectors which I knew would never > be very close hence the large tolerance. this doesn't work however - > the TOL class variable, while overridden in BigVector, is still using > the Vector.TOL variable in the __eq__ method. > > > which kinda makes sense to a certain degree, but how do I get the > behaviour where doing: > > BigVector().__eq__( otherVec ) > > > prints 100 instead of 1e-5? > > does this question make sense? not sure how clearly I'm phrasing my > question... any of you guys python experts? There's just no way. The default values for function/method arguments are evaluated when the function definition is interpreted. When the __eq__ method is defined, TOL is 1e-5, so that will be the value used in the method, whatever you may do afterwards. > > I *could* do this, but its ugly: > > class Vector(object): > TOL = 1e-5 > def __eq__( self, other, tolerance=None ): > if tolerance is None: tolerance = self.TOL > print tolerance Well, ugliness is in the eye of the beholder... ;-) Even if you find it ugly, that's the Python way to do it. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From bruno.desthuilliers at gmail.com Mon Jun 30 13:49:57 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 30 Jun 2008 10:49:57 -0700 (PDT) Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> Message-ID: On 30 juin, 19:19, Mike wrote: > On Jun 30, 10:57 am, Bruno Desthuilliers > 42.desthuilli... at websiteburo.invalid> wrote: > > > Some (if not most) templating systems use their own mini-language to > > handle presentation logic. > > IMHO this is the funniest (worst) part of all this 'templating' > buss :) > It reminds me the good old slogan: "Have you invented your own GUI > library yet?" Yeps, there's something true here. FWIW, my favorite templating system so for is still Mako, for it doesn't try to reinvent yet another language - just uses Python as both the target runtime and the scripting language. (snip) > > > Or could it just be that > > > this is a *good* way to mix HTML and Python, and there are other ways > > > which may be bad? > > > Bingo. > > Then what is so *good* about it, why embedding HTML into Python is not > good? Who said embedding HTML in Python was bad ? Did you _carefully_ read John's question ?-) wrt/ what's so good about it: web designers are usually better at working with this approach (whatever scripting language embedded in html) than they are writing Python code - either as plain strings or using a more declarative syntax like the one provided by Stan or equivalent html generators. But nothing prevents you from using Mako's internals directly if you find it easier and more maintainable !-) From dullrich at sprynet.com Thu Jun 12 13:57:52 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 12 Jun 2008 12:57:52 -0500 Subject: get keys with the same values References: <3fdafa74-2043-4052-bdec-843f69d9e5fa@e39g2000hsf.googlegroups.com> Message-ID: In article <3fdafa74-2043-4052-bdec-843f69d9e5fa at e39g2000hsf.googlegroups.com>, Paul McGuire wrote: > On Jun 12, 6:41?am, David C. Ullrich wrote: > > On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader > > wrote: > > > > >Hello, > > > > >I have a dictionary and will get all keys which have the same values. > > > > > > > d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} > > > > dd = {} > > > > for key, value in d.items(): > > ? try: > > ? ? dd[value].append(key) > > ? except KeyError: > > ? ? dd[value] = [key] > > > > > Instead of all that try/except noise, just use the new defaultdict: That's certainly much better. The machine where I am in the early morning is still stuck with Python 1.5.3... > >>> from collections import defaultdict > >>> > >>> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} > >>> > >>> dd = defaultdict(list) > >>> for key, value in d.items(): > ... dd[value].append(key) > ... > >>> for k,v in dd.items(): > ... print k,':',v > ... > 1 : ['a', 'e'] > 2 : ['c'] > 3 : ['b', 'd'] > 4 : ['f'] > > -- Paul -- David C. Ullrich From jeff at jmcneil.net Wed Jun 18 12:58:05 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 18 Jun 2008 09:58:05 -0700 (PDT) Subject: Looking for lots of words in lots of files References: <6bskfpF3d3v42U1@mid.uni-berlin.de> Message-ID: <4df60f85-9c5c-41b2-b3d0-5891a1d33e4b@27g2000hsf.googlegroups.com> On Jun 18, 10:29?am, "Diez B. Roggisch" wrote: > brad wrote: > > Just wondering if anyone has ever solved this efficiently... not looking > > for specific solutions tho... just ideas. > > > I have one thousand words and one thousand files. I need to read the > > files to see if some of the words are in the files. I can stop reading a > > file once I find 10 of the words in it. It's easy for me to do this with > > a few dozen words, but a thousand words is too large for an RE and too > > inefficient to loop, etc. Any suggestions? > > Use an indexer, like lucene (available as pylucene) or a database that > offers word-indices. > > Diez I've been toying around with Nucular (http://nucular.sourceforge.net/) a bit recently for some side projects. It's pure Python and seems to work fairly well for my needs. I haven't pumped all that much data into it, though. From serbulentu at gmail.com Mon Jun 30 10:29:11 2008 From: serbulentu at gmail.com (python_newbie) Date: Mon, 30 Jun 2008 07:29:11 -0700 (PDT) Subject: insertion sorts... References: <06adb999-c7e2-4475-a49f-dbfbe042f4fd@r66g2000hsg.googlegroups.com> <5f0111a3-c1b9-4864-bae3-32fa324c4e5e@j22g2000hsf.googlegroups.com> <841dd5b8-d99d-4a60-ad39-b7c9563fca1d@d1g2000hsg.googlegroups.com> <8ceb6019-6474-485c-8daf-91111c85040c@m36g2000hse.googlegroups.com> Message-ID: On 25 Haziran, 17:44, MRAB wrote: > On Jun 25, 11:37?am, "A.T.Hofkamp" wrote: > > > > > On 2008-06-25, python_newbie wrote: > > > > On 24 Haziran, 04:33, Terry Reedy wrote: > > > Thanks for all answers. At the end i ve only one point. If a decide to > > > copy list to iterate when will i have to do this ? Before the > > > iteration ? And then iterate through one list and change value of the > > > other ? > > > Before starting the iteration would be a good point.... > > > I usually do in such cases: > > > for x in mylist[:]: > > ? ?... > > > making a copy just before the for loop starts. > > > Lately, I have started avoiding in-place modification of lists. Instead, I > > construct a new list from scratch inside the for-loop, and replace the old list > > with the newly constructed list afterwards like: > > > new_list = [] > > for x in mylist: > > ? ?.... > > ? ?new_list.append(x) > > > mylist = new_list > > > by appending a different value than the original or by not appending, you can > > influence the contents of the new list. > > > I find this solution nicer than in-place modification of an existing list. > > > Sincerely, > > Albert > > And if you were originally doing in-place modification because there > were also other references to the list then you could just do: > > mylist[:] = new_list Thanks again. I see that you use two different syntax for lists "mylist = new_list" and "mylist[:] = new_list" these are same i think ? From fc14301589 at icqmail.com Sat Jun 14 05:29:54 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Sat, 14 Jun 2008 17:29:54 +0800 Subject: Checking list by using of exception References: <3bdcc52d-2432-4b28-8188-bf7c811859d1@d45g2000hsc.googlegroups.com> Message-ID: <48538f92_2@news.tm.net.my> On 15:37, venerd? 13 giugno 2008 Nader wrote: > try: > list_of_files != [] > get the files > For file in list_of_files: try: myfile = open(file, 'r') except (IOError, OSError): print"Your %s file wasn't open" %file # here you can do something with your open file as read option myfile.readlines() # for example -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From danb_83 at yahoo.com Tue Jun 24 23:32:45 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Tue, 24 Jun 2008 20:32:45 -0700 (PDT) Subject: newb question on strings References: <998616c1-8b96-49a7-b830-f122f5f0ee54@a32g2000prf.googlegroups.com> Message-ID: <5a29e27d-c1b4-4028-8e20-841c58e3f006@27g2000hsf.googlegroups.com> On Jun 24, 4:04?pm, "shand... at gmail.com" wrote: > Are you trying to escape for a regular expression? > > Just do re.escape(). > > >>> print re.escape('Happy') > Happy > >>> print re.escape("Frank's Diner") > > Frank\'s\ Diner > > If you're escaping for URLs, there's urllib2.quote(), for a command > line, use subprocess.list2cmdline. And if you're escaping for string literals in Python (or C and its descendants), you can do: >>> print "Frank's Diner".encode('string-escape') Frank\'s Diner From paul.hankin at gmail.com Thu Jun 12 23:19:19 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 12 Jun 2008 20:19:19 -0700 (PDT) Subject: Notify of change to list References: <8b34cc2b-aa3a-4788-b849-1f926284c7ca@m36g2000hse.googlegroups.com> Message-ID: <90336d65-1537-46a5-92e1-9a8712d56e88@8g2000hse.googlegroups.com> On Jun 13, 12:00?pm, "Alan J. Salmoni" wrote: > My question is how can my program be notified of a change to a class > attribute that is a list? You can't. But you can replace lists inside your class with a list that notifies changes. Something like this: class NotifyingList(list): def __setitem__(self, i, v): print 'setting', i, 'to', v list.__setitem__(self, i, v) [[You'll likely need to redefine __setslice__, __delitem__, __delslice__, append and extend as well]]. >>> x = NotifyingList([1, 2, 3]) >>> x[1] = 4 setting 1 to 4 >>> x [1, 4, 3] If users of your class are allowed to replace attributes with their own lists, you'll have to catch these and convert to NotifyingLists; and it may be somewhat messy. I hope this is useful to you. -- Paul Hankin From jeffrey at fro.man Wed Jun 18 17:03:51 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Wed, 18 Jun 2008 14:03:51 -0700 Subject: Who is using python-ldap with Python 1.5.x and 2.0-2.2? References: <6h7ii5-l9m.ln1@nb2.stroeder.com> Message-ID: Michael Str?der wrote: > Please tell me > which Python version you're using We do have one venerable machine here at work using python2.2 with python-ldap2.0.0pre04. As you can see, we haven't bothered to update either in quite a while ;-) > and why it'd be important for you to > have python-ldap updates still supporting it. For us, it is not important. Should we want or need to update python-ldap on that one machine, we'll update python along with it (and vice versa.) Thank you, Jeffrey From mensanator at aol.com Mon Jun 30 19:45:36 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 30 Jun 2008 16:45:36 -0700 (PDT) Subject: The Yield statement References: Message-ID: <95354739-b4ba-47cb-b2c3-437365cc986b@z72g2000hsb.googlegroups.com> On Jun 30, 5:31?pm, Alex Bryan wrote: > Okay, so i don't really understand the Yield thing and i know it is ? > useful. I've read a few things about it but it is all programming ? > jargon and so basically it is hard for me to understand. So can anyone ? > give me a description or link me to a site that has a good definition ? > and/or examples of it? If you could I would really appreciate it. You know what a function does, right? If I were to say x = NextPrime(3) then x should be set to 5. The NextPrime function does this by evaluating the input argument (3) and doing return p as the last statement (p having been determined to be 5). Now, suppose you had a function Primes (i.e., a function that returns ALL the primes). Obviously, since there are an infinite number of them, the function would never end since it would eventually eat up all your memory trying to create a list with infinite elements. However, if Primes were a generator, you could have it return just 1 result at a time. The generator would keep track of the last prime issued so that every .next() call would give you the next prime in the sequence. That's what "yield" does. It functions like a return, only returning a single element of an iteration. For infinite loops, the program simply stops calling the function when it has enough (or tells the function to stop). Here's an example. Note that before it enters the output loop it does a couple things. First, it checks for valid input. If not valid, it executes a "return" statement which kills the generator. If valid, it issues a "yield" prior to the loop. It must do this to issue the first partition. The loop will issue all subsequent partitions with its "yield" statements. This particular generator is always a finite loop. Although the number of generated partitions can be quite large, best to test by doing C(depth-1,width-1) before asking for all the results (which is what "for i in p" does). def partition_generator(depth,width): """creates all partions of a given depth,widtth (depth>=width) depth objects in width bins such that each bin has at least 1 object this function is a generator (does comb(depth-1,width-1) partitions) partition_generator(depth,width) depth: total inverse rule 1 count (p of 2**p) width: total inverse rule 2 count (q of 3**q) sv: sequence vector (the partition) returns sequence vector [sv] """ def move_col(c): sv[c-1] += 1 sv[c] -= 1 def find_c(): i = -1 while i<0: if sv[i]>1: return i i -= 1 def rollover(c): move_col(c) sv[-1] = sv[c] sv[c] = 1 if depth= to width',width return # kills generator max_element = depth - width + 1 sv = [1 for i in range(width)] sv[-1] = max_element yield sv[:] # first partition while sv[0] <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> <484cf5f6$0$15495$426a74cc@news.free.fr> <127975a3-b3d9-4799-9673-b292ec8d37e3@x19g2000prg.googlegroups.com> <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> <484e3526$0$30894$426a74cc@news.free.fr> <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> <783c55ec-a294-4600-91d9-4a0d78632c49@t12g2000prg.googlegroups.com> <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> <484f880c$0$6412$426a74cc@news.free.fr> Message-ID: On Jun 11, 2:36 am, Paul Boddie wrote: > Maybe, but I'd hope that some of those programmers would be at least > able to entertain what Russ has been saying rather than setting > themselves up in an argumentative position where to concede any > limitation in Python might be considered some kind of weakness that > one should be unwilling to admit. Thanks. I sometimes get the impression that Desthuilliers thinks of this forum like a pack of dogs, where he is the top dog and I am a newcomer who needs to be put in his place. I just wish he would take a chill pill and give it a rest. I am not trying to challenge his position as top dog. All I did was to suggest that a keyword be added to Python to designate private data and methods without cluttering my cherished code with those ugly leading underscores all over the place. I don't like that clutter any more than I like all those semi-colons in other popular languages. I was originally attracted to Python for its clean syntax, but when I learned about the leading-underscore convention I nearly gagged. If Desthuilliers doesn't like my suggestion, then fine. If no other Python programmer in the world likes it, then so be it. But do we really need to get personal about it? Python will not be ruined if it gets such a keyword, and Desthuilliers would be perfectly free to continue using the leading-underscore convention if he wishes. Where is the threat to his way of life? From gh at ghaering.de Wed Jun 11 07:50:48 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 11 Jun 2008 13:50:48 +0200 Subject: Parallel python + ?? In-Reply-To: References: Message-ID: Thor wrote: > Hi, > > I am running a program using Parallel Python and I wonder if there is a > way/module to know in which CPU/core the process is running in. Is that > possible? This is of course OS-specific. On Linux, you can parse the proc filesystem: >>> open("/proc/%i/stat" % os.getpid()).read().split()[39] You can use the "taskset" utility to query or set CPU affinity on Linux. -- Gerhard From casey.mcginty at gmail.com Fri Jun 27 21:21:39 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Fri, 27 Jun 2008 15:21:39 -1000 Subject: Help with Borg design Pattern Message-ID: Hi, I'm trying to implement a simple Borg or Singleton pattern for a class that inherits from 'dict'. Can someone point out why this code does not work? class MyDict( dict ): __state = {} def __init__(self): self.__dict__ = self.__state a = MyDict() a['one'] = 1 a['two'] = 2 print a print MyDict() -------------- next part -------------- An HTML attachment was scrubbed... URL: From hat at se-162.se.wtb.tue.nl Tue Jun 17 05:40:56 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 17 Jun 2008 11:40:56 +0200 Subject: Showing a point in Gnuploy.py References: <5360d45b-7b62-4154-bb08-855dfafeae61@m36g2000hse.googlegroups.com> Message-ID: On 2008-06-16, arslanburney at gmail.com wrote: > Hello. Could some1 tell me how i could "display" a specific point in > gnuplot.py. Supposingly if i have a point of intersection (2,3). How > can i show this on the graph? As in how can i write near the point of > intersection the value :(2,3). > Thnx 1. Find out in the Gnuplot manual what command to enter 2. Send the command to Gnuplot using g() function-call From space.captain.face at gmail.com Sat Jun 7 00:35:26 2008 From: space.captain.face at gmail.com (Kalibr) Date: Fri, 6 Jun 2008 21:35:26 -0700 (PDT) Subject: Dynamically naming objects. References: <8a99c3fa-1eeb-49b3-a714-b6063ec1daab@d19g2000prm.googlegroups.com> Message-ID: <3d2a85b2-255d-4e93-8cfb-e2772f57b69a@u6g2000prc.googlegroups.com> On Jun 7, 1:20 pm, Hans Nowak wrote: > Kalibr wrote: > > I've been developing a small script to fiddle with classes, and came > > accross the following problem. Assuming I get some user input asking > > for a number, how would I spawn 'n' objects from a class? > > > i.e. I have a class class 'user' and I don't know how many of them I > > want to spawn. > > > Any ideas? > > Sure. This will give you a list of n instances of user: > > [user() for i in range(n)] > > Of course, you could also use a good old for loop: > > for i in range(n): > u = user() > ...do something with u... > > Hope this helps! > > -- > Hans Nowak (zephyrfalcon at gmail dot com)http://4.flowsnake.org/ whoops, replied to author.... What I wanted to ask before was won't 'u' be overwritten with a new object each time the loop ticks over? what I want to do is have, say 5 users in a game, so I'd have to spawn 5 objects. I can't do that because I have'nt hardcoded any object names for them. or does it somehow work? how would I address them if they all have the name 'u'? From gagsl-py2 at yahoo.com.ar Thu Jun 19 18:16:25 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 19 Jun 2008 19:16:25 -0300 Subject: py2exe & application add-ons References: Message-ID: En Thu, 19 Jun 2008 08:00:32 -0300, Alex Gusarov escribi?: > Hello, I've met a problem - I want my program working without Python > installation but I have some add-on mechanism (add-ons represented by > separate .py files, and application auto-recognize such files on > start). > > So, if I will using py2exe for main program and separate .py files for > add-ons, will I need Python installation on client machine? > Maybe other ways exist for such tasks? It should work fine. Note that when py2exe scans your project, it collects only the modules actually used by your code. Any module that you don't use (directly or indirectly) won't be available to the add-ons. -- Gabriel Genellina From george.sakkis at gmail.com Tue Jun 3 07:21:55 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 3 Jun 2008 04:21:55 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> Message-ID: On Jun 3, 1:42?am, "Russ P." wrote: > On Jun 2, 10:23 pm, alex23 wrote: > > > Then again, I have no issue with the current convention and personally > > find the idea of adding a "private" keyword makes as much sense as > > being able to syntactically define "model", "view" and "controller" > > methods. > > Well, the designers of C++, Java, and Ada, to name just three very > popular languages (well, two) seem to think it makes sense. But maybe > you know more than they know. And even more (well, almost all) languages use explicit delimiters for defining blocks instead of indentation, so what's your point ? From paul at boddie.org.uk Wed Jun 11 18:16:19 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 11 Jun 2008 15:16:19 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> <484cf5f6$0$15495$426a74cc@news.free.fr> <127975a3-b3d9-4799-9673-b292ec8d37e3@x19g2000prg.googlegroups.com> <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> <484e3526$0$30894$426a74cc@news.free.fr> <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> <783c55ec-a294-4600-91d9-4a0d78632c49@t12g2000prg.googlegroups.com> <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> <484f880c$0$6412$426a74cc@news.free.fr> Message-ID: On 11 Jun, 21:28, "Russ P." wrote: > > All I did was to suggest that a keyword be added to Python to > designate private data and methods without cluttering my cherished > code with those ugly leading underscores all over the place. I don't > like that clutter any more than I like all those semi-colons in other > popular languages. I was originally attracted to Python for its clean > syntax, but when I learned about the leading-underscore convention I > nearly gagged. I'm not bothered about having private instance data, but I think there's definitely a case to be answered about the double-underscore name-mangling convention. In the remote past, people were fairly honest about it being something of a hack, albeit one which had mostly satisfactory results, and unlike the private instance data argument which can often be countered by emphasising social measures, there has been genuine surprise about this particular method of preventing attribute name collisions - it's an issue which can trip up even careful programmers. Note also that the double-underscore convention is listed as a Python wart [1] and is described by Kuchling thus: "But it's a hack and a kludge; making privacy depend on an unrelated property such as the attribute's name is clumsy. At least this ugliness is limited to one specific and little-used case; few Python programmers ever bother to use this private variable feature." In my opinion there are too many people either defending the status quo (warts and all) or pushing the envelope in many areas that didn't overly bother people before (various Python 3000 features). Paul [1] http://wiki.python.org/moin/PythonWarts From eduardo.padoan at gmail.com Wed Jun 11 10:01:50 2008 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Wed, 11 Jun 2008 11:01:50 -0300 Subject: Does the python library of Google Data API is truly free? In-Reply-To: References: <3ac654b2-61b4-44ce-8e03-75f2344d5869@s50g2000hsb.googlegroups.com> <6fb57ab1-b0d2-4b7d-93c1-b919ca0e51a0@i36g2000prf.googlegroups.com> <3a296d00-d4e0-4f03-b6b3-bef4c5d628dd@x35g2000hsb.googlegroups.com> <6b5mloF3aeui4U1@mid.uni-berlin.de> <18115776-edf7-41b8-a5e9-639847c57a6a@x41g2000hsb.googlegroups.com> Message-ID: On Wed, Jun 11, 2008 at 10:28 AM, Kless wrote: > I understand very well that a service is a software which is accessed > through a network. > > And the description given on Wikipedia [1] is "A 'Web service' (also > Web Service) is defined by the W3C as "a software system designed to > support interoperable Machine to Machine interaction over a network." > > Now, to ending with this. I understand that (almos) everybody is pro > Google (and anti Microsoft), thinking that they have given a lot of > services for free. And it's very hard that people understand my > thinking. > > All that "free service" has a great price, that are the rights > about those data, and when Google want can to disable the free access > to that information. > > People don't realize that it's one more a company and like so it has > only an end, that is to obtain the greater number of benefits which > will be distributed between his shareholders. Within any years Google > will be as hated as Microsoft. > > At least I try to use the less possible those services than limit my > freedoms about data that has been contributed by me and another users. > > > [1] http://en.wikipedia.org/wiki/Web_service > -- > http://mail.python.org/mailman/listinfo/python-list > It is not a pro-GOOG/anti-MSFT child-thing. Google is a for-profit company. They are in it for the money. There is nothing wrong with it in a capitalist world, if you play by the rules. Also, services like this are scarce resources, it demands storage space, processing power, bandwidth, and etc to provide it, so it makes absolute sense that one would want money to keep providing it. Software per-se isn't scarce resources - you can copy it infinite times (but the work of writing it is, that is why there are programmers payed to write Free Software). Now you seem to be saying that if Google doesn't provide a scarce resource to you for Free (as in "Free Beer"), they will be hated just as you seem to hate Microsoft. I would hate Google if, after proving so much good stuff as free software, they gonne bankrupt for providing services without restrictions, completely for free. http://en.wikipedia.org/wiki/Scarcity -- Eduardo de Oliveira Padoan http://www.advogato.org/person/eopadoan/ http://twitter.com/edcrypt Bookmarks: http://del.icio.us/edcrypt From em00100 at hotmail.com Fri Jun 27 03:23:27 2008 From: em00100 at hotmail.com (em00100 at hotmail.com) Date: Fri, 27 Jun 2008 00:23:27 -0700 (PDT) Subject: the problem about the DLL file generate by py2exe References: <26b30d17-f6b4-45b3-b7fa-eb9702ac873c@u6g2000prc.googlegroups.com> <6che9sF3gadfaU1@mid.uni-berlin.de> Message-ID: <0cf910f5-d53b-4abc-8147-0c94da52503b@w5g2000prd.googlegroups.com> On Jun 26, 7:52?pm, "Diez B. Roggisch" wrote: > em00... at hotmail.com wrote: > > Dear All, > > > I have try to use the py2exe to compile the DLL file > > > first i write the simple python script "test01.py": > > def test001(): > > ? ? return 1 > > > then write the setup.py: > > # setup.py > > from distutils.core import setup > > import py2exe > > import sys > > > if len(sys.argv) == 1: > > ? ? sys.argv.append("py2exe") > > ? ? sys.argv.append("-q") > > > class Target: > > ? ? def __init__(self, **kw): > > ? ? ? ? self.__dict__.update(kw) > > ? ? ? ? # for the version info resources (Properties -- Version) > > ? ? ? ? self.version = "0.0.1" > > ? ? ? ? self.company_name = "Nil" > > ? ? ? ? self.copyright = "Nil" > > ? ? ? ? self.name = "test" > > > testTK = Target( > > ? ? # used for the versioninfo resource > > ? ? description = "test app", > > ? ? # what to build > > ? ? modules = ["test01"], > > ? ? script = "test01.py", > > ? ? # specify which type of com server you want (exe and/or dll) > > ? ? create_exe = False, > > ? ? create_dll = True) > > > #setup(windows=["hkcity_ide_main.py"]) > > setup( > > ? ? name='Test', > > ? ? options={"py2exe": {"bundle_files": 1, }}, > > ? ? zipfile=None, > > ? ? version='1.0', > > ? ? description='Test', > > ? ? author='', > > ? ? author_email='', > > ? ? url='', > > ? ? ctypes_com_server=[testTK], > > ? ? ) > > > and compile the it by the command: > > > C:\Python25\python setup.py py2exe > > > I use the script try to call the function "test001" in the "test01.py" > > from ctypes import * > > test01 = cdll.LoadLibrary("test01.dll") > > test001 = test01.test001 > > print test01() > > > However, this is out the error: > > AttributeError: function 'test001' not found > > > Is it any problem when i define the function? > > I guess you should define a python-function, inside which you call your > dll-function. > > Diez How to define the "python-function"? can you write the statement with my testing script, please. the "python-function" is place in "test01.py"? is it also need to define the "python-function" in "setup.py" thanks for you time From ncoghlan at gmail.com Wed Jun 4 08:09:08 2008 From: ncoghlan at gmail.com (NickC) Date: Wed, 4 Jun 2008 05:09:08 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> <873antn9il.fsf@benfinney.id.au> <6ammujF38poe2U2@mid.uni-berlin.de> <87y75llp5x.fsf@benfinney.id.au> <6an5a7F38poe2U3@mid.uni-berlin.de> <87tzg9l8fp.fsf@benfinney.id.au> Message-ID: <2378abb8-c0b6-4471-8572-7db78232ccfe@d19g2000prm.googlegroups.com> On Jun 4, 9:56 pm, Ben Finney wrote: > Those unit tests should *not*, though, exercise anything but the > public API, otherwise they're breaking encapsulation. Their assertion > should continue to be just as true after a refactoring of the internal > components as before. Python must have bad unit tests then - the CPython test suite explicitly tests private methods all the time. There's actually an extremely good reason for doing it that way: when the implementation of an internal method gets broken, the unit tests flag it explicitly, rather than having to derive the breakage from the breakage of 'higher level' unit tests (after all, you wouldn't factor something out into its own method or function if you weren't using it in at least a couple of different places). Black box testing (testing only the public API) is certainly important, but grey box and white box testing that either exploits knowledge of the implementation when crafting interesting test cases, or explicitly tests internal APIs can be highly beneficial in localising faults quickly when something does break (and as any experienced maintenance programmer will tell you, figuring out what you actually broke is usually harder than fixing it after you find it). From pfreixes at gmail.com Mon Jun 9 14:26:09 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Mon, 9 Jun 2008 20:26:09 +0200 Subject: GIL cpu multi core usage problem Message-ID: <207312b70806091126t6d9c3479hfe39368cd06b029e@mail.gmail.com> Hi List, Surly this is a recurring theme into python dev world, but I need your help for confirm if the follow image it's really http://www.milnou.net/~pfreixes/img/cpu_usage_gil_problem.png I'm writing a brief article for my blog and I need to make sure about the current problem with GIL and multi core environments, this picture try to explain with images the problem for scheduling multiple threads running python code of same interpreter into multiple cpu cores. Can anyone confirm to me this picture ? -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From karthikinfotech1985 at gmail.com Fri Jun 20 09:39:24 2008 From: karthikinfotech1985 at gmail.com (Lilly) Date: Fri, 20 Jun 2008 06:39:24 -0700 (PDT) Subject: SEXY__AUNTY__NEED__HARD__SEX Message-ID: SEXY__AUNTY__NEED__HARD__SEX *** WANT HAVE SECRET DATE WITH HOT SEXY SCHOOL GIRLS , HOUSEWIFE, AUNTIES ETC @@@CLICK MY PHOTO ---> GO TO MY PROFILE AND GET DETAIL FIND HOT GIRLS IN YOUR AREA FOR SEX http://glamourpriya.blogspot.com IMPRESS GIRLS WITH LOVE QUOTATIONS http://glamourpriya.blogspot.com MASALA PICS VIDEOS OF HOT CELEBRITY http://glamourpriya.blogspot.com JOIN COMMUNITY " SEX FRIENDS" TO FIND REAL SEX MATES http://glamourpriya.blogspot.com From bedouglas at earthlink.net Fri Jun 13 14:10:09 2008 From: bedouglas at earthlink.net (bruce) Date: Fri, 13 Jun 2008 11:10:09 -0700 Subject: python screen scraping/parsing In-Reply-To: Message-ID: <206701c8cd80$b7e5d560$0301a8c0@tmesa.com> Hi... got a short test app that i'm playing with. the goal is to get data off the page in question. basically, i should be able to get a list of "tr" nodes, and then to iterate/parse them. i'm missing something, as i think i can get a single node, but i can't figure out how to display the contents of the node.. nor how to get the list of the "tr" nodes.... my test code is: -------------------------------- #!/usr/bin/python #test python script import re import libxml2dom import urllib import urllib2 import sys, string from mechanize import Browser import mechanize #import tidy import os.path import cookielib from libxml2dom import Node from libxml2dom import NodeList ######################## # # Parse pricegrabber.com ######################## # datafile tfile = open("price.dat", 'wr+') efile = open("price_err.dat", 'wr+') urlopen = urllib2.urlopen ##cj = urllib2.cookielib.LWPCookieJar() Request = urllib2.Request br = Browser() user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values1 = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } headers = { 'User-Agent' : user_agent } url ="http://www.pricegrabber.com/rating_summary.php/page=1" #======================================= if __name__ == "__main__": # main app txdata = None #---------------------------- # get the kentucky test pages #br.set_cookiejar(cj) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.addheaders = [('User-Agent', 'Firefox')] br.open(url) #cj.save(COOKIEFILE) # resave cookies res = br.response() # this is a copy of response s = res.read() # s contains HTML not XML text d = libxml2dom.parseString(s, html=1) print "d = d",d #get the input/text dialogs #tn1 = "//div[@id='main_content']/form[1]/input[position()=1]/@name" t1 = "/html/body/div[@id='pgSiteContainer']/div[@id='pgPageContent']/table[2]/tbo dy" tr = "/html/body/div[@id='pgSiteContainer']/div[@id='pgPageContent']/table[2]/tbo dy/tr[4]" tr_=d.xpath(tr) print "len =",tr_[1].nodeValue print "fin" ----------------------------------------------- my issue appears to be related to the last "tbody", or tbody/tr[4]... if i leave off the tbody, i can display data, as the tr_ is an array with data... with the "tbody" it appears that the tr_ array is not defined, or it has no data... however, i can use the DOM tool with firefox to observe the fact that the "tbody" is there... so.. what am i missing... thoughts/comments are most welcome... also, i'm willing to send a small amount via paypal!! -bruce From python-url at phaseit.net Mon Jun 16 12:15:44 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 16 Jun 2008 16:15:44 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Jun 16) Message-ID: QOTW: "The problem [with C++] is, I never feel like I'm programing the *problem*, I always feel like I'm programming the *language*." - Roy Smith Alternatives to the Decimal type: http://groups.google.com/group/comp.lang.python/browse_thread/thread/9cd6dae725268afb/ How to invert a dictionary: http://groups.google.com/group/comp.lang.python/browse_thread/thread/a8222b9dd036e4ef/ Why wxPython is not a standard module (and why some consider it "unpythonic"): http://groups.google.com/group/comp.lang.python/browse_thread/thread/fde7680a07b79cb0/ Why map(None, ...) behaves in the specific way it does: http://groups.google.com/group/comp.lang.python/browse_thread/thread/fe79adf209747a52/ Raw strings, backslashes, filenames, GUI input... A big confusion finally resolved: http://groups.google.com/group/comp.lang.python/browse_thread/thread/43940eb4de069f63/ A simple and suposedly "safe" eval() that isn't safe at all - malicious users can execute arbitrary code: http://groups.google.com/group/comp.lang.python/browse_thread/thread/40d765b5eedfb57/ How networks work - mostly off topic, but clearly and simply explained: http://groups.google.com/group/comp.lang.python/browse_thread/thread/e84dff684899c3f2/ Confusing the Google Data API, the services it access, and their licenses: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b632eee9dc98b26c/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From peterbe at gmail.com Mon Jun 2 07:27:41 2008 From: peterbe at gmail.com (Peter Bengtsson) Date: Mon, 2 Jun 2008 04:27:41 -0700 (PDT) Subject: mocking a logging object Message-ID: <768fa8be-4bf2-40b2-9a26-6e59ff3b5a07@a70g2000hsh.googlegroups.com> In my unittest I want to override the logger of a working module so that it puts all logging messages in /tmp/test.log instead so that in my unittest I can inspect that it logs things correctly. Hopefully this "pseudo" code will explain my problem:: >>> import logging, os >>> logging.basicConfig(filename='/tmp/real.log', level=logging.INFO) >>> logger = logging.getLogger('Real') >>> logger.info('Real stuff') >>> os.path.isfile('/tmp/real.log') True >>> # do the monkey patching like the unit test does >>> logging.basicConfig(filename='/tmp/test.log', level=logging.INFO) >>> logger = logging.getLogger('Test') >>> logger.info('Test stuff') >>> os.path.isfile('/tmp/test.log') False >>> open('/tmp/real.log').read() 'INFO:Real:Real stuff\nINFO:Test:Test stuff\n' How can I change what file the logger should write to? From fake.mail at noone.be Sun Jun 22 06:24:35 2008 From: fake.mail at noone.be (Josip) Date: Sun, 22 Jun 2008 12:24:35 +0200 Subject: Storing value with limits in object References: Message-ID: > Not with normal vars, because = is a rebinding operator in Python, > rather than assignment. > > You can do (close to) the above with object properties. > > David. Yes, but it's done with built-in types like int and float. I suspect I could subclass from them and implement limits, but I would have to make seperate class for each type. Can I override conversion methods like int() and float() within my class? From larry.bates at websafe.com` Mon Jun 30 08:52:58 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 30 Jun 2008 07:52:58 -0500 Subject: HTML Parsing In-Reply-To: <2760a17a-63f9-4700-b31a-b1b60108a26e@m44g2000hsc.googlegroups.com> References: <2760a17a-63f9-4700-b31a-b1b60108a26e@m44g2000hsc.googlegroups.com> Message-ID: disappearedng at gmail.com wrote: > Hi everyone > I am trying to build my own web crawler for an experiement and I don't > know how to access HTTP protocol with python. > > Also, Are there any Opensource Parsing engine for HTML documents > available in Python too? That would be great. > > Check on Mechanize. It wraps Beautiful Soup inside of methods that aid in website crawling. http://pypi.python.org/pypi/mechanize/0.1.7b -Larry From jurgenex at hotmail.com Sun Jun 1 15:16:28 2008 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sun, 01 Jun 2008 19:16:28 GMT Subject: Python's doc problems: sort References: <929d5ce9-9063-4e6c-98aa-89526f89fba3@y18g2000pre.googlegroups.com> Message-ID: "Andrew Koenig" wrote: > wrote in message [Subject: Python's doc problems: sort] >> I want to emphasize a point here, as i have done quite emphatically in >> the past. The Python documentation, is the world's worst technical And WTF does Python documentation have to do with Perl of Lisp? szr, do you still have any doubts about the nature of xahlee? >Welcome to my killfile. Done a long, long time ago. Follow-up set. jue From desothier at yahoo.com Wed Jun 25 11:47:40 2008 From: desothier at yahoo.com (antar2) Date: Wed, 25 Jun 2008 08:47:40 -0700 (PDT) Subject: reading from list with paths Message-ID: Hello, Suppose this is a stupid question, but as a python beginner I encounter a lot of obstacles... so I would be very grateful with some help for following question: I would like to read files, of which the complete filepaths are mentioned in another textfile. In this textfile (list.txt) are for example the following paths: /data/chorec/chorec-nieuw/s01/S01C001M1/S01C001M1_1LG_f01.TextGrid /data/chorec/chorec-nieuw/s01/S01C001M1/ S01C001M1_1LGPseudo_f01.TextGrid /data/chorec/chorec-nieuw/s01/S01C001M1/S01C001M1_AVI1_f01.TextGrid I know how to open and read one file in my current directory, but after trying to find this out my self, I give up... So could someone help me and write some code so that I know how to open and read the content of the mentioned files. Thanks a lot Antar2 From vronskij at gmail.com Tue Jun 3 17:26:04 2008 From: vronskij at gmail.com (vronskij at gmail.com) Date: Tue, 3 Jun 2008 14:26:04 -0700 (PDT) Subject: Q about object identity References: Message-ID: <8f46276a-fbf8-4a5b-a446-645894de3465@k13g2000hse.googlegroups.com> On 3. J?n, 23:08 h., Christian Heimes wrote: > vrons... at gmail.com schrieb: > > > Hello, > > > I am testing object identity. > > > If I do it from the interpreter, I get strange results. > > >>>> print [] is [] > > False > > >>>> print id([]), id([]) > > 3083942700 3083942700 > > > Why is that? Isn't this an error? > > No, it's not an error. You are getting this result because the list > implementation keeps a bunch of unused list objects in a free list. It's > an optimization trick. Python has to create two different list objects > for "[] is []" while it can reuse the same list object for id([]) == id([]). > > Christian Aha. Thanks. jan bodnar From basti.wiesner at gmx.net Tue Jun 10 07:46:02 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Tue, 10 Jun 2008 13:46:02 +0200 Subject: Separators inside a var name References: <3be4a686-16fc-4b20-8c51-df1addc5cefc@m3g2000hsc.googlegroups.com> Message-ID: bruno.desthuilliers at gmail.com at Montag 09 Juni 2008 23:39: > On 9 juin, 20:05, "Sebastian \"lunar\" Wiesner" > wrote: >> Rainy at Montag 09 Juni 2008 19:29: >> > (snip) >> > From what I understand, scheme can have variables like var-name. I'm >> > curious about reasons that python chose to disallow this. >> >> "-" is an operator in Python. How should the parser know, >> whether "var-name" means "the object bound to var_dash_name" or "subtract >> the object bound to name from the object bound to var"? >> >> Scheme can allows such names, because its a functional programming >> language. > > Nope. Scheme and most lisps AFAICT allow such names because of lisp's > syntax, period. Scheme being (more or less) a functional language is > mostly unrelated. FWIW, there are pure functional languages that use > an infix operator syntax just like Python (and FWIW, Python itselfs > uses functions to implement operators) and don't accept dashes in > identifiers for the same reasons as Python : parsing ambiguity. Of course, you're right. My words were badly chosen, I just wanted to point out, that scheme can allow such names, because it doesn't use operators but functions for things like subtraction. My bad, sorry -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From john.gerald.mason at gmail.com Sun Jun 1 17:58:43 2008 From: john.gerald.mason at gmail.com (Mason) Date: Sun, 1 Jun 2008 14:58:43 -0700 (PDT) Subject: convert binary to float References: <0c15e8e1-948b-4bd6-a312-b1e055da859e@t54g2000hsg.googlegroups.com> Message-ID: <55c862a4-f798-443d-8b79-c4336ef8892c@t54g2000hsg.googlegroups.com> On Jun 1, 6:41 pm, Dennis Lee Bieber wrote: > On Sun, 1 Jun 2008 12:55:45 -0700 (PDT), Mason > declaimed the following in > comp.lang.python: > > > I have tried and tried... > > > I'd like to read in a binary file, convert it's 4 byte values into > > floats, and then save as a .txt file. > > > This works from the command line (import struct); > > > In [1]: f = open("test2.pc0", "rb") > > In [2]: tagData = f.read(4) > > In [3]: tagData > > Interpreter display of raw object name uses repr() > > > Out[3]: '\x00\x00\xc0@' > > > I can then do the following in order to convert it to a float: > > > In [4]: struct.unpack("f", "\x00\x00\xc0@") > > Out[4]: (6.0,) > > > But when I run the same code from my .py file: > > > f = open("test2.pc0", "rb") > > tagData = f.read(4) > > print tagData > > Display from a print statement uses str() > > > I get this (ASCII??): > > ?@ > > Probably not ASCII -- ASCII doesn't have that spanish (?) bottom row > quote... And a pair of null bytes don't take up screen space. > > > I only know how to work with '\x00\x00\xc0@'. > > > I don't understand why the output isn't the same. I need a solution > > that will allow me to convert my binary file into floats. Am I close? > > Can anyone point me in the right direction? > > Why do you have to /see/ the byte representation in the first > place... just feed the four bytes to the struct module directly. > > import struct > fin = open("test2.pc0", "rb") > tagFloat = struct.unpack("f", fin.read(4))[0] > print tagFloat > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ Thanks Dennis, I'm OK now. I just sort of dropped the ball for a bit :). Mason From keiths at apache-da.com Fri Jun 6 11:52:17 2008 From: keiths at apache-da.com (Keith Sabine) Date: Fri, 06 Jun 2008 16:52:17 +0100 Subject: SWIG -- Passing python proxy class instance to python callback Message-ID: <48495D31.7010400@apache-da.com> Hi Did you ever find a solution to this? I am having the exact same problem... - Keith I'm trying to pass a proxy class instance (SWIG generated) of CClass, to a python callback function from C++. The proxy class instance of CClass is created from a pointer to the C++ class CClass. Using the code below, I receive the error message: "AttributeError: 'PySwigObject' object has no attribute 'GetName'" The python callback function is being passed in through the clientdata pointer, and the CClass *class pointer is what's being converted to an instance of the SWIG proxy class and passed to the python callback function as an argument. static void PythonCallBack(CClass *class,void *clientdata) { PyObject *func, *arglist,*obj; PyObject *result; func = (PyObject *) clientdata; // Get Python function obj = SWIG_NewPointerObj((void*) cmd, SWIGTYPE_p_CSCSICommand, 1); //create instance of python proxy class from c++ pointer arglist=Py_BuildValue("(O)",*obj); //convert to tuple result = PyEval_CallObject(func,arglist); // Call Python Py_XDECREF(result); return; } Any input would greatly appreciated. Thanks, Jeff From jr9445 at ATT.COM Tue Jun 3 09:51:44 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Tue, 3 Jun 2008 08:51:44 -0500 Subject: regex help In-Reply-To: <0ac601c8c57e$3c9d6bc0$a501a8c0@office.ipglobal.net> References: <0ac601c8c57e$3c9d6bc0$a501a8c0@office.ipglobal.net> Message-ID: > From: python-list-bounces+jr9445=att.com at python.org > [mailto:python-list-bounces+jr9445=att.com at python.org] > On Behalf Of Support Desk > Sent: Tuesday, June 03, 2008 9:32 AM > To: python-list at python.org > Subject: regex help > > I am trying to put together a regular expression that will > rename users address books on our server due to a recent > change we made.? Users with address books user.abook need > to be changed to user at domain.com.abook I'm having trouble > with the regex. Any help would be appreciated. import re emails = ('foo.abook', 'abook.foo', 'bob.abook.com', 'john.doe.abook') for email in emails: print email, '-->', print re.sub(r'\.abook$', '@domain.com.abook', email) ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA623 From pandasagar at gmail.com Tue Jun 3 00:59:04 2008 From: pandasagar at gmail.com (sagar panda) Date: Tue, 3 Jun 2008 10:29:04 +0530 Subject: Please solve me the problem Message-ID: <905b76210806022159l1bcb0165r1096c491f665e914@mail.gmail.com> Hi I am sagar. I want to write a python script that will run the python scripts automatically from a directory. Please help me out to sovle this problem? -- with regards Mr. Sagar Panda Mob:9986142755 -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.wyburn at googlemail.com Wed Jun 18 06:19:19 2008 From: marc.wyburn at googlemail.com (marc wyburn) Date: Wed, 18 Jun 2008 03:19:19 -0700 (PDT) Subject: CSV variable seems to reset Message-ID: <192bf81f-46cb-4a47-bbae-384a2d17a2be@y38g2000hsy.googlegroups.com> Hi, I'm using the CSV module to parse a file using whitelistCSV_file = open("\\pathtoCSV\\whitelist.csv",'rb') whitelistCSV = csv.reader(whitelistCSV_file) for uname, dname, nname in whitelistCSV: print uname, dname, nname The first time I run the for loop the contents of the file is displayed. Subsequent attempts to run the for loop I don't get any data back and no exception. The only way I can get the data is to run whitelistCSV_file = open("\ \pathtoCSV\\whitelist.csv",'rb') again. I'm stumped as to how I can get around this or work out what the problem is, I'm assuming that the 'open' command buffers the data somewhere and that data is being wiped out by the CSV module but surely this shouldn't happen. thanks, Marc. From grante at visi.com Sat Jun 28 20:53:24 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 28 Jun 2008 19:53:24 -0500 Subject: pxssh submit su commands = very very slow References: <39f89067-8ee6-470a-92ce-77b46a344f37@34g2000hsf.googlegroups.com> Message-ID: On 2008-06-28, Neil Hodgson wrote: > gert: >> This works but after the su command you have to wait like 2 minutes >> before each command gets executed ? >> s.sendline ('su') >> s.expect('Password:') > > A common idiom seems to be to omit the start of the > expected reply since it may not be grabbed quickly enough. > Then the prompt has to time out. Try s.expect('assword:') I don't see why the first letter of the password prompt would be dropped. Tty drivers have buffered data for as long as I've been using Unix (25+ years). After writing the username you can wait for an hour before calling read(), and you'll still see the entire password prompt. I always assumed it was done that way so the script would work for either "password:" or "Password:". -- Grant Edwards grante Yow! Edwin Meese made me at wear CORDOVANS!! visi.com From Lie.1296 at gmail.com Sun Jun 29 05:47:36 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 29 Jun 2008 02:47:36 -0700 (PDT) Subject: help debugging noob code - converting binary data to images... References: <56955a42-155c-4c37-9bf6-5a99cadb5c79@l42g2000hsc.googlegroups.com> Message-ID: On Jun 29, 11:18?am, la... at portcommodore.com wrote: > Ok I'm a Python noob, been doing OK so far, working on a data > conversion program and want to create some character image files from > an 8-bit ROM file. > > Creating the image I've got down, I open the file and use TK to draw > the images... but > > 1) ?It does not seem to end (running in IDLE), I have to kill the > process to retry it seems tkinter does not close(?) > > 2) Once I added the Image module open won't open my binary file > (complains its not an image file, which is isnt.) ?I am sure I need to > prefix open with something but I can't seem to find an example of how > to word it, > > Below is the code (if it is lousy its because I've mainly been > borrowing by examples as I go...) Any suggestions are gretly > appreciated. > > #!/usr/local/bin/python > > from Tkinter import * > from string import * > from Image import * DON'T DO THAT... You're importing everything to the current namespace and this corrupts the current namespace, specifically the 'open' function inside Image.open would shadow the built-in 'open' function. use: import Tkinter import string import Image There are use cases where doing 'from blah import *' is useful, such as importing constants, but in general try to avoid importing everything to current namespace. > root = Tk() > root.title('Canvas') If you used 'import Tkinter', you'd have to change that code to: root = Tkinter.Tk() > #open commodore Cset rom > cset ?= open("chargen","r") Because you shadowed the built-in 'open' with the 'from Image import *', this would call Image.open instead of the built-in open. > canvas = Canvas(width=16, height=16, bg='white') If you used 'import Tkinter', you'd have to change that code to: canvas = Tkinter.Canvas(...) > canvas.pack(expand=YES, fill=BOTH) > > # character size factor > size = 2 > > # read all 512 characters from ROM > for cchar in range(0, 511, 1): You can use this instead: for cchar in range(511): but beware, this creates range with length 511 (so do the original range), which means you're lacking on space for the last char. You probably wanted this instead: for cchar in range(512): But again, python can loop directly over string/list/file, etc, so this might be best: for char in cset.read(): > ? ? #draw line > ? ? while charline < 8: > ? ? ? ? position = 0 > ? ? ? ? x = cset.read(1) > ? ? ? ? ch = ord(x) > ? ? ? ? # draw pixels > ? ? ? ? while position < 8: > ? ? ? ? ? ? if ch & ( 2 ** position ): > ? ? ? ? ? ? ? ? xp = 1+(7-position)*size > ? ? ? ? ? ? ? ? yp = 1+charline*size > ? ? ? ? ? ? ? ? canvas.create_rectangle(xp,yp,xp+size,yp+size, > fill='black', width=0) > ? ? ? ? ? ? position += 1 Since you're planning to use Image module (from PIL/Python Imaging Library) why not use functions from Image instead to create the image. The format of the file you're using seems to be RAW format (i.e. simple uncompressed bitmap, without any kinds of header). That means Image.fromstring() should work. > ? ? ? ? charline += 1 > ? ? #save character image > ? ? outfile = "/home/mydir/work/char"+zfill(cchar,3)+".png" > ? ? canvas.save(outfile,"png") > ? ? #clear canvas for next char... > ? ? canvas.create_rectangle(1,1,size*8,size*8, fill='white', width=0) > root.mainloop() From sturlamolden at yahoo.no Sat Jun 14 11:05:38 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 14 Jun 2008 08:05:38 -0700 (PDT) Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> Message-ID: <0213909a-7888-4474-bd88-fc5f148f0abe@y38g2000hsy.googlegroups.com> On Jun 12, 3:48 pm, Mark wrote: > Is this possible? def foobar(user,score): sums = {} for u,s in zip(user,score): try: sums[u] += s except KeyError: sums[u] = s return [(u, sums[u]) for u in sums].sort() usersum = foobar(user,score) for u,s in usersum: print "%d %d" % (u,s) From workitharder at gmail.com Sat Jun 14 13:26:54 2008 From: workitharder at gmail.com (bukzor) Date: Sat, 14 Jun 2008 10:26:54 -0700 (PDT) Subject: Python + RDBM framework? Message-ID: It seems that whenever I have an application that uses a database (MySQL) I end up writing a database framework from scratch. Is there some accepted pre-existing project that has done this? I see Django, but that seems to have a lot of web-framework that I don't (necessarily) need. I just want to have my objects go in and out of the database in a consistent manner without writing a ton of code. Can you just use the database part without making a full-blow web app? I see Zope, but that doesn't use MySQL (as far as I can tell), which I've invested a lot of time learning to use and optimize. Also, my manager wants to be able to log into a MySQL prompt and be able to look at the data. --Buck From george.sakkis at gmail.com Wed Jun 11 08:00:13 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 11 Jun 2008 05:00:13 -0700 (PDT) Subject: Producer-consumer threading problem References: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> <9482cbb7-297e-4429-b7a1-6d7c1dcc9070@t12g2000prg.googlegroups.com> Message-ID: <3d0a1204-526b-4447-a2cf-7f40860bb299@d1g2000hsg.googlegroups.com> On Jun 11, 1:59?am, Rhamphoryncus wrote: > Why not use a normal Queue, put a dummy value (such as None) in when > you're producer has finished, and have the main thread use the normal > Thread.join() method on all your child threads? I just gave two reasons: - Concurrency / interactivity. The main thread shouldn't wait for all one million items to be produced to get to see even one of them. - Limiting resources. Just like iterating over the lines of a file is more memory efficient than reading the whole file in memory, getting each consumed item as it becomes available is more memory efficient than waiting for all of them to finish. George From rhamph at gmail.com Wed Jun 11 01:40:33 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Tue, 10 Jun 2008 22:40:33 -0700 (PDT) Subject: Confusion with weakref, __del__ and threading References: Message-ID: On Jun 10, 8:15 pm, George Sakkis wrote: > I'm baffled with a situation that involves: > 1) an instance of some class that defines __del__, > 2) a thread which is created, started and referenced by that instance, > and > 3) a weakref proxy to the instance that is passed to the thread > instead of 'self', to prevent a cyclic reference. > > This probably sounds like gibberish so here's a simplified example: > > ========================================== > > import time > import weakref > import threading > > num_main = num_other = 0 > main_thread = threading.currentThread() > > class Mystery(object): > > def __init__(self): > proxy = weakref.proxy(self) > self._thread = threading.Thread(target=target, args=(proxy,)) > self._thread.start() > > def __del__(self): > global num_main, num_other > if threading.currentThread() is main_thread: > num_main += 1 > else: > num_other += 1 > > def sleep(self, t): > time.sleep(t) > > def target(proxy): > try: proxy.sleep(0.01) > except weakref.ReferenceError: pass > > if __name__ == '__main__': > for i in xrange(1000): > Mystery() > time.sleep(0.1) > print '%d __del__ from main thread' % num_main > print '%d __del__ from other threads' % num_other > > ========================================== > > When I run it, I get around 950 __del__ from the main thread and the > rest from non-main threads. I discovered this accidentally when I > noticed some ignored AssertionErrors caused by a __del__ that was > doing "self._thread.join()", assuming that the current thread is not > self._thread, but as it turns out that's not always the case. > > So what is happening here for these ~50 minority cases ? Is __del__ > invoked through the proxy ? The trick here is that calling proxy.sleep(0.01) first gets a strong reference to the Mystery instance, then holds that strong reference until it returns. If the child thread gets the GIL before __init__ returns it will enter Mystery.sleep, then the main thread will return from Mystery.__init__ and release its strong reference, followed by the child thread returning from Mystery.sleep, releasing its strong reference, and (as it just released the last strong reference) calling Mystery.__del__. If the main thread returns from __init__ before the child thread gets the GIL, it will release the only strong reference to the Mystery instance, causing it to clear the weakref proxy and call __del__ before the child thread ever gets a chance. If you added counters to the target function you should see them match the counters of the __del__ function. Incidentally, += 1 isn't atomic in Python. It is possible for updates to be missed. From straton at lampsacos.demon.co.uk Thu Jun 5 04:42:06 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Thu, 05 Jun 2008 09:42:06 +0100 Subject: Interesting Math Problem In-Reply-To: References: Message-ID: BEES INC wrote: > I've been awfully busy programming lately. My Django-based side > project is coming along well and I hope to have it ready for use in a > few weeks. Please don't ask more about it, that's really all I can say > for now. Anyways, I came across an interesting little math problem > today and was hoping some skilled programmers out there could come up > with a more elegant solution than mine. > Problem: Star Ratings > > People can rate cheeseburgers on my website with a star rating of 0-5 > stars (whole stars only), 5 being mighty tasty and 0 being disgusting. > I would like to show the average of everyone's ratings of a particular > cheeseburger to the nearest half star. I have already calculated the > average rating as a float (star_sum) and the total number of people > that rated the particular cheeseburger (num_raters). The result should > be stored as a float in a variable named "stars." > My Solution (in Python): > > # round to one decimal place and > # separate into whole and fractional parts > parts = str(round(star_sum/num_raters, 1)).split('.') > whole = int(parts[0]) > frac = int(parts[1]) > if frac < 3: > ___frac = 0 > elif frac > 7: > ___frac = 0 > ___whole += 1 > else: > ___frac = 5 > # recombine for a star rating rounded to the half > stars = float(str(whole)+'.'+str(frac)) > > Mmmm? In-N-Out Burgers? Please reply if you've got a better solution. for raw in [0.05 * n for n in range (41)]: rounded = round(2.0*raw)/2.0 print "%0.2f --> %0.2f" % (raw,rounded) From noagbodjivictor at gmail.com Sat Jun 28 11:39:32 2008 From: noagbodjivictor at gmail.com (Victor Noagbodji) Date: Sat, 28 Jun 2008 11:39:32 -0400 Subject: C++ or Python Message-ID: Kurda Yon wrote: > I would like to know what are advantages of Python in comparison with C > ++? In which cases and why Python can be a better tool than C++? I have used both in small projects and I think Python wins by far. First of all, you don't have the hassle of compiling each time you make a change to your code. This compiling step can be a nightmare when developing a web application (CGI, but you will see only few C++ frameworks for web development anyway) or a GUI. Second: Python is easy to read and write. This is very important when working in a team. Python doesn't give you much choice on the code layout, and that's a good thing. And it also increases the speed of your coding. I strongly suggest you learn Python, then C (not C++) in order to extend Python when you feel like something is slow. -- NOAGBODJI Paul Victor From Lie.1296 at gmail.com Mon Jun 16 14:22:50 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 16 Jun 2008 11:22:50 -0700 (PDT) Subject: sqlite3 and Python 2.5.1 References: <612ed26a-c6cf-4133-af6c-f256484e3928@x41g2000hsb.googlegroups.com> Message-ID: On Jun 17, 12:59?am, milan_sanremo wrote: > I have sqlite installed, but when I try to import sqlite3 I receive: > > Python 2.5.1 (r251:54863, Nov ?3 2007, 02:54:36) [C] on sunos5 > Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 > > Traceback (most recent call last): > ? File "", line 1, in > ImportError: No module named sqlite3 > > > > Yet: > > # find /usr/local/python -name "sqlite*" -print > /usr/local/python/lib/python2.5/sqlite3 > > # /opt/csw/bin/sqlite3 > SQLite version 3.2.2 > Enter ".help" for instructions > sqlite> > > What is missing? Did you, by chance, happened to compile your Python yourself? From what I see here: http://www.megasolutions.net/python/python-unix-install,-sqlite3-78710.aspx Python's source doesn't include the sqlite3 source, it only contains pysqlite interface, so when compiling python you need to get sqlite3 too. From tjreedy at udel.edu Sat Jun 21 18:34:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 21 Jun 2008 18:34:34 -0400 Subject: Way to unblock sys.stdin.readline() call In-Reply-To: <56b21108-45b4-4b9e-bda5-171c9ddc21ce@i76g2000hsf.googlegroups.com> References: <56b21108-45b4-4b9e-bda5-171c9ddc21ce@i76g2000hsf.googlegroups.com> Message-ID: joamag wrote: > Is there any possible way to unblock the sys.stdin.readline() call > from a different thread. If you want the thread to do something 'else' when no input is available, would this work? Put readline in a thread that puts lines in a q=queue.Quese(). Then try: l=q.ge_nowait except queue.Empty From ed at leafe.com Tue Jun 24 14:58:02 2008 From: ed at leafe.com (Ed Leafe) Date: Tue, 24 Jun 2008 13:58:02 -0500 Subject: Using Python and MS-SQL Server In-Reply-To: <734a9927-a18b-4af6-a717-eaf2631b4836@c58g2000hsc.googlegroups.com> References: <734a9927-a18b-4af6-a717-eaf2631b4836@c58g2000hsc.googlegroups.com> Message-ID: On Jun 23, 2008, at 11:10 AM, hwcowan at hotmail.com wrote: > The current script that I am working on requires pulling in some > information from a Microsoft SQL Server. > > I was wondering if anyone could suggest the best way of doing this? I > have looked at the different modules that are specific to SQL server, > but none of them seem to be active or up to date. Dabo may be what you need. It is a 3-tier framework for developing desktop applications, so even if you are doing web apps, the data access layer is fully usable by itself. We support MS SQL Server, as well as several other database backends. -- Ed Leafe -- http://dabodev.com From bruno.42.desthuilliers at websiteburo.invalid Fri Jun 6 11:32:37 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 06 Jun 2008 17:32:37 +0200 Subject: Newb question: underscore In-Reply-To: <601115a1-c788-4be7-b6b4-92cf159559bd@f36g2000hsa.googlegroups.com> References: <873anrl8p5.fsf@benfinney.id.au> <87y75jjeqo.fsf@benfinney.id.au> <601115a1-c788-4be7-b6b4-92cf159559bd@f36g2000hsa.googlegroups.com> Message-ID: <48495857$0$26543$426a74cc@news.free.fr> cokofreedom at gmail.com a ?crit : >>> My question is: Why would anyone decide to obfuscate something as easy >>> to read as Python??? >> They didn't decide to obfuscate; they decided to follow a >> strongly-expected convention for the name of that function by existing >> users of the 'gettext' functionality, in contexts that predate the >> appearance of that functionality in Python. >> > > Well _ can also mean the previous output statement that wasn't null, In the shell only IIRC. From jimmy at retzlaff.com Sun Jun 15 14:42:51 2008 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Sun, 15 Jun 2008 11:42:51 -0700 Subject: py2exe 0.6.8 released Message-ID: py2exe 0.6.8 released ===================== py2exe is a Python distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation. Console and Windows (GUI) applications, Windows NT services, exe and dll COM servers are supported. Changes in 0.6.8: * Support for relative imports. * Fix MemoryLoadLibrary to handle loading function addresses by ordinal numbers. Patch and test by Matthias Miller. * Using the options compressed=1, bundle_files=3, and zipfile=None at the same time now works; patch from Alexey Borzenkov. * Allow renaming of single-executable files; patch from Alexey Borzenkov. * Embedding icon resources into the image now works correctly even for ico files containing multiple images. * pyd files from different packages with the same filename no longer conflict. Patch from Grant Edwards. * There are new samples for the 'typelibs' support, including the new option of pre-generating a typelib and specifying the file as an input to py2exe. * The test suite is now included in the source distribution. Changes in 0.6.6: * Better support for Python 2.5. * Experimental support for 64-bit builds of Python on win64. * Better ISAPI support. * New samples for ISAPI and COM servers. * Support for new "command-line styles" when building Windows services. Changes in 0.6.5: * Fixed modulefinder / mf related bugs introduced in 0.6.4. This will be most evident when working with things like win32com.shell and xml.xpath. * Files no longer keep read-only attributes when they are copied as this was causing problems with the copying of some MS DLLs. Changes in 0.6.4: * New skip-archive option which copies the Python bytecode files directly into the dist directory and subdirectories - no archive is used. * An experimental new custom-boot-script option which allows a boot script to be specified (e.g., --custom-boot-script=cbs.py) which can do things like installing a customized stdout blackhole. See py2exe's boot_common.py for examples of what can be done. The custom boot script is executed during startup of the executable immediately after boot_common.py is executed. * Thomas Heller's performance improvements for finding needed modules. * Mark Hammond's fix for thread-state errors when a py2exe created executable tries to use a py2exe created COM DLL. Changes in 0.6.3: * First release assembled by py2exe's new maintainer, Jimmy Retzlaff. Code changes in this release are from Thomas Heller and Gordon Scott. * The dll-excludes option is now available on the command line. It was only possible to specify that in the options argument to the setup function before. The dll-excludes option can now be used to filter out dlls like msvcr71.dll or even w9xpopen.exe. * Fix from Gordon Scott: py2exe crashed copying extension modules in packages. Changes in 0.6.2: * Several important bugfixes: - bundled extensions in packages did not work correctly, this made the wxPython single-file sample fail with newer wxPython versions. - occasionally dlls/pyds were loaded twice, with very strange effects. - the source distribution was not complete. - it is now possible to build a debug version of py2exe. Changes in 0.6.1: * py2exe can now bundle binary extensions and dlls into the library-archive or the executable itself. This allows to finally build real single-file executables. The bundled dlls and pyds are loaded at runtime by some special code that emulates the Windows LoadLibrary function - they are never unpacked to the file system. This part of the code is distributed under the MPL 1.1, so this license is now pulled in by py2exe. * By default py2exe now includes the codecs module and the encodings package. * Several other fixes. Homepage: Download from the usual location: Enjoy, Jimmy From mdw at distorted.org.uk Sun Jun 8 08:52:10 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Sun, 8 Jun 2008 12:52:10 +0000 (UTC) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> Message-ID: Fuzzyman wrote: > So, you are stating that no API programmer using Python *ever* has a > valid or genuine reason for wanting (even if he can't have it) genuine > 'hiding' of internal state or members from consumers of his (or > her...) API? I don't want to speak for whoever you were responding to, but from my point of view... Yes. I understand the difference between the documented interface of a system and the details of its implementation. But sometimes it can be useful to take advantage of implementation details, particularly if the published interface is inadequate in some way. Whether or not I choose to make use of implementation details is a trade-off between immediate convenience and maintainability, but that's something I can make a rational decision about. By enforcing your `data hiding', you're effectively telling me that I'm too stupid to make rational decisions of this sort. And that's actually extremely insulting. -- [mdw] From usfreeads69 at gmail.com Sat Jun 14 06:43:32 2008 From: usfreeads69 at gmail.com (USFREEADS) Date: Sat, 14 Jun 2008 03:43:32 -0700 (PDT) Subject: Get Google Ads Free! Message-ID: <9b33e6b6-f403-46a9-a694-3f450b12a470@h1g2000prh.googlegroups.com> Internet Multimillionaire is deliberately out to show up Google, Yahoo, MSN and every other big search engine by giving away this monster of a secret! (But he doesn?t even care!)... "Internet Marketer Gets $87 Million in Google Pay-Per-Click Ads FREE! ... And Makes Over $314 Million as a Result! ... And Now He's Going to Give You This Same Secret for Next to Nothing!? ?Everyday Google sells several $10 million?s in pay-per-clicks. But I get all mine absolutely FREE ? and now I am going to show you how to get yours FREE also!? That?s right ? Start Sharing in the *Incredible* Secret So Few Others Know About that Allow Them to Actually Get All Their Pay-Per-Click Advertising Absolutely FREE! Fast facts about this amazing NEW SECRET!... This is an incredible system developed by none other than Dr Jon Cohen, MD (retired) who found a little-known ?twist? in how to use the pay-per-click (PPC) and paid-for targeted advertising programs at Google? and the other search engines. Dr Jon has personally used this to: Eliminate over $87 million in otherwise paid-for and PPC ads at Google? and other search engines over the course of about 9 years now! Generate over $314 million in product sales as a result of this incredible savings! Acquire a personal wealth of more than $68 million! (Net) Start and develop 16 online ventures of his own. Has coached ?live? where he taught others this same amazing formula - including 198 executives from major Fortune 500 and FortuneSM 1000 companies, 14 representatives of publicly-traded companies on the New York Stock ExchangeSM (NYSE), 82 more on the NASDAQ?, 5 members of investment houses on the American Stock ExchangeSM (AMEX), as well as at least one former US Congressman (now retired also) who now stays at home and runs a home-based online family business, among countless others. Please click here for further details:- http://tubeurl.com/7l7u0b From ptmcg at austin.rr.com Mon Jun 30 03:10:38 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 30 Jun 2008 00:10:38 -0700 (PDT) Subject: best option for python lex/yacc? References: Message-ID: On Jun 30, 1:47?am, m... at pixar.com wrote: > I'm porting a C lex/yacc based project, and would like to redo > it in python. > > What's the best option for a python lex/yacc-like? ?I've > googled a few things, but wanted to see the current concensus. > > Many TIA! > Mark > > -- > Mark Harrison > Pixar Animation Studios For a full list, see http://nedbatchelder.com/text/python-parsers.html For lex/yacc-like's, PLY, Spark, simpleparse, or ANTLR are probably the leaders. If you consider using pyparsing, then *don't* just try to do a straight transliteration from your existing lex/yacc implementation - you will end up fighting some of pyparsing's basic concepts. But if you already have this implemented and working in C, and given that parsing usually is such a performance-sucking operation, why not package the existing parser into a lib, and call it from python using ctypes, or some similar technology for embedding C code in Python? -- Paul From nick at craig-wood.com Wed Jun 11 22:01:49 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 11 Jun 2008 21:01:49 -0500 Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: Frank Millman wrote: > Thanks to all for the various replies. They have all helped me to > refine my ideas on the subject. These are my latest thoughts. > > Firstly, the Decimal type exists, it clearly works well, it is written > by people much cleverer than me, so I would need a good reason not to > use it. Speed could be a good reason, provided I am sure that any > alternative is 100% accurate for my purposes. > > My approach is based on expressing a decimal number as a combination > of an integer and a scale, where scale means the number of digits to > the right of the decimal point. > > Therefore 0.04 is integer 4 with scale 2, 1.1 is integer 11 with scale > 1, -123.456 is integer -123456 with scale 3. I am pretty sure that any > decimal number can be accurately represented in this form. > > All arithmetic is carried out using integer arithmetic, so although > there may be rounding differences, there will not be the spurious > differences thrown up by trying to use floats for decimal > arithmetic. I used an identical scheme in a product some time ago (written in C not python). It was useful because it modelled the problem domain exactly. You might want to investigate the rational class in gmpy which might satisfy your requirement for exact arithmetic :- >>> import gmpy >>> gmpy.mpq(123,1000) mpq(123,1000) >>> a = gmpy.mpq(123,1000) >>> b = gmpy.mpq(12,100) >>> a+b mpq(243,1000) >>> a*b mpq(369,25000) >>> a/b mpq(41,40) >>> It is also *very* fast being written in C. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bignose+hates-spam at benfinney.id.au Sun Jun 15 18:35:02 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 16 Jun 2008 08:35:02 +1000 Subject: Making wxPython a standard module? References: <48512f69$0$11262$c3e8da3@news.astraweb.com> <0bb2d727-4bd8-4baf-be34-716daec1ddff@d1g2000hsg.googlegroups.com> <87y756ahn2.fsf@benfinney.id.au> <0e2b604c-769b-4191-87ea-948566412094@34g2000hsh.googlegroups.com> Message-ID: <87skve9vjd.fsf@benfinney.id.au> s0suk3 at gmail.com writes: > On Jun 15, 9:37 am, Ben Finney > wrote: > > The Zen of Python, by Tim Peters > > ? > > There should be one-- and preferably only one --obvious way to do it. > > I agree with that concept. But there already is more than one way to > do it, only that the other ways are being made less accessible (by > not being on the standard library), don't you think? With the result that there is only one *obvious* way to do it. That's a property worth some effort to preserve. For some reason, people always overlook that qualification when reading that part of the Zen. -- \ ?A hundred times every day I remind myself that [...] I must | `\ exert myself in order to give in the same measure as I have | _o__) received and am still receiving? ?Albert Einstein | Ben Finney From alexnbryan at gmail.com Sun Jun 29 14:52:25 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sun, 29 Jun 2008 11:52:25 -0700 (PDT) Subject: using urllib2 In-Reply-To: <27fbd1c7-6735-4fb0-9758-726b2fd8b86e@m3g2000hsc.googlegroups.com> References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> <25d97d35-6d28-43ef-9e54-d8ae7a03bc8f@b1g2000hsg.googlegroups.com> <27fbd1c7-6735-4fb0-9758-726b2fd8b86e@m3g2000hsc.googlegroups.com> Message-ID: <18184087.post@talk.nabble.com> Okay, so i've hit a new snag and can't seem to figure out what is wrong. What is happening is the first 4 definitions of the word "simple" don't show up. The html is basicly the same, with the exception of noun turning into adj. Ill paste the html of the word cheese, and then the one for simple, and the code I am using to do the work. line of html for the 2nd def of cheese:
    1.the curd of milk separated from the whey and >>> prepared >>> >> in >>> >> >> many ways as a food.
    2.a definite mass of this substance, often in the shape of a wheel or cylinder.
    line of html for the 2nd def of simple:
    2.not elaborate or artificial; plain: a simple style.
    code: import urllib from BeautifulSoup import BeautifulSoup def get_defs(term): soup = BeautifulSoup(urllib.urlopen('http://dictionary.reference.com/search?q=%s' % term)) for tabs in soup.findAll('table', {'class': 'luna-Ent'}): yield tabs.findAll('td')[-1].contents[-1].string word = raw_input("What word would you like to define: ") mainList = list(get_defs(word)) n=0 q = 1 for x in mainList: print str(q)+". "+str(mainList[n]) q=q+1 n=n+1 Now, I don't think it is the italics because one of the definitions that worked had them in it in the same format. Any Ideas??! Jeff McNeil-2 wrote: > > On Jun 29, 12:50?pm, Alexnb wrote: >> No I figured it out. I guess I never knew that you aren't supposed to >> split a >> url like "http://www.goo\ >> gle.com" But I did and it gave me all those errors. Anyway, I had a >> question. On the original code you had this for loop: >> >> for tabs in soup.findAll('table', {'class': 'luna-Ent'}): >> ? ? ? ? yield tabs.findAll('td')[-1].contents[-1].string >> >> I hate to be a pain, but I was looking at the BeautifulSoup docs, and >> found >> the findAll thing. But I want to know why you put "for tabs," also why >> you >> need the "'table', {'class': 'luna-Ent'}):" Like why the curly braces and >> whatnot? >> >> Jeff McNeil-2 wrote: >> >> > On Jun 27, 10:26?pm, Alexnb wrote: >> >> Okay, so I copied your code(and just so you know I am on a mac right >> now >> >> and >> >> i am using pydev in eclipse), and I got these errors, any idea what is >> >> up? >> >> >> Traceback (most recent call last): >> >> ? File >> >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", >> >> line 14, in >> >> ? ? print list(get_defs("cheese")) >> >> ? File >> >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", >> >> line 9, in get_defs >> >> ? ? dictionary.reference.com/search?q=%s' % term)) >> >> ? File >> >> >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >> lib.py", >> >> line 82, in urlopen >> >> ? ? return opener.open(url) >> >> ? File >> >> >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >> lib.py", >> >> line 190, in open >> >> ? ? return getattr(self, name)(url) >> >> ? File >> >> >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >> lib.py", >> >> line 325, in open_http >> >> ? ? h.endheaders() >> >> ? File >> >> >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >> plib.py", >> >> line 856, in endheaders >> >> ? ? self._send_output() >> >> ? File >> >> >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >> plib.py", >> >> line 728, in _send_output >> >> ? ? self.send(msg) >> >> ? File >> >> >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >> plib.py", >> >> line 695, in send >> >> ? ? self.connect() >> >> ? File >> >> >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >> plib.py", >> >> line 663, in connect >> >> ? ? socket.SOCK_STREAM): >> >> IOError: [Errno socket error] (8, 'nodename nor servname provided, or >> not >> >> known') >> >> >> Sorry if it is hard to read. >> >> >> Jeff McNeil-2 wrote: >> >> >> > Well, what about pulling that data out using Beautiful soup? If you >> >> > know the table name and whatnot, try something like this: >> >> >> > #!/usr/bin/python >> >> >> > import urllib >> >> > from BeautifulSoup import BeautifulSoup >> >> >> > def get_defs(term): >> >> > ? ? soup = BeautifulSoup(urllib.urlopen('http:// >> >> > dictionary.reference.com/search?q=%s' % term)) >> >> >> > ? ? for tabs in soup.findAll('table', {'class': 'luna-Ent'}): >> >> > ? ? ? ? yield tabs.findAll('td')[-1].contents[-1].string >> >> >> > print list(get_defs("frog")) >> >> >> > jeff at martian:~$ python test.py >> >> > [u'any tailless, stout-bodied amphibian of the order Anura, >> including >> >> > the smooth, moist-skinned frog species that live in a damp or >> >> > semiaquatic habitat and the warty, drier-skinned toad species that >> are >> >> > mostly terrestrial as adults. ', u' ', u' ', u'a French person or a >> >> > person of French descent. ', u'a small holder made of heavy >> material, >> >> > placed in a bowl or vase to hold flower stems in position. ', u'a >> >> > recessed panel on one of the larger faces of a brick or the like. ', >> >> > u' ', u'to hunt and catch frogs. ', u'French or Frenchlike. ', u'an >> >> > ornamental fastening for the front of a coat, consisting of a button >> >> > and a loop through which it passes. ', u'a sheath suspended from a >> >> > belt and supporting a scabbard. ', u'a device at the intersection of >> >> > two tracks to permit the wheels and flanges on one track to cross or >> >> > branch from the other. ', u'a triangular mass of elastic, horny >> >> > substance in the middle of the sole of the foot of a horse or >> related >> >> > animal. '] >> >> >> > HTH, >> >> >> > Jeff >> >> >> > On Jun 27, 7:28?pm, Alexnb wrote: >> >> >> I have read that multiple times. It is hard to understand but it >> did >> >> help >> >> >> a >> >> >> little. But I found a bit of a work-around for now which is not >> what I >> >> >> ultimately want. However, even when I can get to the page I want >> lets >> >> >> say, >> >> >> "Http://dictionary.reference.com/browse/cheese", I look on firebug, >> >> and >> >> >> extension and see the definition in javascript, >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> Jeff McNeil-2 wrote: >> >> >> >> > the problem being that if I use code like this to get the html of >> >> that >> >> >> >> > page in python: >> >> >> >> > response = urllib2.urlopen("the webiste....") >> >> >> > html = response.read() >> >> >> > print html >> >> >> >> > then, I get a bunch of stuff, but it doesn't show me the code >> with >> >> the >> >> >> > table that the definition is in. So I am asking how do I access >> this >> >> >> > javascript. Also, if someone could point me to a better reference >> >> than >> >> >> the >> >> >> > last one, because that really doesn't tell me much, whether it be >> a >> >> >> book >> >> >> > or anything. >> >> >> >> > I stumbled across this a while back: >> >> >> >http://www.voidspace.org.uk/python/articles/urllib2.shtml. >> >> >> > It covers quite a bit. The urllib2 module is pretty >> straightforward >> >> >> > once you've used it a few times. ?Some of the class naming and >> >> whatnot >> >> >> > takes a bit of getting used to (I found that to be the most >> >> confusing >> >> >> > bit). >> >> >> >> > On Jun 27, 1:41 pm, Alexnb wrote: >> >> >> >> Okay, I tried to follow that, and it is kinda hard. But since >> you >> >> >> >> obviously >> >> >> >> know what you are doing, where did you learn this? Or where can >> I >> >> >> learn >> >> >> >> this? >> >> >> >> >> Maric Michaud wrote: >> >> >> >> >> > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit : >> >> >> >> >> I have never used the urllib or the urllib2. I really have >> >> looked >> >> >> >> online >> >> >> >> >> for help on this issue, and mailing lists, but I can't figure >> >> out >> >> >> my >> >> >> >> >> problem because people haven't been helping me, which is why >> I >> >> am >> >> >> >> here! >> >> >> >> >> :]. >> >> >> >> >> Okay, so basically I want to be able to submit a word to >> >> >> >> dictionary.com >> >> >> >> >> and >> >> >> >> >> then get the definitions. However, to start off learning >> >> urllib2, I >> >> >> >> just >> >> >> >> >> want to do a simple google search. Before you get mad, what I >> >> have >> >> >> >> found >> >> >> >> >> on >> >> >> >> >> urllib2 hasn't helped me. Anyway, How would you go about >> doing >> >> >> this. >> >> >> >> No, >> >> >> >> >> I >> >> >> >> >> did not post the html, but I mean if you want, right click on >> >> your >> >> >> >> >> browser >> >> >> >> >> and hit view source of the google homepage. Basically what I >> >> want >> >> >> to >> >> >> >> know >> >> >> >> >> is how to submit the values(the search term) and then search >> for >> >> >> that >> >> >> >> >> value. Heres what I know: >> >> >> >> >> >> import urllib2 >> >> >> >> >> response = urllib2.urlopen("http://www.google.com/") >> >> >> >> >> html = response.read() >> >> >> >> >> print html >> >> >> >> >> >> Now I know that all this does is print the source, but thats >> >> about >> >> >> all >> >> >> >> I >> >> >> >> >> know. I know it may be a lot to ask to have someone show/help >> >> me, >> >> >> but >> >> >> >> I >> >> >> >> >> really would appreciate it. >> >> >> >> >> > This example is for google, of course using pygoogle is easier >> in >> >> >> this >> >> >> >> > case, >> >> >> >> > but this is a valid example for the general case : >> >> >> >> >> >>>>[207]: import urllib, urllib2 >> >> >> >> >> > You need to trick the server with an imaginary User-Agent. >> >> >> >> >> >>>>[208]: def google_search(terms) : >> >> >> >> > ? ? return >> >> >> >> urllib2.urlopen(urllib2.Request("http://www.google.com/search?" >> >> >> >> > + >> >> >> >> > urllib.urlencode({'hl':'fr', 'q':terms}), >> >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? >> >> >> ?headers={'User-Agent':'MyNav >> >> >> >> > 1.0 >> >> >> >> > (compatible; MSIE 6.0; Linux'}) >> >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ).read() >> >> >> >> > ? ?.....: >> >> >> >> >> >>>>[212]: res = google_search("python & co") >> >> >> >> >> > Now you got the whole html response, you'll have to parse it >> to >> >> >> recover >> >> >> >> > datas, >> >> >> >> > a quick & dirty try on google response page : >> >> >> >> >> >>>>[213]: import re >> >> >> >> >> >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

    > >> >> >> class=r>.*?

    ', >> >> >> >> > res) ] >> >> >> >> > ...[229]: >> >> >> >> > ['Python Gallery', >> >> >> >> > ?'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des >> >> Monty >> >> >> >> ...', >> >> >> >> > ?'Re: os x, panther, python & co: msg#00041', >> >> >> >> > ?'Re: os x, panther, python & co: msg#00040', >> >> >> >> > ?'Cardiff Web Site Design, Professional web site design >> services >> >> >> ...', >> >> >> >> > ?'Python Properties', >> >> >> >> > ?'Frees < Programs < Python < Bin-Co', >> >> >> >> > ?'Torb: an interface between Tcl and CORBA', >> >> >> >> > ?'Royal Python Morphs', >> >> >> >> > ?'Python & Co'] >> >> >> >> >> > -- >> >> >> >> > _____________ >> >> >> >> >> > Maric Michaud >> >> >> >> > -- >> >> >> >> >http://mail.python.org/mailman/listinfo/python-list >> >> >> >> >> -- >> >> >> >> View this message in >> >> >> context:http://www.nabble.com/using-urllib2-tp18150669p18160312.html >> >> >> >> Sent from the Python - python-list mailing list archive at >> >> Nabble.com. >> >> >> >> > -- >> >> >> >http://mail.python.org/mailman/listinfo/python-list >> >> >> >> -- >> >> >> View this message in >> >> >> >> context:http://www.nabble.com/using-urllib2-tp18150669p18165634.html >> >> >> Sent from the Python - python-list mailing list archive at >> Nabble.com. >> >> >> > -- >> >> >http://mail.python.org/mailman/listinfo/python-list >> >> >> -- >> >> View this message in... >> >> read more ? > > The definitions were embedded in tables with a 'luna-Ent' class. I > pulled all of the tables with that class out, and then returned the > string value of td containing the actual definition. The findAll > method takes an optional dictionary, thus the {}. > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/using-urllib2-tp18150669p18184087.html Sent from the Python - python-list mailing list archive at Nabble.com. From n.emami at gmail.com Thu Jun 12 07:48:42 2008 From: n.emami at gmail.com (Nader) Date: Thu, 12 Jun 2008 04:48:42 -0700 (PDT) Subject: get keys with the same values References: Message-ID: <7334507d-24e7-43f9-baa3-4e9e87eb20fa@w7g2000hsa.googlegroups.com> On Jun 12, 1:35 pm, bearophileH... at lycos.com wrote: > Nader: > > > d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} > > I will something as : > > d.keys(where their values are the same) > > That's magic. > > > With this statement I can get two lists for this example: > > l1= ['a','e'] > > l2=['b','d'] > > Would somebody tell me how I can do it? > > You can create a new dict where the keys are the values of the input > dict and the values are a list of the keys of the original dict. So > scanning the keys, values of the input dict, you can fill the second > dict. Then you can scan the second dict, and create a list that > contains only value lists longer than one. > > Bye, > bearophile Is it niet possible with one or two statement, maybe with list comprehension. For exmple: l = [(k,v) for k in d.keys() for v in d.values() | en here we need some extra logic (v = 1)] I don;t konw how we can define a logic statement in a list comprehension. It will be very compact, if it would possible. Nader From ppearson at nowhere.invalid Sat Jun 28 13:36:30 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: Sat, 28 Jun 2008 12:36:30 -0500 Subject: Do I need "self" and "other"? References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> Message-ID: On Fri, 27 Jun 2008 20:19:00 -0400, Nick Dumas wrote: [snip] > > Example: > > class Foo(): > self.x = 5 Have you tried what you're posting? Python 2.4.3 (#2, Oct 6 2006, 07:52:30) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo(): File "", line 1 class Foo(): ^ SyntaxError: invalid syntax >>> class Foo( object ): ... self.x = 5 ... Traceback (most recent call last): File "", line 1, in ? File "", line 2, in Foo NameError: name 'self' is not defined >>> -- To email me, substitute nowhere->spamcop, invalid->net. From apardon at forel.vub.ac.be Mon Jun 2 06:40:07 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 2 Jun 2008 10:40:07 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> Message-ID: On 2008-06-02, Carl Banks wrote: > On Jun 2, 5:38 am, Antoon Pardon wrote: >> If you really need it, you can do data hiding in python. It just >> requires a bit more work. >> >> ----------------------------- Hide.py --------------------------------- >> class Rec(object): >> def __init__(__, **kwargs): >> for key,value in kwargs.items(): >> setattr(__, key, value) >> >> def __getitem__(self, key): >> return getattr(self, key) >> >> def __setitem__ (self, key, val): >> setattr(self, key, val) >> >> class Foo(object): >> >> def __init__(self): >> >> hidden = Rec(x=0, y=0) >> >> def SetX(val): >> hidden.x = val >> >> def SetY(val): >> hidden.y = val >> >> def GetX(): >> return hidden.x >> >> def GetY(): >> return hidden.y >> >> self.SetX = SetX >> self.SetY = SetY >> self.GetX = GetX >> self.GetY = GetY > > Red Herring. > > 1. This doesn't hide the variables; it just changes their spelling. > 2. This also "hides" the variables from its own class. > > In other words, it's a useless no-op. > > In fact, I'd say this is even worse than useless. Creating accessor > functions is a sort of blessing for external use. Knowing that there > are accessor functions is likely to cause a user to show even less > restraint. I think you completed missed the point. This is just a proof of concept thing. In a real example there would of course no Set en Get methods but just methods that in the course of their execution would access or update the hidden attributes -- Antoon Pardon From barisc at bckm.org Sun Jun 8 18:38:23 2008 From: barisc at bckm.org (Baris-C) Date: Sun, 8 Jun 2008 15:38:23 -0700 (PDT) Subject: Python is slow References: Message-ID: <4aa0d411-071e-46dd-a568-4b5f148aab48@z72g2000hsb.googlegroups.com> On May 22, 7:14?pm, cm_gui wrote: > Python is slow. ? ?Almost all of the web applications written in > Python are slow. ? Zope/Plone is slow, sloow, so very slooow. ?Even > Google Apps is not faster. ? Neither is Youtube. > Facebook and Wikipedia (Mediawiki), written in PHP, are so much faster > than Python. > Okay, they probably use caching or some code compilation -- but Google > Apps and those Zope sites probably also use caching. > > I've yet to see a web application written in Python which is really > fast. I do not have much experience on python but, php is %25 more faster than python in a simple iteration. From martin at v.loewis.de Tue Jun 10 17:05:53 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 10 Jun 2008 23:05:53 +0200 Subject: Cannot install python under Win32 In-Reply-To: <0358337a-b147-4e38-b37f-a8119a39b6d7@j22g2000hsf.googlegroups.com> References: <82d86466-0b90-47aa-af40-f52b52eb2526@d77g2000hsb.googlegroups.com> <484e258f$0$13627$9b622d9e@news.freenet.de> <0358337a-b147-4e38-b37f-a8119a39b6d7@j22g2000hsf.googlegroups.com> Message-ID: <484EECB1.6020109@v.loewis.de> > DEBUG: Error 2356: Couldn't locate cabinet in stream: python. That sounds bad indeed. In the original file, that stream is definitely present, so most likely, you experienced a corruption in download. Please check the md5 sum of the MSI file; if it differs, download again (preferably using a different web browser). Another possible source is that the Windows installer (running as local system) does not have access to your Regards, Martin From http Wed Jun 4 01:01:51 2008 From: http (Paul Rubin) Date: 03 Jun 2008 22:01:51 -0700 Subject: Books for programmers References: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> <78ef063d-7219-4ffa-bf8f-88dc24dd90bc@r66g2000hsg.googlegroups.com> Message-ID: <7xzlq1sshs.fsf@ruckus.brouhaha.com> V writes: > I think that I'm interested in a more advance book, ideally one that > talk of the Python gotchas, traps, pitfall, idioms, performance, > stile, and so on. I may have missed it but I haven't seen Python in a Nutshell mentioned in this thread. From jgodoy at gmail.com Wed Jun 25 06:44:03 2008 From: jgodoy at gmail.com (Jorge Godoy) Date: Wed, 25 Jun 2008 07:44:03 -0300 Subject: IDE on the level of Eclipse or DEVc++? References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> <486214ae$0$9742$426a34cc@news.free.fr> <87ej6lq02c.fsf@benfinney.id.au> Message-ID: cokofreedom at gmail.com wrote: > How is emacs on a windows platform? Except for Windows using _emacs instead of .emacs, it was the same I had on Linux, last time I tried it... :-) There are packages for Windows that have a lot of things pre-packaged to make it feel more like a Windows application, including keyboard shortcuts. -- Jorge Godoy From bj_666 at gmx.net Thu Jun 5 07:19:19 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 5 Jun 2008 11:19:19 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> <873antn9il.fsf@benfinney.id.au> <6ammujF38poe2U2@mid.uni-berlin.de> <87y75llp5x.fsf@benfinney.id.au> <6an5a7F38poe2U3@mid.uni-berlin.de> <6aok3pF38pu6cU2@mid.uni-berlin.de> Message-ID: <6aq0dnF3892asU2@mid.uni-berlin.de> On Thu, 05 Jun 2008 08:21:41 +0000, Antoon Pardon wrote: > On 2008-06-04, Marc 'BlackJack' Rintsch wrote: >> On Wed, 04 Jun 2008 09:34:58 +0000, Antoon Pardon wrote: >> >>> On 2008-06-04, Marc 'BlackJack' Rintsch wrote: >>> >>>>>> it makes sense to me to also test if they work as documented. >>>>> >>>>> If they affect the behaviour of some public component, that's where >>>>> the documentation should be. >>>> >>>> As I said they are public themselves for someone. >>> >>> Isn't that contradictory: "Public for someone" I always >>> thought "public" meant accessible to virtually anyone. >>> Not to only someone. >> >> For the programmer who writes or uses the private API it isn't really >> "private", he must document it or know how it works. > > How does that make it not private. Private has never meant "accessible > to noone". And sure he must document it and know how it works. But that > documentation can remain private, limited to the developers of the > product. It doesn't have to be publicly documented. If the audience is the programmer(s) who implement the "private" API it is not private but public. Even the "public" API is somewhat "private" to a user of a program that uses that API. The public is not virtually anyone here. Depends at which level you look in the system. Ciao, Marc 'BlackJack' Rintsch From mail at timgolden.me.uk Tue Jun 10 15:06:52 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 10 Jun 2008 20:06:52 +0100 Subject: Python doesn't understand %userprofile% In-Reply-To: References: Message-ID: <484ED0CC.6050004@timgolden.me.uk> drobinow at gmail.com wrote: > On Jun 10, 2:09 pm, Duncan Booth wrote: >> bsag... at gmail.com wrote: >>> In xp when I try os.path.getmtime("%userprofile/dir/file%") Python >>> bites back with "cannot find the path specified" Since my script has >>> to run on machines where the username is unspecified I need a fix. >>> Thanks in advance. >>>>> os.path.expanduser("~/dir/file") >> 'C:\\Documents and Settings\\Duncan/dir/file' > > "~" appears to look first at the HOME environment variable. > That is not necessarily the same as "USERPROFILE". On my machine it is > not. There was quite a debate over that on python-dev earlier this year. In short, it's not easy to identify exactly what "~" means on a Windows box. The implementer of that patch took the view that HOME comes first and then USERPROFILE, finally HOMEDRIVE/SHARE/PATH. On my machine at work, the latter should take precedence as they are set via my domain logon. Other people's mileage may vary. In addition, the code assumes that the home for any *other* user can always be derived from the *current* user's home. Which will not always be the case. All that is essentially why the user-specific functions exposed in win32profile rely on a logon token to operate. (Bit of a rant, but just to highlight that things are seldom what they seem). TJG From bearophileHUGS at lycos.com Thu Jun 12 13:13:17 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 12 Jun 2008 10:13:17 -0700 (PDT) Subject: Making wxPython a standard module? References: <3EEC30D2-4536-4CCA-9047-8542CFAF52EC@leafe.com> Message-ID: <53f780fb-84ae-46aa-8033-40731f7a5dca@d1g2000hsg.googlegroups.com> Andrea Gavana: > Maybe. But I remember a nice quote made in the past by Roger Binns (4 > years ago): > """ > The other thing I failed to mention is that the wxPython API isn't very > Pythonic. (This doesn't matter to people like me who are used to GUI > programming - the wxPython API is very much in the normal style for GUI > APIs.) > """ There was a WX wrapper project named WAX (http://zephyrfalcon.org/ waxapi/wx._core.Image.html ) that was trying to create a more pythonic API for WX that I have appreciated. But most people was not interested, so once the original developer has lost interest, no one else has improved the code, so the project has died... Bye, bearophile From Lie.1296 at gmail.com Mon Jun 9 12:12:25 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 9 Jun 2008 09:12:25 -0700 (PDT) Subject: Can I find out (dynamically) where a method is defined? References: Message-ID: <8f177e57-75af-4d12-8307-a146eb17736e@w8g2000prd.googlegroups.com> On Jun 9, 10:28?pm, allendow... at gmail.com wrote: > Hi All. > > In a complex inheritance hierarchy, it is sometimes difficult to find > where a > method is defined. ?I thought it might be possible to get this info > from the > method object itself, but it looks like maybe not. ?Here is the test > case I tried: > > class A(object): > ? ? def method(): > ? ? ? ? pass > > class B(A): > ? ? pass > > a = A() > b = B() > > print a.method > print b.method > > Since B inherits method from A, I thought that printing b.method might > tell > me that the definition is in A, but no. ?Here's the output: > > > > > > > This in indistinguishable from the case where B overrides method. > > So, is there any way to inspect a method to see where (in what class) > it > is defined? I don't know if there is other easier methods, but if you have access to the source code, you can always add a print function. class A(object): def method(self): print 'Entering A.method' ... The rest of the codes ... class B(A): def method(self): print 'Entering B.method' ... The rest of the codes ... class C(A): pass If you don't have access to the source code, that means you shouldn't need to worry about it. A rather odd thing I just noticed is this: class A(object): def method(self): pass class B(A): def method(self): pass class C(A): pass print A.method == B.method ## False print A.method == C.method ## True From zapwireDASHgroups at yahoo.com Wed Jun 4 16:20:16 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Wed, 4 Jun 2008 13:20:16 -0700 Subject: php vs python References: <6ak1pjF379qfdU2@mid.uni-berlin.de> Message-ID: <8OC1k.150152$Tj3.133613@en-nntp-02.dc1.easynews.com> "Marc 'BlackJack' Rintsch" wrote in message news:6ak1pjF379qfdU2 at mid.uni-berlin.de... > I think you are talking about something a little different than Arnaud. Ah, OK. > Other old habits from people coming to Python are: using indexes where they > are not needed, trivial getters and setters, putting *everything* into > classes and every class into a module, and so on. Some of that is more political/policy than anything having to do with the language. Python likes to make it blatantly obvious that a lot of it is unnecessary, so it puts the "control freak" type of programmers on the defensive when, e.g., class variables and methods aren't private by default. (Guido's "we're all conesenting adults here" is of course a good response to this!) > Another difference are internal versus external iterators. In Python you > write the loop outside the iterable and pull the items out of it. In > other languages (Ruby, Io, .) iterables do internal iteration and you give > them a function where all item are "pushed" into one at a time. The Python method is -- IMO -- rather more powerful here, even if the whole protocol is somewhat less explciti than the Ruby/Io/etc. approach. > What makes C++ a "first class" language? My somewhat arbitrary definition is something along the lines of a language with most all of the "contemporary" features expected of languages (e.g., "old school" procedural languages like C/Pascal/Fortran 77 don't count) that are targeting at writing everything from small utilities to programs of various sizes to full-blown operating systems. > And did you quote "first class" > for the same reason than I did? ;-) Probably... C++ is kinda like the McMaster-Carr catalog, whereas Python is a well-stocked hardware store with knowledgable salespeople. ---Joel From __peter__ at web.de Mon Jun 30 09:51:24 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 30 Jun 2008 15:51:24 +0200 Subject: List Performance References: <42358e0b-a351-4862-8f6a-1938eedeff6c@s21g2000prm.googlegroups.com> <2eydnaP-saOZQfXVnZ2dnUVZ_qvinZ2d@comcast.com> Message-ID: Larry Bates wrote: > Peter Otten wrote: >> Ampedesign wrote: >> >>> If I happen to have a list that contains over 50,000 items, will the >>> size of the list severely impact the performance of appending to the >>> list? >> >> No. >> >> $ python -m timeit -n20000 -s"items = []" "items.append(42)" >> 20000 loops, best of 3: 0.554 usec per loop >> $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" >> 20000 loops, best of 3: 0.529 usec per loop >> >> http://wiki.python.org/moin/TimeComplexity >> >> Peter > > Peter, > > So its actually faster to append to a long list than an empty one? That > certainly would not have been intuitively obvious now would it? You shouldn't blindly trust the numbers. Here's what happens if I repeat the measurements a few times: $ python -m timeit -n20000 -s"items = []" "items.append(42)" 20000 loops, best of 3: 0.531 usec per loop $ python -m timeit -n20000 -s"items = []" "items.append(42)" 20000 loops, best of 3: 0.511 usec per loop $ python -m timeit -n20000 -s"items = []" "items.append(42)" 20000 loops, best of 3: 0.512 usec per loop $ python -m timeit -n20000 -s"items = []" "items.append(42)" 20000 loops, best of 3: 0.51 usec per loop $ python -m timeit -n20000 -s"items = []" "items.append(42)" 20000 loops, best of 3: 0.514 usec per loop $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" 20000 loops, best of 3: 0.506 usec per loop $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" 20000 loops, best of 3: 0.512 usec per loop $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" 20000 loops, best of 3: 0.543 usec per loop $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" 20000 loops, best of 3: 0.522 usec per loop $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" 20000 loops, best of 3: 0.51 usec per loop The difference is within the error margin. All you can say is that both operations take roughly the same time. In general, if no error margin (e. g. 0.5+-0.1) is given that is always a warning sign, be it opinion polls or timeit output. Peter From raashidbhatt at gmail.com Thu Jun 19 01:41:54 2008 From: raashidbhatt at gmail.com (raashid bhatt) Date: Wed, 18 Jun 2008 22:41:54 -0700 (PDT) Subject: good Message-ID: <0818dbbe-5019-4b0a-8254-4591d77d8084@f24g2000prh.googlegroups.com> I like your programming choice becaz python is safe than c or c++ or any other compiled languages as it protects against buffer overflow which causes potentail security problems i am wanted to know how many requests can it handle is it configurable for that.....
    Raashid Bhatt (C) From zapwireDASHgroups at yahoo.com Sun Jun 1 19:42:24 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Sun, 1 Jun 2008 16:42:24 -0700 Subject: php vs python References: Message-ID: "Ethan Furman" wrote in message news:mailman.1782.1212179802.12834.python-list at python.org... > Jerry Stuckle wrote: > > As I've said before - good programmers can write good code in any > > language. > So... an eloquent speaker of English is also an eloquent speaker of > Spanish/French/German? There's potentially a large difference between a "good" speaker of English/German/etc. vs. "eloquent." I'd tend to agree with Jerry that if you can write "good" code in one language, you can in pretty much any other as well... but that doesn't imply you're necessarily "eloquent" in any languages. :-) Eloquence is nice, but eradicating "bad" code in this world is about a million times more important than attempting to move people from "good" code to "eloquent" code. To be Pythonic here, "eloquent" code would perhaps often have clear, clean list comprehensions used when "good" code would use a "for" loop but still be easy to follow as well and perfectly acceptable in the vast majority of cases. From buzzard at urubu.freeserve.co.uk Fri Jun 13 05:43:14 2008 From: buzzard at urubu.freeserve.co.uk (duncan smith) Date: Fri, 13 Jun 2008 10:43:14 +0100 Subject: boolian logic In-Reply-To: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> References: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> Message-ID: marc wyburn wrote: > HI all, I'm a bit stuck with how to work out boolian logic. > > I'd like to say if A is not equal to B, C or D: > do something. > > I've tried > > if not var == A or B or C: > and various permutations but can't seem to get my head around it. I'm > pretty sure I need to know what is calulated first i.e the not or the > 'OR/AND's > > thanks, Marc. There's a number of ways of coding it. How about, if not var in [A, B, C]: #do stuff Duncan From tjreedy at udel.edu Sun Jun 29 14:54:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 29 Jun 2008 14:54:25 -0400 Subject: tkinter, loading image error, TclError: couldn't recognize data in image file "C:/users/me/desktop/images/blob4.jpg" In-Reply-To: <0ae49ec6-2d6a-48bd-9112-dc0237363822@25g2000hsx.googlegroups.com> References: <0ae49ec6-2d6a-48bd-9112-dc0237363822@25g2000hsx.googlegroups.com> Message-ID: defn noob wrote: > from Tkinter import * > import os > > master = Tk() > w = Canvas(master, width=800, height=600) > > print os.path.exists('C:/me/saftarn/desktop/images/blob4.jpg') > > im = PhotoImage(file = 'C:/users/saftarn/desktop/images/blob4.jpg') > #im = file = 'C:/users/me/desktop/images/blob4.jpg' > pic = w.create_image(0, 0, image = im, anchor = NW) > > #image = open('C:/users/saftarn/desktop/images/blob.png') > > colors = [] > for x in range(1, 800): > for y in range(1, 600): > pic = w.find_closest(x, y)[0] > obj = objects[pic] > colors.append(obj.get(int(x), int(y))) > > print colors > > > > True > > Traceback (most recent call last): > File "C:/Python25/Progs/ImageVideoSearch/imId.py", line 9, in > > im = PhotoImage(file = 'C:/users/me/desktop/images/blob4.jpg') > File "C:\Python25\lib\lib-tk\Tkinter.py", line 3270, in __init__ > Image.__init__(self, 'photo', name, cnf, master, **kw) > File "C:\Python25\lib\lib-tk\Tkinter.py", line 3226, in __init__ > self.tk.call(('image', 'create', imgtype, name,) + options) > TclError: couldn't recognize data in image file "C:/users/me/desktop/ > images/blob4.jpg" > > > > it has worked before opening and displaying a file like this, anything > to do with python 2.52, upgraded from 2.5.1 Did it work with that exact file? Have you tried other files that did work with 2.5.1? The error comes from tcl/tk, not Python. I expect that the version of tcl/tk delivered with 2.5.2 is exactly the same as that delivered with 2.5.1, just to avoid such problems. Note that even if one program displays a file it may still be slightly corrupt and properly fail to display with another. If you have an image editor, you might try opening and saving (different name) without changing. tjr From tjreedy at udel.edu Tue Jun 24 01:40:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Jun 2008 01:40:03 -0400 Subject: An idiom for code generation with exec In-Reply-To: <0967da3a-1fea-401e-896d-9c099b3054ce@c58g2000hsc.googlegroups.com> References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485f4f35$0$28417$426a74cc@news.free.fr> <0967da3a-1fea-401e-896d-9c099b3054ce@c58g2000hsc.googlegroups.com> Message-ID: eliben wrote: > And while we're on the topic of what compilation means in Python, It depends on the implementation. I'm > not sure I fully understand the difference between compiled (.pyc) > code and exec-ed code. Is the exec-ed code turned to bytecode too, > i.e. it will be as efficient as compile-d code ? CPython always compiles to bytecode before executing. There is no alternative execution path. From jsloop at austin.rr.com Wed Jun 18 21:02:40 2008 From: jsloop at austin.rr.com (John Sloop) Date: Wed, 18 Jun 2008 20:02:40 -0500 Subject: Python email server Message-ID: <008301c8d1a8$2c74c460$855e4d20$@rr.com> I am starting to build a Python email server. Before assembling the individual pieces I am wondering if there is a prebuilt package anyone would recommend? Thanks in advance for your advice and guidance. John S. -------------- next part -------------- An HTML attachment was scrubbed... URL: From carsten.haese at gmail.com Wed Jun 11 10:14:58 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Wed, 11 Jun 2008 10:14:58 -0400 Subject: problems with opening files due to file's path In-Reply-To: <77acc29a-fffa-44d6-b07b-6bcf8b5bdd74@h1g2000prh.googlegroups.com> References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> <77acc29a-fffa-44d6-b07b-6bcf8b5bdd74@h1g2000prh.googlegroups.com> Message-ID: Lie wrote: > In most GUI toolkits (including Tkinter) and raw_input() function, > when you input a string (using the textbox, a.k.a Entry widget) it > would automatically be escaped for you, so when you input 'path\path > \file.txt', the GUI toolkit would convert it into 'path\\path\ > \file.txt'. That's incorrect. If you enter text into a text box or in raw_input(), *no* conversion of backslashes is happening. A backslash entered in raw_input is just a backslash. A backslash entered in a textbox is just a backslash. A backslash read from a file is just a backslash. A "conversion" happens when you print the repr() of a string that was obtained from raw_input or from a text box, because repr() tries to show the string literal that would result in the contents, and in a string literal, a backslash is not (always) a backslash, so repr() escapes the backslashes: py> text = raw_input("Enter some text: ") Enter some text: This is a backslash: \ py> print text This is a backslash: \ py> print repr(text) 'This is a backslash: \\' As you can see, I entered a single backslash, and the string ends up containing a single backslash. Only when I ask Python for the repr() of the string does the backslash get doubled up. -- Carsten Haese http://informixdb.sourceforge.net From rubrum at pacbell.net Tue Jun 17 20:13:36 2008 From: rubrum at pacbell.net (Michael Press) Date: Tue, 17 Jun 2008 17:13:36 -0700 Subject: Multiprecision arithmetic library question. Message-ID: I already compiled and installed the GNU multiprecision library on Mac OS X, and link to it in C programs. How do I link to the library from Python? I do not want to download and install redundant material. (I am new to Python) -- Michael Press From alexnbryan at gmail.com Fri Jun 27 13:41:13 2008 From: alexnbryan at gmail.com (Alexnb) Date: Fri, 27 Jun 2008 10:41:13 -0700 (PDT) Subject: using urllib2 In-Reply-To: <200806271227.17081.maric@aristote.info> References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> Message-ID: <18160312.post@talk.nabble.com> Okay, I tried to follow that, and it is kinda hard. But since you obviously know what you are doing, where did you learn this? Or where can I learn this? Maric Michaud wrote: > > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit?: >> I have never used the urllib or the urllib2. I really have looked online >> for help on this issue, and mailing lists, but I can't figure out my >> problem because people haven't been helping me, which is why I am here! >> :]. >> Okay, so basically I want to be able to submit a word to dictionary.com >> and >> then get the definitions. However, to start off learning urllib2, I just >> want to do a simple google search. Before you get mad, what I have found >> on >> urllib2 hasn't helped me. Anyway, How would you go about doing this. No, >> I >> did not post the html, but I mean if you want, right click on your >> browser >> and hit view source of the google homepage. Basically what I want to know >> is how to submit the values(the search term) and then search for that >> value. Heres what I know: >> >> import urllib2 >> response = urllib2.urlopen("http://www.google.com/") >> html = response.read() >> print html >> >> Now I know that all this does is print the source, but thats about all I >> know. I know it may be a lot to ask to have someone show/help me, but I >> really would appreciate it. > > This example is for google, of course using pygoogle is easier in this > case, > but this is a valid example for the general case : > >>>>[207]: import urllib, urllib2 > > You need to trick the server with an imaginary User-Agent. > >>>>[208]: def google_search(terms) : > return urllib2.urlopen(urllib2.Request("http://www.google.com/search?" > + > urllib.urlencode({'hl':'fr', 'q':terms}), > headers={'User-Agent':'MyNav > 1.0 > (compatible; MSIE 6.0; Linux'}) > ).read() > .....: > >>>>[212]: res = google_search("python & co") > > Now you got the whole html response, you'll have to parse it to recover > datas, > a quick & dirty try on google response page : > >>>>[213]: import re > >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

    .*?

    ', > res) ] > ...[229]: > ['Python Gallery', > 'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des Monty ...', > 'Re: os x, panther, python & co: msg#00041', > 'Re: os x, panther, python & co: msg#00040', > 'Cardiff Web Site Design, Professional web site design services ...', > 'Python Properties', > 'Frees < Programs < Python < Bin-Co', > 'Torb: an interface between Tcl and CORBA', > 'Royal Python Morphs', > 'Python & Co'] > > > -- > _____________ > > Maric Michaud > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/using-urllib2-tp18150669p18160312.html Sent from the Python - python-list mailing list archive at Nabble.com. From bearophileHUGS at lycos.com Thu Jun 19 08:53:18 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 19 Jun 2008 05:53:18 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <1ea1731d-9de9-4e73-9c08-e9f5572b9fd6@t54g2000hsg.googlegroups.com> <1a8797c6-a165-49b1-82de-94a6054cf856@z16g2000prn.googlegroups.com> Message-ID: dbpoko...: > Which should be 12 bytes on a 32-bit machine. I thought the space for > growth factor for dicts was about 12% but it is really 100%. (Please ignore the trailing ".2" in my number in my last post, such precision is silly). My memory value comes from experiments, I have created a little program like this: from memory import memory def main(N): m1 = memory() print m1 d = {} for i in xrange(N): d[i] = None m2 = memory() print m2 print float((m2 - m1) * 1024) / N main(20000000) Where memory is a small module of mine that calls a little known program that tells how much memory is used by the current Python process. The results for that run n=20000000 are (first two numbers are kilobytes, the third number is byte/pair): 1876 633932 32.3612672 It means to store 20_000_000 pairs it requires about 647_000_000 bytes, Python 2.5.2, on Win. Bye, bearophile From nick at craig-wood.com Sun Jun 8 15:30:46 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sun, 08 Jun 2008 14:30:46 -0500 Subject: time.clock() or Windows bug? References: Message-ID: Theo v. Werkhoven wrote: > In this code I read out an instrument during a user determined period, > and save the relative time of the sample (since the start of the test) > and the readback value in a csv file. > > from datetime import * > from time import * > from visa import * > from random import * > [..] > for Reading in range(Readings): > RelTimeOfSample = "%.1f" % clock() > #PwrMtr.write("READ?") > #Sample = "%.3f" % float(PwrMtr.read()) > Sample = "%.3f" % (uniform(8.9,9.3)) # Simulation of reading. > print "Sample %s, at %s seconds from start; Output power is: %s dBm" > % (Reading+1, RelTimeOfSample, Sample) > writer.writerow([RelTimeOfSample, Sample]) > ResultFile.flush() > sleep(6.6) > > Output: > Sample 1, at 0.0 seconds from start; Output power is: 8.967 dBm [snip] > Sample 17, at 105.7 seconds from start; Output power is: 9.147 dBm > Sample 18, at 112.4 seconds from start; Output power is: 9.284 dBm > Sample 19, at 119.0 seconds from start; Output power is: 9.013 dBm > Sample 20, at 125.6 seconds from start; Output power is: 8.952 dBm > Sample 21, at 91852.8 seconds from start; Output power is: 9.102 dBm > Sample 22, at 91862.7 seconds from start; Output power is: 9.289 dBm > Sample 23, at 145.4 seconds from start; Output power is: 9.245 dBm > Sample 24, at 152.0 seconds from start; Output power is: 8.936 dBm [snip] > But look at the timestamps of samples 21, 22 and 43. > What is causing this? > I've replaced the time.clock() with time.time(), and that seems to > solve the problem, but I would like to know if it's something I > misunderstand or if it's a problem with the platform (Windows Server > 2003) or the time.clock() function. time.clock() uses QueryPerformanceCounter under windows. There are some known problems with that (eg with Dual core AMD processors). See http://msdn.microsoft.com/en-us/library/ms644904.aspx And in particular On a multiprocessor computer, it should not matter which processor is called. However, you can get different results on different processors due to bugs in the basic input/output system (BIOS) or the hardware abstraction layer (HAL). To specify processor affinity for a thread, use the SetThreadAffinityMask function. I would have said time.time is what you want to use anyway though because under unix time.clock() returns the elapsed CPU time which is not what you want at all! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From karsten.heymann at blue-cable.net Fri Jun 13 08:12:40 2008 From: karsten.heymann at blue-cable.net (Karsten Heymann) Date: Fri, 13 Jun 2008 14:12:40 +0200 Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> Message-ID: <878wx9leiv.fsf@ara.blue-cable.net> Hi Mark, Mark writes: > I have a scenario where I have a list like this: > > User Score > 1 0 > 1 1 > 1 5 > 2 3 > 2 1 > 3 2 > 4 3 > 4 3 > 4 2 > > And I need to add up the score for each user to get something like > this: > > User Score > 1 6 > 2 4 > 3 2 > 4 8 > > Is this possible? If so, how can I do it? I've tried looping through > the arrays and not had much luck so far. Although your problem has already been solved, I'd like to present a different approach which can be quite a bit faster. The most common approach seems to be using a dictionary: summed_up={} for user,vote in pairs: if summed_up.has_key(user): summed_up[user]+=vote else: summed_up[user]=vote But if the list of users is compact and the maximum value is known before, the using a list and coding the user into the list position is much more elegant: summed_up=list( (0,) * max_user ) for user,vote in pairs: summed_up[user] += vote I've run a quick and dirty test on these approaches and found that the latter takes only half the time than the first. More precisely, with about 2 million pairs, i got: * dict approach: 2s (4s with "try: ... except KeyError:" instead of the "if") * list approach: 0.9s BTW this was inspired by the book "Programming Pearls" I read some years ago where a similar approach saved some magnitudes of time (using a bit field instead of a list to store reserved/free phone numbers IIRC). Yours, Karsten From bruno.42.desthuilliers at websiteburo.invalid Fri Jun 27 11:44:28 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 27 Jun 2008 17:44:28 +0200 Subject: what is meaning of "@" in pyhon program. In-Reply-To: <4bfb891d-7a7b-45bc-b126-1d485c9206ee@m44g2000hsc.googlegroups.com> References: <88990b3d-1916-413f-83b9-796aabf43623@l28g2000prd.googlegroups.com> <19aa4978-242b-4732-b072-aa5ff16975b0@27g2000hsf.googlegroups.com> <486502bf$0$6426$426a74cc@news.free.fr> <4bfb891d-7a7b-45bc-b126-1d485c9206ee@m44g2000hsc.googlegroups.com> Message-ID: <48650adb$0$7975$426a74cc@news.free.fr> Damon Getsman a ?crit : > Okay, maybe I just didn't understand the websites that were given as > examples as to 'decoration'. I first came across the unusual '@' when > I was browsing through some extreme beginner's information on os.x > method descriptions. I asked some other people about it and they had > no idea what it meant. I don't _THINK_ that the decoration definition > fits, though, because the examples that I saw it in had it prefixing > an if conditional & a for loop. > > ie: > @if os.exists(foo): > etc > etc > > and > > @for blah: > etc > etc This is not valid Python. period. From exarkun at divmod.com Fri Jun 20 13:17:57 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 20 Jun 2008 13:17:57 -0400 Subject: Python "is" behavior In-Reply-To: <537daeff-e283-47bf-b539-3e6c99aabe5a@m45g2000hsb.googlegroups.com> Message-ID: <20080620171757.4714.198154922.divmod.quotient.11254@ohm> On Fri, 20 Jun 2008 10:07:56 -0700 (PDT), George Sakkis wrote: >On Jun 20, 12:45 pm, michalis.avr... at gmail.com wrote: >> On Jun 20, 9:42 am, George Sakkis wrote: >> >> >> >> > On Jun 20, 12:31 pm, michalis.avr... at gmail.com wrote: >> >> > > I am not certain why this is the case, but... >> >> > > >>> a = 256 >> > > >>> b = 256 >> > > >>> a is b >> >> > > True >> >> > > >>> a = 257 >> > > >>> b = 257 >> > > >>> a is b >> >> > > False >> >> > > Can anyone explain this further? Why does it happen? 8-bit integer >> > > differences? >> >> > No, implementation-dependent optimization (caching). For all we know, >> > the next python version may cache up to 1024 or it may turn off >> > caching completely; do not rely on it. More generally, do not use 'is' >> > when you really mean '=='. >> >> > George >> >> Thank you George. I am very curious about some of these internal >> Python things that I keep stumbling upon through friends. And thank >> you for all the help! > >As far it's plain curiosity it's ok, but it's a small implementation >detail you shouldn't rely on. There's nothing magic about 256, just >the size decided for 2.5. If you tried it on 2.4 you'd get: > >Python 2.4.2 (#1, Mar 8 2006, 13:24:00) >[GCC 3.4.4 20050721 (Red Hat 3.4.4-2)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> a=99 >>>> b=99 >>>> a is b >True >>>> a=100 >>>> b=100 >>>> a is b >False > >I was more surprised by the following: > >Python 2.5.1 (r251:54863, May 8 2007, 14:46:30) >[GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> a= 123456; b=123456; a is b >True > >For some reason, stacking multiple statements reuses the same object. > This is because using the ";" puts the statements into the same compilation unit as each other. So secretly an integer object is created for 123456 and then a and b are both given a reference to it. This is a different mechanism than the other case, where the builtin integer cache causes the literal 100 to refer to the same object each time it is evaluated. Jean-Paul From dwahli at gmail.com Fri Jun 6 02:56:40 2008 From: dwahli at gmail.com (dwahli at gmail.com) Date: Thu, 5 Jun 2008 23:56:40 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> Message-ID: <769c54bf-8664-4179-bd17-c18705320606@27g2000hsf.googlegroups.com> On Jun 6, 8:44?am, "Terry Reedy" wrote: > > Of course, enumerate(iterable) is just a facade over zip(itertools.count(), > iterable) So you could write: gen = (x for x in itertools.izip(itertools.count(8), [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3])) print list(gen) Using zip like you own example is the best option. If you have a huge amount of data and only want to iterate over the result, using a generator is probably better: gen = (x for x in itertools.izip(itertools.count(8), [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3])) for i, j in gen: ... your code here ... From mark.hachey at gmail.com Sat Jun 14 17:33:24 2008 From: mark.hachey at gmail.com (Hachey) Date: Sat, 14 Jun 2008 14:33:24 -0700 (PDT) Subject: sorting a file References: Message-ID: <90f51884-5d70-40c9-b05c-0f3b3f7cc8d1@e39g2000hsf.googlegroups.com> On Jun 14, 12:00 pm, jim-on-linux wrote: > On Saturday 14 June 2008 03:15, Beema > > shafreen wrote: > > Hi all, > > > I have a file with three columns i need > > to sort the file with respect to the third > > column. How do I do it uisng python. I > > used Linux command to do this. Sort but i > > not able to do it ? can any body ssuggest > > me > > I have used this method to solve similar > problems. > > This is a consept of how to do what you want, > but you will have to work a little to get it > right. > > You might try something like this; > > Dict = {} ##create a dictionary > > make a list of all column3 values > > for loop colum3 values > > Make these values the key in a dictionary > If the values are long, you can use the first > 7 to 15 characters if you want. > > use this key to equal all the values in the > other columns on the same row. > > Dict[column3] = column1, column2, column3 > > once the dictionary is made > > get the dictionary key > x = Dict.keys() ## get the keys from Dict > > x.sort() # produce a sorted list of keys of > column3 > > Loop these sorted keys to extract from the > dictionary the values related to each > > jim-on-linux > http://:inqvista.com Here's another way to attack it. Make a class that takes your columns as arguments. define an operator on that class to get the comparison you want. make a list that is your rows, and call sort. here's an example using only two columns class twoColumns : def __init__(self, c1 = 0, c2 = 0) : self.c1 = c1 self.c2 = c2 #just use this for debugging if you want to see everything def getVals(self): print self.c1, self.c2 #order members of this class by the second column def __lt__(c,d): if (c.c2 < d.c2) : return 1 else : return 0 #end class definition Here's what happened when I used this class. >>> r1 = twoColumns(3,4) >>> r2 = twoColumns(1,5) >>> test = [r1,r2] #this is already sorted >>> test[0].getVals() 3 4 >>> test[1].getVals() 1 5 >>> test.sort() #and the sort looks the same >>> test[0].getVals() 3 4 >>> test[1].getVals() 1 5 >>> test = [r2,r1] #I reversed the rows >>> test[0].getVals() 1 5 >>> test[1].getVals() 3 4 >>> test.sort() #and we get what we want >>> test[0].getVals() 3 4 >>> test[1].getVals() 1 5 I think that does what you're asking. From ptmcg at austin.rr.com Tue Jun 17 02:20:51 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 16 Jun 2008 23:20:51 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <4856e80c$0$30401$9b622d9e@news.freenet.de> <97b828d8-e64c-47db-8b8e-d403e8076756@x35g2000hsb.googlegroups.com> <48574B8D.6010102@v.loewis.de> Message-ID: On Jun 17, 12:28?am, "Martin v. L?wis" wrote: > > My guess is that the two main memory allocate/deallocate cases are 1) > > appending a new item to the end, and 2) GC'ing the entire data > > structure. ?I would optimize these 2 at the expense of all others. > > Does that include dictionary lookups? > > Regards, > Martin Well, I did (try to) qualify my guess as pertaining specifically to memory allocate/deallocate cases, the other topics in the nearby posts were talking about updates to the odict, so I hope I can be forgiven this oversight. But you're right, the keyed access is one of the main reasons this is being done with an odict instead of just a list of tuples. The point I was trying to make was that sometimes, the GC case occurs far more frequently than other update methods, yet is overlooked because it happens invisibly to most Python users. I worked on a project a while ago where there was a huge performance penalty in releasing a list structure, because each node was freed individually, causing surrounding freelist entries to be updated for every node. In typical worst-case scenario fashion, a second list was built at the same time as the first, and the default system memory allocator interleaved the list nodes. The truly frustrating part was that at this point in the program, we were trying to free *all* the nodes in *both* lists, and would have preferred to just release the whole chunk of memory, if it had just been allocated in a large chunk instead of a node at a time. I implemented a zone-based memory allocator, so that nodes were allocated within a memory zone, but when we were done, we just released the entire zone, with tremendous improvement in system performance. But what kind of keyed access is likely to be used on an odict? For those cases where all of the items are desired, then I would recommend that the odict iterator be preferred, for this type of retrieval: for k,v in odictvar.iteritems(): # do something with key k and value v and discourage this usage: for k in odictvar.keys(): # or iterkeys() # do something with key k and value odictvar[k] How about this as a simple first approach? Let's assume that the nominal usage pattern for an odict is 1) create all entries in the odict, probably using append, 2) access some or all of the entries, either by iterating over the keys or values, or by keyed access to specific values, and 3) delete the odict. Have the odict keep an internal dict representing the keyed lookups, and have this internal dict set to null whenever the odict is updated. When the odict is accessed by specific key, the internal dict is used - if it null, it is built using dict(odict.iteritems()). In the nominal usage, this dict will only be built once, since the keyed accesses wont begin until after all of the key-value pairs have been added to the odict. Or as a first-first approach (to avoid premature optimization), just implement the odict as a list of tuples, and do linear search for matching key if accessed by key. I would bias any performance choices about keyed access toward cases where the queried key exists in the odict - I think that in those cases where odicts are used, such as ORMs and XML, the keys for a particular odict are known and expected to exist. Those applications where the keys are not known are likely to be meta-type apps, like debuggers and introspection GUIs. I contend that the meat-and- potatoes production apps will be those like database queries - when I get an odict back after querying an EMPLOYEES table, I really should reasonably expect odictvar["EMPNO"] to exist. And what would be the conditions of an abusive form of odict? How about an application log kept in an odict, keyed by timestamp? This could have many 1000's of entries, and yet, I would guess that an odict would be the wrong data structure for this, and that a list of tuples or LogMessage objects would be more appropriate. But someone is likely to do it - if they do, what will happen? Perhaps trying to anticipate "abusive" or degenerate uses of an odict might shed some light on ways to avoid, discourage, or maybe even accommodate these uses in odict. Well, this has become something of a rant, and a speculative one at that, but I think the "delete the entire data structure" memory case should be given reasonably high design attention. (And maybe this is already the norm in Python development - I'm really quite ignorant of this process, not being in the Python development circle.) Always nice to hear from you Martin - cheers! -- Paul From sjmachin at lexicon.net Thu Jun 12 07:47:43 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 12 Jun 2008 04:47:43 -0700 (PDT) Subject: using re module to find " but not " alone ... is this a BUG in re? References: Message-ID: <5aeb32bd-923f-4b98-952b-06097ac8479d@v1g2000pra.googlegroups.com> On Jun 12, 7:11 pm, anton wrote: > Hi, > > I want to replace all occourences of " by \" in a string. > > But I want to leave all occourences of \" as they are. > > The following should happen: > > this I want " while I dont want this \" > > should be transformed to: > > this I want \" while I dont want this \" > > and NOT: > > this I want \" while I dont want this \\" > > I tried even the (?<=...) construction but here I get an unbalanced paranthesis > error. Sounds like a deficit of backslashes causing re to regard \) as plain text and not the magic closing parenthesis in (?<=...) -- and don't you want (? > It seems tha re is not able to do the job due to parsing/compiling problems > for this sort of strings. Nothing is ever as it seems. > > Have you any idea?? For a start, *ALWAYS* use a raw string for an re pattern -- halves the backslash pollution! > > > re.findall("[^\\]\"","this I want \" while I dont want this \\\" ") and if you have " in the pattern, use '...' to enclose the pattern so that you don't have to use \" > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\re.py", line 175, in findall > return _compile(pattern, flags).findall(string) > File "C:\Python25\lib\re.py", line 241, in _compile > raise error, v # invalid expression > error: unexpected end of regular expression As expected. What you want is: >> import re >> text = r'frob this " avoid this \", OK?' >>> text 'frob this " avoid this \\", OK?' >> re.sub(r'(?> HTH, John From tjreedy at udel.edu Tue Jun 24 20:46:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Jun 2008 20:46:03 -0400 Subject: Sequence iterators with __index__ In-Reply-To: <119bb268-2064-4128-8006-f5564f0c62f8@q27g2000prf.googlegroups.com> References: <433c6aca-745e-4c9f-b182-d76291449829@m73g2000hsh.googlegroups.com> <119bb268-2064-4128-8006-f5564f0c62f8@q27g2000prf.googlegroups.com> Message-ID: schickb wrote: > On Jun 24, 3:45 pm, Matimus wrote: >>> I think it would be useful if iterators on sequences had the __index__ >>> method so that they could be used to slice sequences. I was writing a >>> class and wanted to return a list iterator to callers. I then wanted >>> to let callers slice from an iterator's position, but that isn't >>> supported without creating a custom iterator class. Creating custom classes is what the class statement is for. See below. >> Could you post an example of what you are talking about? I'm not >> getting it. > > Interactive mock-up: > >>>> a = ['x','y','z'] >>>> it = iter(a) >>>> a[it:] > ['x', 'y', 'z'] >>>> it.next() > 'x' >>>> a[it:] > ['y', 'z'] >>>> a[:it] > ['x'] >>>> it.next() > 'y' >>>> a[it:] > ['z'] > > This lets you use sequence iterators more general position indicators. > Currently if you want to track a position and slice from a tracked > position you must do it manually with an integer index. It's not > difficult, but given that sequence iterators already do that already > it seems redundant (and of course more error prone). Python's iterator protocol is intentionally simple and general. Wanting to slice while iterating is a *very* specialized usage. In any case: A. If the iterator uses in incrementing index to iterate, you want access. B. Using an iterator as an integer will strike most people as conceptually bizarre; it will never be accepted. C. Doing so is unnecessary since the internal index can just as easily be exposed as an integer attribute called 'index' or, more generally, 'count'. a[it.count:] looks *much* better. D. You can easily add .index or .count to any iterator you write. The iterator protocol is a minimum rather than maximum specification. E. You can easily wrap any iterable/iterator in an iterator class that provides .count for *any* iteration process. Slicing is not the only possible use of such an attribute. class indexerator(): def __inti__(self, iterable): self.it = iter(iterable) self.count = 0 def __iter__(self): return self def __next__(self): # 3.0 tem = self.it.next() self.count += 1 return tem .count is always the number of items returned. It is also the index of the next item to be returned if (but only if() the base iterable exists and is an indexable sequence. F. Even this should be unnecessary for most usages. Built-in function enumerate(iterable) generates count,item pairs in much the same manner: >> In any case, the first step is writing a PEP.http://www.python.org/dev/peps/ Discussion usually comes first. > Ok thanks, but I do want some idea of interest level before spending a > bunch of time on this. Even the developers sometimes take this precaution. Many ideas never make it to the PEP stage. I see no need for a change in Python here. Terry Jan Reedy From goldwamh at slu.edu Wed Jun 4 23:09:45 2008 From: goldwamh at slu.edu (Michael H. Goldwasser) Date: 04 Jun 2008 22:09:45 -0500 Subject: Books for programmers References: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> <32791EDC-1033-4B65-BFB5-DF1CF71EF20D@comhem.se> Message-ID: Dick Moores writes: > Do not neglect the 2008 book, "Object-Oriented Programming in Python", > by Goldwasser and Letscher. > > > > Dick Moores I'll note that our book is designed as a "CS1" text, and thus intended primarly for beginners. So its probably not a match for the original poster who wants a more advanced Python book. That said, I think its a great book for those with less experience. +----------------------------------------------- | Michael Goldwasser | Associate Professor | Dept. Mathematics and Computer Science | Saint Louis University | 220 North Grand Blvd. | St. Louis, MO 63103-2007 From ladasky at my-deja.com Wed Jun 4 12:03:26 2008 From: ladasky at my-deja.com (John Ladasky) Date: Wed, 4 Jun 2008 09:03:26 -0700 (PDT) Subject: Import, site packages, my modules, Windows vs. Linux References: <4993bd3d-22aa-4e0d-a593-38c0f5e2d69a@m44g2000hsc.googlegroups.com> <878wxmm0fa.fsf@benfinney.id.au> Message-ID: On Jun 3, 6:52 pm, Ben Finney wrote: > John Ladasky writes: > > I want to know what is the *recommended* way to integrate my own > > personal modules with Python. Thanks! > > You want the 'distutils' documentation > and the documents > that it references, which will lead you to write a 'setup.py' module > for your package. Many thanks, Ben, distutils was exactly what I needed. It was a little strange to grasp the concept that I would be "distributing" my module to myself -- but once I got over that mental hurdle, it worked perfectly. From hall.jeff at gmail.com Mon Jun 23 15:50:58 2008 From: hall.jeff at gmail.com (hall.jeff at gmail.com) Date: Mon, 23 Jun 2008 12:50:58 -0700 (PDT) Subject: tuple.index() and tuple.count() Message-ID: <0411a4b3-7b99-41f9-980e-dd81845101bd@y21g2000hsf.googlegroups.com> Before the inevitable response comes, let me assure you I've read through the posts from Guido about this. 7 years ago Guido clearly expressed a displeasure with allowing these methods for tuple. Let me lay out (in a fresh way) why I think we should reconsider. 1) It's counterintuitive to exclude them: It makes very little sense why an indexable data structure wouldn't have .index() as a method. It makes even less sense to not allow .count() 2) There's no technical reason (that I'm aware of) why these can't be added 3) It does not (contrary to one of Guido's assertions) require any relearning of anything. It's a new method that could be added without breaking any code whatsoever (there isn't even a UserTuple.py to break) 4) The additional documentation is relatively minute (especially since it could be copied and pasted virtually verbatim from the list methods 5) It's MORE Pythonic to do it this way (more intuitive, less boilerplate) 6) It jives with the help file better. One of Guido's many stated reasons was that tuples are for heterogeneous sequences and lists are for homogeneous sequences. While this may be hypothetically true, the help file does not come close to pointing you in this direction nor does the implementation of the language. example: "Tuples have many uses. For example: (x, y) coordinate pairs, employee records from a database, etc. Tuples, like strings, are immutable: it is not possible to assign to the individual items of a tuple (you can simulate much of the same effect with slicing and concatenation, though). It is also possible to create tuples which contain mutable objects, such as lists." is a quote from the help file. Not only does it never mention homogeneous vs. heterogeneous but mentions both immutable and mutable which draws your mind and attention to that aspect. While tuples and lists may have different uses based on convention, there's really only two reasons to ever use a tuple: Efficiency or dictionary keys (or some similar immutability requirement). The implementation contains absolutely NOTHING to reinforce the idea that lists are for homogeneous data. The implementation of the language contains EVERY indication that tuples are second class citizens only to be used for those limited functions above (in fact, efficiency isn't even talked about in the documentation... I pieced that together from other threads). Tuples could have been implemented as frozenlist just as easily. The lack of .index() and .count() appears to be primarily motivated by a subtle and silent (at least in the documentation) desire to push towards coding "best practice" rather than for any technical reason. While I'm certainly not a "change for change sake" kind of guy and I understand the "bang for your buck" thinking, I'm just not seeing the rational for stopping this so forcibly. I get the impression that if a perfect working patch was submitted, Guido might still reject it which just seems odd to me. Again, I'm not trying to raise a stink or open old wounds, I just ran across it in an app, started doing some research and was thoroughly confused (for the record, I'm using the tuples as dictionary keys and had a desire to do k.count() for some edit checks and realized I had to convert the thing to a list first to run count() ) From pfreixes at milnou.net Tue Jun 3 15:58:12 2008 From: pfreixes at milnou.net (Pau Freixes) Date: Tue, 3 Jun 2008 21:58:12 +0200 Subject: Different execution time in python code between embedded or standalone Message-ID: <207312b70806031258n68b9dfl942e098e5119c1dc@mail.gmail.com> Hi list, First Hello to all, this is my and hope not end message to the list :P This last months I have been writting a program in c like to mod_python for embedding python language, it's a middleware for dispatch and execute python batch programs into several nodes. Now I'm writing some python program for test how scale this into several nodes and comparing with "standalone" performance. I found a very strange problem with one application named md5challenge, this aplication try to calculate the max number md5 digest in several seconds, md5challenge use a simple signal alarm for stop program when time has passed. This is the code of python script def handler_alrm(signum, frame): global _signal global _nrdigest global _f _signal = True def try_me(): global _nrdigest global _f global _signal _f = open("/dev/urandom","r") while _signal is not True: buff = _f.read(_const_b) md5.md5(buff).hexdigest() _nrdigest = _nrdigest + 1 if _f is not None : _f.close() def main( req ): global _nrdigest signal.signal(signal.SIGALRM, handler_alrm) signal.alarm(req.input['time']) try_me() req.output['count'] = _nrdigest return req.OK if __name__ == "__main__": # test code class test_req: pass req = test_req() req.input = { 'time' : 10 } req.output = { 'ret' : 0, 'count' : 0 } req.OK = 1 main(req) print "Reached %d digests" % req.output['count'] When I try to run this program in standalone into my Pentium Dual Core md4challenge reached 1.000.000 milion keys in 10 seconds but when i try to run this in embedded mode md5challenge reached about 200.000 more keys !!! I repeat this test many times and always wins embedded mode !!! What's happen ? Also I tested to erase read dependencies from /dev/random, and calculate all keys from same buffer. In this case embedded mode win always also, and the difference are more bigger !!! Thks to all, can anybody help to me ? -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From pythonblogs at gmail.com Mon Jun 2 21:33:16 2008 From: pythonblogs at gmail.com (pythonblogs at gmail.com) Date: Mon, 2 Jun 2008 18:33:16 -0700 (PDT) Subject: python blogs References: <19d5037f-837d-4f6b-9e56-d4e6d84b277d@y22g2000prd.googlegroups.com> Message-ID: <61119f97-9d1c-4ea9-af05-34ae70fb3bcf@p39g2000prm.googlegroups.com> On Jun 2, 2:14 pm, miller.pau... at gmail.com wrote: > On Jun 2, 2:49 pm, pythonbl... at gmail.com wrote: > > http://www.pythonblogs.com > > It seems like Python blogs are gaining popularity. It seems to me that > > they play a crucial role in promoting Python as a language. > > Neat! Do blogs on your site have to be about Python programming, or > can people blog about anything? Sure, feel free to blog about anything. However, it is assumed that Python will also be one of your topics :) ~pyblog From vasudevram at gmail.com Tue Jun 3 17:05:25 2008 From: vasudevram at gmail.com (vasudevram) Date: Tue, 3 Jun 2008 14:05:25 -0700 (PDT) Subject: Books for programmers References: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> <78ef063d-7219-4ffa-bf8f-88dc24dd90bc@r66g2000hsg.googlegroups.com> Message-ID: <6f709bc8-a527-420a-92c9-6e829fd0315d@w34g2000prm.googlegroups.com> On Jun 3, 6:42 pm, Mike Driscoll wrote: > On Jun 3, 5:45 am, V wrote: > > > Hi Matt, > > > and thank you very much for your answer. > > > > Hm, depends of course, how good your programming skills are in the > > > languages you knwo already, but I rely on the book "Beginning Python - > > > From Novice to Professional" by Magnus Lie Hetland, published by Apress. > > > I think that I'm interested in a more advance book, ideally one that > > talk of the Python gotchas, traps, pitfall, idioms, performance, > > stile, and so on. I really like the style used from Scott Meyers in > > his Effective C++ series, or from Herb Sutter's Exceptional C++, but > > after a quick look I did not find anything similar for Python... > > > Best regards. > > I agree with Rick. "Core Python Programming" by Chun is pretty good. > However, Lutz's "Programming Python" is also very good and has a few > big example programs to walk through. You might also find the Python > Cookbooks handy. > > There's also "Python Power!" by Matt Telles, which is more of a > reference book although not quite as dry as "Python Essential > Reference" was. > > Mike The Python Cookbook - printed version - I've read it - is a very good book on the lines of what you're looking for, IMO. If you go by its title, it might not sound like a book in the Effective Series (I've read Effective C++ too and agree that its excellent), but it actually is something quite like Effective C++, since its contributors include many very good Python developers, including Alex Martelli, David Ascher, Tim Peters, Raymond Hettinger, to name just a few. Though the explicit goal of the book is not to be a book about idiomatic Python, the point is that it ends up being a lot like that, since most of the contributors write idiomatic Python. For example, one idiom that's mentioned a lot in the book, is about one of Python's greatest strengths - "smooth signature-based polymorphism" - with good examples to substantiate it. Though not a book, you may also find the Python articles by David Mertz on IBM developerWorks very useful. Go to http://www.ibm.com/developerworks and search for either "Charming Python" - the name of his Python column there - or his name - to get the articles. HTH Vasudev ------- Vasudev Ram Biz site: http://www.dancingbison.com Quick PDF creation toolkit (in Python, open source): http://www.dancingbison.com/products.html From bruno.42.desthuilliers at websiteburo.invalid Wed Jun 4 07:50:42 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 04 Jun 2008 13:50:42 +0200 Subject: new to python, looking for streams clues In-Reply-To: <58bb3360-daa5-4cf8-a3bf-93044ed189b1@x41g2000hsb.googlegroups.com> References: <58bb3360-daa5-4cf8-a3bf-93044ed189b1@x41g2000hsb.googlegroups.com> Message-ID: <48468161$0$26543$426a34cc@news.free.fr> Thierry a ?crit : > Hello peoples, > > As I said, I'm new to python, and particularly to XML generation in > python. > Using the 4suite XML package, I have been able to produce XML, but > only directly to STDOUT. > > Refering to the 4suite markupWriter refrence, the class needs a stream > to output the generated XML, and if none is specified, it's the STDOUT > stream that is used. > > What I would like, would be to store the generated XML into a python > object which implement the stream interface to be able to transform it > via XSLT if needed (it's in a web based project). > > But, I've read the python doc for the last 12 hours without finding > anything about an existing object that implements that interface. > Am I missing something, or should I really create that object myself ? > > I mean, I just need something that I can write into and read > thereafter. > It should already exists, no ? It does, it's named StringIO (or cStringIO for the faster C implementation), and it's part of the standard lib. AFAICT, it should fit your needs. From hackame at gmail.com Sun Jun 22 16:42:48 2008 From: hackame at gmail.com (AngelinaCarmen) Date: Sun, 22 Jun 2008 13:42:48 -0700 (PDT) Subject: Learning Python in a group References: Message-ID: <8cc4de66-0139-4052-95dc-1b9c7d9ad97a@a1g2000hsb.googlegroups.com> I would like to be a part of this if enough people are able to join up, I nabbed python less than two days ago, and have been trying to absorb as much as I can out of websites and practice projects. Learning this together would speed up the process slightly because we could share tips and such, all in all, I'm up for it. From __peter__ at web.de Fri Jun 13 13:05:57 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Jun 2008 19:05:57 +0200 Subject: struct unpack issue References: Message-ID: Ping Zhao wrote: > I am writing a small program to decode MS bitmap image. When I use > statements as follow, it works fine: > > header['sig'] = str(struct.unpack('2s', self.__read(src, 2))[0]) > header['len'] = int(struct.unpack('1i', self.__read(src, 4))[0]) > > However, when I tried to rewrite them in short: > > header = struct.unpack('2s1i', self.__read(src, 6)) > > The Python interpreter in my Linux box came up with an error: > > ... > header = struct.unpack('2s1i', self.__read(src, 6)) > File "/usr/lib/python2.5/struct.py", line 87, in unpack > return o.unpack(s) > struct.error: unpack requires a string argument of length 8 > > It was weired that the required argument length increased to 8. Any idea > on this? I am using a 32bit pentium-m and the picture file was stored in > little-edian format. Try specifying byte order and alignment: >>> struct.unpack("2s1i", "123456") Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/struct.py", line 87, in unpack return o.unpack(s) struct.error: unpack requires a string argument of length 8 >>> struct.unpack("=2s1i", "123456") ('12', 909456435) See the second table on http://docs.python.org/lib/module-struct.html for the options you have. Peter From ram.rachum at gmail.com Wed Jun 18 15:00:23 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Wed, 18 Jun 2008 12:00:23 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> <4857AA74.2080205@electrooptical.net> Message-ID: <612892c1-0703-48bb-9351-dc855bd3c1de@2g2000hsn.googlegroups.com> On Jun 18, 7:12?pm, Peter Pearson wrote: > On Tue, 17 Jun 2008 08:13:40 -0400, Phil Hobbs wrote: > > ram.rac... at gmail.com wrote: > [snip] > >> I have a physical system set up in which a body is supposed to > >> accelerate and to get very close to lightspeed, while never really > >> attaining it. After approx. 680 seconds, Python gets stuck and tells > >> me the object has passed lightspeed. I put the same equations in > >> Mathematica, again I get the same mistake around 680 seconds. So I > >> think, I have a problem with my model! Then I pump up the > >> WorkingPrecision in Mathematica to about 10. I run the same equations > >> again, and it works! At least for the first 10,000 seconds, the object > >> does not pass lightspeed. > >> I concluded that I need Python to work at a higher precision. > [snip] > > You need to change your representation. ?Try redoing the algebra using > > (c-v) as the independent variable, and calculate that. > > Or represent the velocity as c*tanh(b), where b is the independent > variable. ?If memory serves, this is the representation in which > constant acceleration corresponds to db/dt = constant. > > -- > To email me, substitute nowhere->spamcop, invalid->net. See my comment to Brodie. From johnjsal at gmailNOSPAM.com Sun Jun 15 22:53:19 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sun, 15 Jun 2008 22:53:19 -0400 Subject: Combining music or video files? Message-ID: <4855d5a5$0$11609$607ed4bc@cv.net> Before I try this and destroy my computer :) I just wanted to see if this would even work at all. Is it possible to read a binary file such as an mp3 or an avi, put its contents into a new file, then read another such file and append its contents to this same new file as well, thereby making, for example, a single long video instead of two smaller ones? Thanks. From alexnbryan at gmail.com Fri Jun 27 19:36:57 2008 From: alexnbryan at gmail.com (Alexnb) Date: Fri, 27 Jun 2008 16:36:57 -0700 (PDT) Subject: using urllib2 In-Reply-To: References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> Message-ID: <18165692.post@talk.nabble.com> I have read that multiple times. It is hard to understand but it did help a little. But I found a bit of a work-around for now which is not what I ultimately want. However, even when I can get to the page I want lets say, "Http://dictionary.reference.com/browse/cheese", I look on firebug, and extension and see the definition in javascript,
    1.the curd of milk separated from the whey and >> prepared >> >> in >> >> >> many ways as a food.
    the problem being that if I use code like this to get the html of that page in python: response = urllib2.urlopen("the webiste....") html = response.read() print html then, I get a bunch of stuff, but it doesn't show me the code with the table that the definition is in. So I am asking how do I access this javascript. Also, if someone could point me to a better reference than the last one, because that really doesn't tell me much, whether it be a book or anything. Jeff McNeil-2 wrote: > > I stumbled across this a while back: > http://www.voidspace.org.uk/python/articles/urllib2.shtml. > It covers quite a bit. The urllib2 module is pretty straightforward > once you've used it a few times. Some of the class naming and whatnot > takes a bit of getting used to (I found that to be the most confusing > bit). > > On Jun 27, 1:41 pm, Alexnb wrote: >> Okay, I tried to follow that, and it is kinda hard. But since you >> obviously >> know what you are doing, where did you learn this? Or where can I learn >> this? >> >> >> >> >> >> Maric Michaud wrote: >> >> > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit : >> >> I have never used the urllib or the urllib2. I really have looked >> online >> >> for help on this issue, and mailing lists, but I can't figure out my >> >> problem because people haven't been helping me, which is why I am >> here! >> >> :]. >> >> Okay, so basically I want to be able to submit a word to >> dictionary.com >> >> and >> >> then get the definitions. However, to start off learning urllib2, I >> just >> >> want to do a simple google search. Before you get mad, what I have >> found >> >> on >> >> urllib2 hasn't helped me. Anyway, How would you go about doing this. >> No, >> >> I >> >> did not post the html, but I mean if you want, right click on your >> >> browser >> >> and hit view source of the google homepage. Basically what I want to >> know >> >> is how to submit the values(the search term) and then search for that >> >> value. Heres what I know: >> >> >> import urllib2 >> >> response = urllib2.urlopen("http://www.google.com/") >> >> html = response.read() >> >> print html >> >> >> Now I know that all this does is print the source, but thats about all >> I >> >> know. I know it may be a lot to ask to have someone show/help me, but >> I >> >> really would appreciate it. >> >> > This example is for google, of course using pygoogle is easier in this >> > case, >> > but this is a valid example for the general case : >> >> >>>>[207]: import urllib, urllib2 >> >> > You need to trick the server with an imaginary User-Agent. >> >> >>>>[208]: def google_search(terms) : >> > return >> urllib2.urlopen(urllib2.Request("http://www.google.com/search?" >> > + >> > urllib.urlencode({'hl':'fr', 'q':terms}), >> > headers={'User-Agent':'MyNav >> > 1.0 >> > (compatible; MSIE 6.0; Linux'}) >> > ).read() >> > .....: >> >> >>>>[212]: res = google_search("python & co") >> >> > Now you got the whole html response, you'll have to parse it to recover >> > datas, >> > a quick & dirty try on google response page : >> >> >>>>[213]: import re >> >> >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

    > class=r>.*?

    ', >> > res) ] >> > ...[229]: >> > ['Python Gallery', >> > 'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des Monty >> ...', >> > 'Re: os x, panther, python & co: msg#00041', >> > 'Re: os x, panther, python & co: msg#00040', >> > 'Cardiff Web Site Design, Professional web site design services ...', >> > 'Python Properties', >> > 'Frees < Programs < Python < Bin-Co', >> > 'Torb: an interface between Tcl and CORBA', >> > 'Royal Python Morphs', >> > 'Python & Co'] >> >> > -- >> > _____________ >> >> > Maric Michaud >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> -- >> View this message in >> context:http://www.nabble.com/using-urllib2-tp18150669p18160312.html >> Sent from the Python - python-list mailing list archive at Nabble.com. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/using-urllib2-tp18150669p18165692.html Sent from the Python - python-list mailing list archive at Nabble.com. From tjreedy at udel.edu Sat Jun 28 20:06:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 28 Jun 2008 20:06:41 -0400 Subject: Testing for Null? In-Reply-To: <268ac2770806281605n663670e9n29620f344ed66e4d@mail.gmail.com> References: <268ac2770806281605n663670e9n29620f344ed66e4d@mail.gmail.com> Message-ID: Alex Bryan wrote: > I am having a problem with a list value that is empty. I have a list of > definitions called mainList. the 5th value in the list doesn't have > anything in it. In this case, the values are definitions; also, in this > case just the word cheese is defined. Here is my output to the console: > > > 5. a sprawling,weedy plant having small lavender or white flowers and > round, flat, segmented fruits thought to resemble little wheels of cheese. > 6. > 7. an ingot or billet made into a convex, circular form by blows at the > ends. > > > I've made it so where the numbers, the period, and two spaces follow > that, then the definition. However, as you can see in 6, there is > nothing. Here is the code to print all this: > > n=0 > > for x in mainList: > if mainList[n] == "": > print "Error on this definition" > else: > print str(n+1)+". "+str(mainList[n]) > n=n+1 > > Now the two "" is where I need to figure out if it is empty. What is up > right now doesn't work; or at least doesn't give the desired result. So > I need to know how to write the if statement to make it work. This > should be simple, but I just don't know how to do it, never had this > problem before. My guess is that your 'empty' value is something like ' ', which is not equal to ''. Change str to repr and see better what item 6 is. From patelgopal at gmail.com Sun Jun 29 04:39:11 2008 From: patelgopal at gmail.com (gops) Date: Sun, 29 Jun 2008 01:39:11 -0700 (PDT) Subject: What is "@" used for ? Message-ID: Hi. I am noob in python. while reading some source code I came across , this funny thing called @ in some function , def administrator(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): user = users.get_current_user() if not user: if self.request.method == "GET": self.redirect(users.create_login_url(self.request.uri)) return raise web.HTTPError(403) elif not users.is_current_user_admin(): raise web.HTTPError(403) else: return method(self, *args, **kwargs) return wrapper now what is that "@" used for ? I tried to google , but it just omits the "@" and not at all useful for me(funny!! :D) It will be enough if you can just tell me some link where i can look for it.. Thank you in advance. :D From saptarshi.guha at gmail.com Mon Jun 9 15:44:47 2008 From: saptarshi.guha at gmail.com (sapsi) Date: Mon, 9 Jun 2008 12:44:47 -0700 (PDT) Subject: Numpy, adding a row to a matrix Message-ID: <359ea846-786a-4267-9068-d61ff4c58974@x35g2000hsb.googlegroups.com> Hello, I have a numpy array (2 rows 3 colums) import numpy a=numpy.array( [ [1,2,3] , [3,3,1] ]) I wish to add a row, this is how i do it s=a.shape numpy.resize(a,s[0]+1,s[1]) a[s[0]]=new row vector. Q: Is this a costly operation? What happens if i have to it several (and unknown) number of times? is there a simpler way to add a row? Thank you in advance Saptarshi From d3vvnull at gmail.com Thu Jun 19 10:24:53 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Thu, 19 Jun 2008 09:24:53 -0500 Subject: python/ruby question.. In-Reply-To: <485A3173.3080908@mattnordhoff.com> References: <3b017f08-2d42-4c65-9003-19ffc606234d@l64g2000hse.googlegroups.com> <485A3173.3080908@mattnordhoff.com> Message-ID: <170543c70806190724m4cbd67f0t7cd01956f36212d0@mail.gmail.com> The commands module might help you out as well. import commands as c output = c.getoutput('testruby.rb') On Thu, Jun 19, 2008 at 5:14 AM, Matt Nordhoff wrote: > Mensanator wrote: > > On Jun 18, 10:33?pm, "bruce" wrote: > >> hi... > >> > >> can someone point me to where/how i would go about calling a ruby app > from a > >> python app, and having the python app being able to get a returned value > >> from the ruby script. > >> > >> something like > >> > >> test.py > >> ?a = os.exec(testruby.rb) > >> > >> testruby.py > >> ?foo = 9 > >> ?return foo > >> > >> i know this doesn't work... but i've been searching for hours on this > with > >> no luck.... (and yeah, i'm relatively new to both ruby/python!!) > >> > >> thanks > > > > Well, I don't know anything about Ruby, but here's > > how I do it for C programs (compiled to .exe that > > write to stdout). > > > > > > import os > > factor_program = 'factor! -d200 ' # factor!.exe from MIRACL > > > > n = > > > '50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749' > > > > # call external program and capture stdout > > the_output = os.popen(factor_program+n).readlines() > > > > print 'n: %s' % n > > for i in the_output: > > print i, > > > > You're supposed to use the subprocess module. > > In this case, something like: > > import subprocess > factor_program = ['factor!', '-d200'] > > ... > > p = subprocess.Popen(factor_program + [n], stdout=subprocess.PIPE) > p.wait() # wait for it to finish; not sure how necessary it is > the_output = p.stdout.readlines() > > See subprocess's documentation [1], which includes guides on replacing > os.popen* and other functions with it. > > [1] > -- > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From omer at no-log.org Tue Jun 24 06:45:35 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Tue, 24 Jun 2008 12:45:35 +0200 Subject: sending executable data over network.. In-Reply-To: <19ac19520806232359r31f74c7bk9f5d47eb3540e457@mail.gmail.com> References: <19ac19520806232359r31f74c7bk9f5d47eb3540e457@mail.gmail.com> Message-ID: <200806241245.35047.omer@no-log.org> Le Tuesday 24 June 2008 08:59:40 Piyush Anonymous, vous avez ?crit?: > hi, > i wish to change the way the function definition at run time in a running > server. new function code which is to be executed is provided by a client > at different location. > i am getting it by reading a file and sending it using makefile() with > server/client connected using sockets. > > how can make the lines received in a string array as new function > definition? or should i receive it in a different way? > > is there any better way to do the entire thing? One way is to transmit the code as a string and compile it on server-side with the 'compile' builtin function. Another is to compile it on client-side and transmit the resulting code object with the marshal module but there are many restrictions on it (specially the fact that the client and server will have to run the same python version) so carefully read the docs first. I'd choose the first solution, eventually using the pickle module to avoid encoding problems. -- C?dric Lucantis From nick at craig-wood.com Mon Jun 9 16:30:49 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 09 Jun 2008 15:30:49 -0500 Subject: _POSIX_C_SOURCE References: Message-ID: Madhur wrote: > I would like to know the difference between using the > C_INCLUDE_PATH and using the -I option with compilers. How are they > different? No idea on that - I always just use -I > The problem which I am facing is that I am having a > source base which uses python. I am currently enabling compile time > option _POSIX_C_SOURCE in my Makefile. The compilaiton fails if i > include -I option to /usr/include/python2.4 > > /usr/include/python2.4/pyconfig-32.h:838:1: error: "_POSIX_C_SOURCE" > redefined > > but if i do > > export C_INCLUDE_PATH=/usr/include/python2.4 > > I do not face any compilation issues. > > I would like to know if there is anything i am missing on this. Do it in your code with #define _POSIX_C_SOURCE instead of the Makefile, and do it after the #include "Python.h" -- Nick Craig-Wood -- http://www.craig-wood.com/nick From ggpolo at gmail.com Fri Jun 20 18:20:39 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Fri, 20 Jun 2008 19:20:39 -0300 Subject: inheritance question... In-Reply-To: <587C2C9324493D4B96BD6BBCDEAC321AA95911@exchange3.valvesoftware.com> References: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> <09ec833f-7751-4991-8d09-45c200fb4c18@z72g2000hsb.googlegroups.com> <587C2C9324493D4B96BD6BBCDEAC321AA95911@exchange3.valvesoftware.com> Message-ID: On Fri, Jun 20, 2008 at 6:19 PM, Hamish McKenzie wrote: > > I have this class: > > class Vector(object): > TOL = 1e-5 > def __eq__( self, other, tolerance=TOL ): > print tolerance > > > shortened for clarity obviously. so I want to subclass this class like > so: > > class BigVector(Vector) > TOL = 100 > > > for example if I was working with large vectors which I knew would never > be very close hence the large tolerance. this doesn't work however - > the TOL class variable, while overridden in BigVector, is still using > the Vector.TOL variable in the __eq__ method. > > > which kinda makes sense to a certain degree, but how do I get the > behaviour where doing: > > BigVector().__eq__( otherVec ) No, don't do this. Just do "avector == othervector" > > > prints 100 instead of 1e-5? > > does this question make sense? not sure how clearly I'm phrasing my > question... any of you guys python experts? > > > I *could* do this, but its ugly: > > class Vector(object): > TOL = 1e-5 > def __eq__( self, other, tolerance=None ): > if tolerance is None: tolerance = self.TOL > print tolerance > class Vector(object): TOL = 1e-5 def __eq__(self, other): print self.TOL > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From garyrob at mac.com Mon Jun 23 22:12:18 2008 From: garyrob at mac.com (Gary Robinson) Date: Mon, 23 Jun 2008 22:12:18 -0400 Subject: 32-bit python memory limits? Message-ID: <20080623221218152774.85cdf772@mac.com> I'm running a Python job on OS X 10.5.3 and the Python 2.5.2 that's available as a binary download at python.org for OS X. I ran a python program tonight that ended up using much more memory than anticipated. It just kept on using more and more memory. Instead of killing it, I just watched it, using Activity Monitor. I assumed that when it had 2GB allocated it would blow up, because I thought 32-bit python could only address 2GB. But Activity Monitor reported that it had allocated 3.99GB of virtual memory before it finally blew up with malloc errors. Was my understanding of a 2GB limit wrong? I guess so! But I'm pretty sure I saw it max out at 2GB on linux... Anybody have an explanation, or is it just that my understanding of a 2GB limit was wrong? Or was it perhaps right for earlier versions, or on linux...?? Thanks for any thoughts, Gary -- Gary Robinson CTO Emergent Music, LLC personal email: garyrob at mac.com work email: grobinson at emergentmusic.com Company: http://www.emergentmusic.com Blog: http://www.garyrobinson.net From gongchangzhaojie at gmail.com Thu Jun 5 13:52:54 2008 From: gongchangzhaojie at gmail.com (Zhaojie Boulder) Date: Thu, 5 Jun 2008 11:52:54 -0600 Subject: gcc error in Mac OS X In-Reply-To: References: <12956470806041550k7e2815b4ga6823ee7967a8718@mail.gmail.com> Message-ID: <12956470806051052g2d4a53as7b644c1f26dddcfa@mail.gmail.com> Hi Tommy, When I typed which gcc,nothing happened,I checked the /usr/bin path myself and gcc was not there. In fact, the Xcode folder is at the same level with the usr folder. Is there a way you can install Xcode in the right place? I did not find such a option during the installation process of Xcode. Thanks Jie 2008/6/4 Tommy Grav : > What happens when you run > > which gcc > > Cheers > Tommy > > > On Jun 4, 2008, at 6:50 PM, Zhaojie Boulder wrote: > > Hello, >> >> I am new to Mac and used python in linux before. What I am trying to do is >> to install "Ipython" and "PyCogent" in Mac OS X. >> >> For PyCogent, after entering the package path, I typed "python setup.py >> install". The results are as follows: >> >> Didn't find Pyrex - will compile from .c files >> running install >> running build >> running build_py >> running build_ext >> building 'cogent.align._compare' extension >> gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd >> -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DMACOSX >> -I/usr/include/ffi -DENABLE_DTRACE -arch i386 -arch ppc -pipe >> -I/Users/zhaojie/Downloads/PyCogent-1.0.1/include >> -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 >> -c cogent/align/_compare.c -o >> build/temp.macosx-10.5-i386-2.5/cogent/align/_compare.o -w >> unable to execute gcc: No such file or directory >> error: command 'gcc' failed with exit status 1 >> >> After google, I installed Xcode,but it did not help. Also, the Xcode >> folder is not within "applications" folder, but a separate one parallel with >> "applications". Dragging Xcode folder into the applications folder did not >> make a difference, either. >> >> Hope someone familiar with Mac can help me out. >> >> Thank you, >> >> Jie >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From brian_vanderburg2 at yahoo.com Thu Jun 26 19:23:11 2008 From: brian_vanderburg2 at yahoo.com (Allen) Date: Thu, 26 Jun 2008 19:23:11 -0400 Subject: Adding functions to an existing instance In-Reply-To: References: <27adnS2SrIrOLv7VnZ2dnUVZ_rjinZ2d@earthlink.com> Message-ID: bruno.desthuilliers at gmail.com wrote: > On 26 juin, 17:18, Allen wrote: >> I need a way to add a method to an existing instance, but be as close as >> possible to normal instance methods. > > def set_method(obj, func, name=None): > if not name: > name = func.__name__ > setattr(obj, name, func.__get__(obj, type(obj))) > > class Toto(object): > pass > > toto = Toto() > > def titi(self): > print self > > set_method(toto, titi) > I tried that. func.__get__(obj, type(obj)) creates a bound method and then sets an attribute to that, creating a cyclic reference. toto contains a reference to the bound method, the bound method contains a reference to the instance toto. However it does eliminate the need for FunctionCaller. Instead of: return InstanceFunctionHelper.FunctionCaller(self, funcs[name]) __getattr__(...) can just do: return funcs[name].__get__(self, type(self)) to get the same behavior. All of the extra __setattr__ and __delattr__ exist so that if the attribute is set after a function is set, it will delete the function so that later deleting the attribute will not make the function visible again. Brian Vanderburg II From inhahe at gmail.com Tue Jun 24 05:55:50 2008 From: inhahe at gmail.com (inhahe) Date: Tue, 24 Jun 2008 05:55:50 -0400 Subject: How to import filenames with special characters? Message-ID: How would I import a python file whose name contains characters like .'s or !'s? Is there really _no_ way to do that? I have to use plain jane letters and numbers for everything? From vtians at gmail.com Mon Jun 9 21:14:22 2008 From: vtians at gmail.com (TT) Date: Mon, 9 Jun 2008 18:14:22 -0700 (PDT) Subject: 65K length limitation in MySQLdb? Message-ID: <4e79050f-ee50-42f0-9b84-4571faa30ee5@a32g2000prf.googlegroups.com> I'm trying to using the following code insert a long string into a MySQL table, the data type is of that column is TEXT. When the length of the content is longer than 65K, it get truncated in the database. Any idea about this? Thanks import MySQLdb import MySQLdb.cursors class MyDb: def __init__(self): self.conn = None self.cursor = None def connect(self): self.conn = MySQLdb.Connect( host='localhost', user='user', passwd='password', db='testdb',compress=1, cursorclass=MySQLdb.cursors.DictCursor) self.cursor = self.conn.cursor() def insert(self, id, content): try: self.cursor.execute("INSERT INTO `my_table`(`id`, `content`) VALUES (%s, %s);", (id, content)); except: print "Failed to insert new record" pass From pavlovevidence at gmail.com Fri Jun 20 20:25:54 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 20 Jun 2008 17:25:54 -0700 (PDT) Subject: sublassing as a verb References: Message-ID: On Jun 20, 4:34?pm, davidj411 wrote: > docs on urllib module say this about the FancyUrlOpener: > "class FancyURLopener( ...) > > FancyURLopener subclasses URLopener providing default handling > for ..." > > does that mean the FancyURLopener is a subclass of URLopener? Yes. Anthimeria is very common in English. Carl Banks From Lie.1296 at gmail.com Tue Jun 10 11:55:42 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 10 Jun 2008 08:55:42 -0700 (PDT) Subject: proposal: give delattr ability to ignore missing attribute References: <4e9122bb-eb81-460f-85cd-11e344195175@p25g2000hsf.googlegroups.com> Message-ID: On Jun 10, 10:06?pm, Gary Wilson wrote: > I would like to propose that functionality be added to delattr to > handle the case when the attribute does not exist. > > First off, getattr handles this nicely with the default parameter: > > value = getattr(obj, 'foo', False) > > instead of: > > try: > ? ? value = getattr(obj, 'foo') > except AttributeError: > ? ? value = False > > or: > > if hasattr(obj, 'foo'): > ? ? value = getattr(obj, 'foo') > else: > ? ? value = False > > And I think it makes sense to have something similar for delattr (name > the argument as you wish): > > delattr(obj, 'foo', allow_missing=True) > > instead of: > > try: > ? ? delattr(obj, 'foo') > except AttributeError: > ? ? pass > > or: > > try: > ? ? del obj.foo > except AttributeError: > ? ? pass > > or: > > if hasattr(obj, 'foo') > ? ? delattr(obj, 'foo') > > For backwards compatibility, allow_missing would default to False. > > Gary That doesn't need to be implemented internally, you could do it yourself in python. def my_delattr(obj, attr): try: delattr(obj, attr) except AttributeError: pass def my_getattr(obj, attr, default): try: return getattr(obj, attr) except AttributeError: return default From weheh at yahoo.com Sun Jun 22 16:31:20 2008 From: weheh at yahoo.com (weheh) Date: Sun, 22 Jun 2008 20:31:20 GMT Subject: binary number format ? format character %b or similar. References: Message-ID: I don't know if you found this example: http://www.daniweb.com/code/snippet285.html -- > I'm was wanting to format a positive integer in binary, > and not finding it--to my surprise--I rolled my own version. > > Is this already in python, or have I missed it somewhere? > > I have Googled around a bit, and found a few threads on > the subject, but they all seem to fizzle out. > > (e.g. : INPUT 35, OUTPUT "100011" ) From s0suk3 at gmail.com Thu Jun 5 09:06:35 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Thu, 5 Jun 2008 06:06:35 -0700 (PDT) Subject: Books for learning how to write "big" programs References: <219c77ef-dd0c-464b-bb6a-e4f3bee89eae@x41g2000hsb.googlegroups.com> Message-ID: <304580c2-bdfb-4564-8507-d742d9eaf5a8@79g2000hsk.googlegroups.com> On May 22, 12:49?pm, "Kurt Smith" wrote: > On Thu, May 22, 2008 at 10:55 AM, duli wrote: > > Hi: > > I would like recommendations forbooks(in any language, not > > necessarily C++, C, python) which have walkthroughs for developing > > a big software project ? So starting from inception, problem > > definition, design, coding and final delivery on a single theme > > or application. > > The bigger the project, the more likely it is that you'll have > documentation on how to use it (for a language or library, how to use > the features in your program) but to take the time to write up a > dead-tree book on the project's "inception, problem definition, > design, coding and final delivery" is not likely well spent. ?Anyone > who has the expertise to write such a book would probably be spending > his time working on the next phase of the project itself. > > Someone will probably respond with an amazon link to a book that does > exactly what you're asking, in which case, I will stand corrected. > But I'll be surprised. > > > > > Most of the code I have written andbooksthat I have read deal with > > toy programs and I am looking for something a bit more > > comprehensive. ?For example, maybe a complete compiler written in C++ > > for some language, or a complete web server or implementing > > .net libraries in some language (just a few examples of the scale of > > things I am interested in learning). > > It seems to me the reason toy programs are so prevalent is because > they illustrate a (few) well defined ideas in a short amount of code. > A big project, necessarily, brings together all kinds of stuff, much > of which may not interest the author at all, and so doesn't motivate > him to write a book about it. > > Compilers, web servers & .NET libraries are *widely* varying areas. > You may have interest in them all, but to significantly contribute to > any requires a fair amount of expertise and specialization. > > The best route I've found to learn how to organize & program large > scale applications is this: find a cutting edge program that interests > you and that is open source. ?Download its source, and read the code. > Diagram it. ?Map it out. ?Read the comments. ?Join the mailing list > (probably the developer's list), lurk for a while, and ask questions > about why they organized things the way they did. ?Get the overall big > picture and learn from it. ?Better yet, find out what pitfalls they > found and avoided (or fell into). ?Compare their approach & > organization with another competing project. ?This is the wonder of > open source software -- you have access to everything, and can learn > from all the expertise the developers put into their opus. > > You can learn the basics frombooks, but nothing beats analyzing a > species in the wild. I think I have lately understood what you mean, thanks to Programming Python 3rd Ed by Lutz. It doesn't teach Python itself -- the book aims to teach Python programming at an application level, but I'm starting to wonder whether that knowledge can be obtained from any book. The book goes through over 1500 pages (!) giving small- and medium-sized example programs and describing their details. Roughly after a couple of hundred pages I started to feel like all that was trivial (isn't looking at code and figuring their details what we do in our every-day programmer lifes?), and then started to feel like it was really useless. Maybe large-scale programming can only be self-thought in every day life, am I right?. From laurent.ploix at gmail.com Mon Jun 16 17:56:22 2008 From: laurent.ploix at gmail.com (=?ISO-8859-1?Q?m=E9choui?=) Date: Mon, 16 Jun 2008 14:56:22 -0700 (PDT) Subject: How to request data from a lazily-created tree structure ? References: <6bo3ifF3dj7dmU1@mid.uni-berlin.de> Message-ID: <896f8600-4183-4147-96c9-64ab5a9ad753@x41g2000hsb.googlegroups.com> On Jun 16, 11:16 pm, "Diez B. Roggisch" wrote: > m?choui schrieb: > > > > > Problem: > > > - You have tree structure (XML-like) that you don't want to create > > 100% in memory, because it just takes too long (for instance, you need > > a http request to request the information from a slow distant site). > > - But you want to be able to request data from it, such has "give me > > all nodes that are under a "//foo/bar" tree, and have a child with an > > "baz" attribute of value "zzz". > > > Question : > > > Do you have any other idea to request data from a lazily-created tree > > structure ? > > > And does it make sense to create a DOM-like structure and to use a > > generic XPath engine to request the tree ? (and does this generic > > XPath engine exist ?) > > > The idea is to have the tree structure created on the fly (we are in > > python), only when the XPath engine requests the data. Hopefully the > > XPath engine will not request all the data from the tree (if the > > request is smart enough and does not contain **, for instance). > > Generic XPath works only with a DOM(like) structure. How else would you > e.g. evaluate an expression like foo[last()]? > > So if you really need lazy evaluation, you will need to specifically > analyze the query of interest and see if it can be coded in a way that > allows to forget as much of the tree as possible, or even better not > query it. > > Diez Yes, I need to make sure my requests are properly written so that the generic XPath engine does not need all the structure in memory. There are quite a few cases where you really don't need to load everything at all. /a/b/*/c/d is an example. But even with an example like /x/z[last()]/t, you don't need to load everything under the every /x/z nodes. You just need to check for the latest one, and make sure there is a t node under it. Anyway, if I need to make requests that need all the data... that means that the need for lazy instantiation of nodes disappears, right ? From lists at cheimes.de Tue Jun 3 05:03:24 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 03 Jun 2008 11:03:24 +0200 Subject: Writing Empty folders into ZipFile In-Reply-To: References: Message-ID: otaeris at o2.pl schrieb: > Hello. > > I'm having situation writing folders structure into > a zip file. Folders contain no files. > > Is it possible to do in python ? As far as I remember the zip format it's not possible at all. Folders are created implicitly. The zip format doesn't support empty directories. Christian From shore.cloud at gmail.com Mon Jun 16 15:30:15 2008 From: shore.cloud at gmail.com (Mr Shore) Date: Mon, 16 Jun 2008 12:30:15 -0700 (PDT) Subject: vmware job vacancy! Message-ID: <3239dff8-d5b2-42d3-9b98-e5947eb65f4f@v26g2000prm.googlegroups.com> A veteran engineer from VMWare Inc., Jeffrey, is being featured on jobirn.com on Monday Jun 16, from 9am to 5pm (PST.) He will chat with applicants who are interested in job openings in VMWare. He will identify qualified candidates and directly submit qualified candidates' resumes to hiring managers. Logon to http://jobirn.com and chat with Jeff. Jobirn.com is a job-referral company. It connects job applicants with insider employees in companies. Jobirn.com believes it gives qualified candidates higher opportunities to catch the attention of the right managers. Referrers, once featured, will usually make significant amount of bonus (Employee Referral Bonus) from his own company,if the recommended candidates are hired. From Robert.Bossy at jouy.inra.fr Wed Jun 18 08:10:38 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 18 Jun 2008 14:10:38 +0200 Subject: dict order In-Reply-To: <1a7a2dc6-4acf-473d-a51c-4715ca9c7068@c19g2000prf.googlegroups.com> References: <4804032a-adef-4973-ae21-acc4ad2dce37@z72g2000hsb.googlegroups.com> <411fc353-dd54-4bbc-a72e-ddee66408313@c58g2000hsc.googlegroups.com> <1a7a2dc6-4acf-473d-a51c-4715ca9c7068@c19g2000prf.googlegroups.com> Message-ID: <4858FB3E.1060907@jouy.inra.fr> Lie wrote: >> Whoops, I think I misunderstood the question. If what you're asking >> whether two dictionary is equal (equality comparison, rather than >> sorting comparison). You could do something like this: >> Testing for equality and finding differences are trivial tasks indeed. It is the sort order I'm interested in. The meaning of the order is not really an issue, I'm rather looking for a consistent comparison function (in the __cmp__ sense) such as: if d1 > d2 and d2 > d3, then d1 > d3 I'm not sure the hashing method suggested by Albert guarantees that. Cheers From wizzardx at gmail.com Wed Jun 18 04:22:20 2008 From: wizzardx at gmail.com (David) Date: Wed, 18 Jun 2008 10:22:20 +0200 Subject: Database design questions In-Reply-To: <18c1e6480806180041s5ffaca54r39a7554734cd513c@mail.gmail.com> References: <18c1e6480806180041s5ffaca54r39a7554734cd513c@mail.gmail.com> Message-ID: <18c1e6480806180122o5fe113e3m9a1c8e0761391fbf@mail.gmail.com> > I have a few database-related questions. These aren't Python-specific > questions, but some of my apps which use (or will use) these tables > are in Python :-) Let me know if I should ask this on a different > list. Hi list. I've thought about this some more, and it is off-topic for the python list. I'm going to ask this on the postgresql users list instead. David. From dgetsman at amirehab.net Wed Jun 4 14:53:50 2008 From: dgetsman at amirehab.net (Damon Getsman) Date: Wed, 4 Jun 2008 11:53:50 -0700 (PDT) Subject: python library for passwd suitable blowfish hash generation Message-ID: I'm working on a utility that needs to be able to generate /etc/shadow suitable hashes on an OpenSuSE 10.3 system. All of the shadowed hashes are blowfish, I believe, from seeing the 'magic' $2a$10$ at the start of each of the entries. Ideally I would like to find a library that will take my string and spit out the hash in a compatible ascii form so that I could just drop it in place or prepend the $2a$10$ and drop it in, but I'm not afraid of taking the binary and trying to convert it to compatible ascii. Does anybody know of any python libraries like this? I've seen a few of the libraries so far and I'm not sure if I want to use them or not; documentation was rather lacking. I'd appreciate any input you all might be able to give on this. Thanks for your time. -Damon Getsman From phillip.oldham at gmail.com Thu Jun 12 10:27:36 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Thu, 12 Jun 2008 07:27:36 -0700 (PDT) Subject: Comments on my first script? Message-ID: <7e3a7c92-6204-46dd-8df8-90218f2fb314@26g2000hsk.googlegroups.com> I'm keen on learning python, with a heavy lean on doing things the "pythonic" way, so threw the following script together in a few hours as a first-attempt in programming python. I'd like the community's thoughts/comments on what I've done; improvements I can make, "don'ts" I should be avoiding, etc. I'm not so much bothered about the resulting data - for the moment it meets my needs. But any comment is welcome! #!/usr/bin/env python ## Open a file containing a list of domains (1 per line), ## request and parse it's whois record and push to a csv ## file. import subprocess import re src = open('./domains.txt') dest = open('./whois.csv', 'w'); sep = "|" headers = ["Domain","Registrant","Registrant's Address","Registrar","Registrant Type","Date Registered","Renewal Date","Last Updated","Name Servers"] dest.write(sep.join(headers)+"\n") def trim( txt ): x = [] for line in txt.split("\n"): if line.strip() == "": continue if line.strip().startswith('WHOIS'): continue if line.strip().startswith('>>>'): continue if line.strip().startswith('%'): continue if line.startswith("--"): return ''.join(x) x.append(" "+line) return "\n".join(x) def clean( txt ): x = [] isok = re.compile("^\s?([^:]+): ").match for line in txt.split("\n"): match = isok(line) if not match: continue x.append(line) return "\n".join(x); def clean_co_uk( rec ): rec = rec.replace('Company number:', 'Company number -') rec = rec.replace("\n\n", "\n") rec = rec.replace("\n", "") rec = rec.replace(": ", ":\n") rec = re.sub("([^(][a-zA-Z']+\s?[a-zA-Z]*:\n)", "\n\g<0>", rec) rec = rec.replace(":\n", ": ") rec = re.sub("^[ ]+\n", "", rec) return rec def clean_net( rec ): rec = rec.replace("\n\n", "\n") rec = rec.replace("\n", "") rec = rec.replace(": ", ":\n") rec = re.sub("([a-zA-Z']+\s?[a-zA-Z]*:\n)", "\n\g<0>", rec) rec = rec.replace(":\n", ": ") return rec def clean_info( rec ): x = [] for line in rec.split("\n"): x.append(re.sub("^([^:]+):", "\g<0> ", line)) return "\n".join(x) def record(domain, record): details = ['','','','','','','','',''] for k, v in record.items(): try: details[0] = domain.lower() result = { "registrant": lambda: 1, "registrant name": lambda: 1, "registrant type": lambda: 4, "registrant's address": lambda: 2, "registrant address1": lambda: 2, "registrar": lambda: 3, "sponsoring registrar": lambda: 3, "registered on": lambda: 5, "registered": lambda: 5, "domain registeration date": lambda: 5, "renewal date": lambda: 6, "last updated": lambda: 7, "domain last updated date": lambda: 7, "name servers": lambda: 8, "name server": lambda: 8, "nameservers": lambda: 8, "updated date": lambda: 7, "creation date": lambda: 5, "expiration date": lambda: 6, "domain expiration date": lambda: 6, "administrative contact": lambda: 2 }[k.lower()]() if v != '': details[result] = v except: continue dest.write(sep.join(details)+"\n") ## Loop through domains for domain in src: domain = domain.strip() if domain == '': continue rec = subprocess.Popen(["whois",domain], stdout=subprocess.PIPE).communicate()[0] if rec.startswith("No whois server") == True: continue if rec.startswith("This TLD has no whois server") == True: continue rec = trim(rec) if domain.endswith(".net"): rec = clean_net(rec) if domain.endswith(".com"): rec = clean_net(rec) if domain.endswith(".tv"): rec = clean_net(rec) if domain.endswith(".co.uk"): rec = clean_co_uk(rec) if domain.endswith(".info"): rec = clean_info(rec) rec = clean(rec) details = {} try: for line in rec.split("\n"): bits = line.split(': ') a = bits.pop(0) b = bits.pop(0) details[a.strip()] = b.strip().replace("\t", ", ") except: continue record(domain, details) ## Cleanup src.close() dest.close() From lawtonpaul at gmail.com Sun Jun 15 21:23:44 2008 From: lawtonpaul at gmail.com (takayuki) Date: Sun, 15 Jun 2008 18:23:44 -0700 (PDT) Subject: newbie question: for loop within for loop confusion Message-ID: Hi, I'm studying python via the exellent book "How to think like a python programmer" by Allen Downey. Noob question follows... animals.txt is a list of animals, each on a separate line: "aardvard, bat, cat, dog, elephant, fish, giraffe, horse, insect, jackelope" I want to loop through the list of words and print words that don't have any "avoid" letter in them. def hasnolet(avoid): fin = open('animals.txt') for line in fin: word = line.strip() for letter in avoid: if letter in word: break else: print word hasnolet('abcd') Why doesn't the function above work? It returns: dog dog dog fish fish fish fish horse horse horse horse inchworm inchworm thanks for any help. takayuki From giltay at gmail.com Wed Jun 11 09:48:03 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Wed, 11 Jun 2008 06:48:03 -0700 (PDT) Subject: Producer-consumer threading problem References: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> <5d41116a-a75f-4421-a397-cde28403d73b@a70g2000hsh.googlegroups.com> Message-ID: <3f7e7640-87bf-4c2e-a7d5-1dda7d6989f3@f63g2000hsf.googlegroups.com> > Sounds like a sentinel would work for this. The producer puts a > specific object (say, None) in the queue and the consumer checks for > this object and stops consuming when it sees it. But that seems so > obvious I suspect there's something else up. There's a decent implementation of this in the Python Cookbook, Second Edition (9.4: Working with a Thread Pool), available from Safari as a preview: http://my.safaribooksonline.com/0596007973/pythoncook2-CHP-9-SECT-4 Basically, there's a request_work function that adds (command, data) pairs to the input Queue. The command 'stop' is used to terminate each worker thread (there's the sentinel). stop_and_free_thread_pool() just puts N ('stop', None) pairs and join()s each thread. The threadpool put()s the consumed items in an output Queue; they can be retrieved concurrently using get(). You don't call join() until you want to stop producing; you can get() at any time. Geoff Gilmour-Taylor (I ended up using this recipe in my own code, but with a completely different stopping mechanism---I'm using the worker threads to control subprocesses; I want to terminate the subprocesses but keep the worker threads running---and a callback rather than an output queue.) From bsagert at gmail.com Wed Jun 18 13:37:13 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Wed, 18 Jun 2008 10:37:13 -0700 (PDT) Subject: Importing module PIL vs beautifulSoup. References: Message-ID: On Jun 18, 10:18 am, Duncan Booth wrote: > bsag... at gmail.com wrote: > > I downloaded BeautifulSoup.py from > >http://www.crummy.com/software/BeautifulSoup/and being a n00bie, I > > just placed it in my Windows c:\python25\lib\ file. When I type > > "import beautifulsoup" from the interactive prompt it works like a > > charm. This seemed too easy in retrospect. > > It might be better if you put the file in \python25\lib\site-packages\ > The same import will still work, but you probably want to avoid putting > non-core files directly in \python25\lib. > > Also, it sounds like you renamed the file: "import beautifulsoup" should > fail (the file is supposed to be called BeautifulSoup.py). If you want to > be able to install other software which has been written to use > BeautifulSoup you'll need to make sure the case of the filename is correct. > > > > > Then I downloaded the PIL (Python Imaging Library) module from > >http://www.pythonware.com/products/pil/. Instead of a simple file that > > BeautifulSoup sent me, PIL is an .exe that installed itself in c: > > \python25\lib\site-packages\PIL\. However it won't load by typing > > "import pil". > > > I know I am supposed to RTFM, but a Google search has not led to the > > holy grail that Monty Python found. I realize that PIL is a package as > > opposed to a simple script (and it does not include a readme file). > > Thanks in advance for any help. > > Did you try "import PIL"? All module and package names in Python are case > sensitive. YIKES, Python is case sensitive! I knew that, says he blushing. Now it works. Thanks Duncan. Ciao, Bill From n.emami at gmail.com Fri Jun 13 06:01:55 2008 From: n.emami at gmail.com (Nader) Date: Fri, 13 Jun 2008 03:01:55 -0700 (PDT) Subject: Checking list by using of exception References: <3bdcc52d-2432-4b28-8188-bf7c811859d1@d45g2000hsc.googlegroups.com> Message-ID: <93f7f082-627b-4da2-8a1c-4e6e9400a428@34g2000hsf.googlegroups.com> On Jun 13, 11:34 am, "Gabriel Genellina" wrote: > En Fri, 13 Jun 2008 04:37:44 -0300, Nader escribi?: > > > Hello, > > > I read some files name from a directory and then I put these name in a > > list. I will check whether it is empty or not, and I would do it with > > an exception. With if statement it is very simple: > > > If list_of_files != "" : # this can be if list_of_files != > > []: > > get the files > > elas: > > there is no file > > If it is simple, just do it! Why do you want to make things more > complicated? This would be enough: > > if list_of_files: > get_the_files(list_of_files) > else: > print "there is no file" > > (a list has a false boolean value when it is empty) > > > But with exception, I can write something as: > > > try: > > list_of_files != [] > > get the files > > except ValueError: > > Print " there is no file" > > > What can the first statement be inside 'try' if I don't want to use if > > statement? > > If you insist on using an exception (and assuming list_of_files is > actually a list, not a string or other kind of sequence): > > try: > list_of_files[0] > except IndexError: > ...no files... > > This way you're checking that list_of_files contains at least one element. > But I would not reccomend it. > > -- > Gabriel Genellina I would accept your suggestion in raltion of checking a list whether it is empty or not with "if" statement. It is more expressive and clear. But In this case I would learn more about the "try .... except" exception. Nader From cmpython at gmail.com Mon Jun 9 21:23:15 2008 From: cmpython at gmail.com (CM) Date: Mon, 9 Jun 2008 18:23:15 -0700 (PDT) Subject: Write to file and see content on screen References: <5b2e915f-9fc5-4acc-b49e-d1b90d00bda0@59g2000hsb.googlegroups.com> Message-ID: On Jun 9, 9:01 pm, lama... at verizon.net wrote: > Hello all, > > New user to python. I can write to a file, however, I would like to > do both...whatever I do on the screen, I'd like to write it to a file. > > any pointers on where I can find this info. > > thanks, There is probably some smart way to do this that I don't know, but in wxPython you could have your textbox and bind it to an EVT_TEXT event, and then in the event handler for that write the contents of the textbox to your file. This way on any change in the textbox, there would be a write to the file. But I don't know if that is practical or if the writes would keep up well. You could also have a counter and when the counter reaches x characters then do a write. Or you could set a timer and do the write every x seconds. From ethan at stoneleaf.us Wed Jun 11 13:37:44 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 11 Jun 2008 09:37:44 -0800 Subject: can't assign to literal In-Reply-To: <484feda6_2@news.tm.net.my> References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> <1a244dc4-4d10-491d-8ec7-224f3a1f0df5@m73g2000hsh.googlegroups.com> <484feda6_2@news.tm.net.my> Message-ID: <48500D68.6050406@stoneleaf.us> TheSaint wrote: > On 00:15, gioved? 12 giugno 2008 Ethan Furman wrote: > > >>I like Vim (Vi Improved) > > What about justifying text ? Do you mean indenting, or wrapping? Vim has excellent indenting support, and Python files already included that support proper indenting, syntax coloring, etc. I don't use the line-wrapping feature myself, so I have no experience with it. -- Ethan From mal at egenix.com Fri Jun 27 06:40:34 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 27 Jun 2008 12:40:34 +0200 Subject: Multiprecision arithmetic library question. In-Reply-To: References: Message-ID: <4864C3A2.7050201@egenix.com> duncan smith wrote: > Michael Press wrote: >> In article , >> Mark Wooding wrote: >> >>> Michael Press wrote: >>> >>>> I already compiled and installed the GNU multiprecision library >>>> on Mac OS X, and link to it in C programs. How do I link to the >>>> library from Python? >>> You know that Python already supports multiprecision integer arithmetic, >>> right? If you desperately want GMP, though, there's the gmpy module >>> (q.g.). >> >> No, I do not know that. Define desperate. Does Python support the >> extended Euclidean algorithm >> and other number theory functions? >> How fast does Python multiply? >> Not that the latter is particularly important, >> as C is built for speed. >> >> I've been fooling around. Ran dir(gmpy), and it does not show the full >> complement of GMP >> library functions, such as the various division >> functions. e.g. mpz_tdiv_qr. >> > > There's also > http://www.egenix.com/products/python/mxExperimental/mxNumber/. I'm not > sure how the functionality compares to GMPY. mxNumber is a implementation of number types that use GMP for the internals. It doesn't expose all APIs available in GMP and also doesn't use a 1-1 mapping. Instead, it wraps the basic types available in GMP in Python objects which can be used just like normal Python numbers. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From Lie.1296 at gmail.com Mon Jun 9 12:39:45 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 9 Jun 2008 09:39:45 -0700 (PDT) Subject: money data type References: Message-ID: On Jun 9, 10:22?pm, Stephan Diehl wrote: > Hi lazyweb, > I'm wondering, if there is a usable money data type for python available. > A quick search in pypi and google didn't convey anything, even though the > decimal data type seemed to be planned as a money data type originaly. > Thanks for any pointers > > Stephan What is it that you feel is lacking in the decimal datatype that makes you feel you require a money datatype? Decimal datatype was a general purpose fixed-point number, which is usually the behavior required for money calculation, but it's not named 'money' because this behavior isn't only useful for money calculation, so they don't name it money. From nihao at qinqin.com Sun Jun 22 14:32:36 2008 From: nihao at qinqin.com (Serve Lau) Date: Sun, 22 Jun 2008 20:32:36 +0200 Subject: -1/2 Message-ID: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> What is the expected result of -1/2 in python? From lawtonpaul at gmail.com Mon Jun 16 01:35:03 2008 From: lawtonpaul at gmail.com (takayuki) Date: Sun, 15 Jun 2008 22:35:03 -0700 (PDT) Subject: newbie question: for loop within for loop confusion References: Message-ID: Thanks to everyone for the excellent advice. Roy: I did as you suggested and could see after staring at the output for awhile what was going on. The print statements really helped to put a little light on things. Yes, I agree that "learning to fish" is the best way. John: There were two "inchworms" because "c" is in "inchworm" so it shouldn't print. Thanks for your detailed description of the for loop. The Saint: i'll check out the word = line.split() command. After much flailing about, here's a loop that is working: def hasnolet2(avoid): fin = open('animals.txt') for line in fin: word = line.strip() length = len(avoid) x = 0 noprint = 0 while length -1 >= x: if avoid[x] in word: noprint = noprint + 1 x = x + 1 if noprint == 0: print word hasnolet2('abcd') which should return: fish horse hasnolet2('abcd') From arslanburney at gmail.com Thu Jun 12 07:30:21 2008 From: arslanburney at gmail.com (arslanburney at gmail.com) Date: Thu, 12 Jun 2008 04:30:21 -0700 (PDT) Subject: Plotting Graphs using Gnuplot Message-ID: <17f71342-0cc4-4eea-b99a-668096302b8b@a70g2000hsh.googlegroups.com> Hello. Was trying to create a simple plotting function. Wasnt working however. If i write the same code without putting it inside a function it works. :S. Could some1 tell me the problem? Heres the code: # File name Plotting2 import Gnuplot def plot(original, expected, actual): if type (original) != type([]): return False else: gp = Gnuplot.Gnuplot() gp('set data style lines') # Make the plot items plot1 = Gnuplot.PlotItems.Data(original, title="Original") plot2 = Gnuplot.PlotItems.Data(expected, title="Expected") plot3 = Gnuplot.PlotItems.Data(actual, title="Acutal") return gp.plot(plot1, plot2, plot3) ---- import Plotting2 #The name of my file... Plotting2.plot( [(2,3), (3,4)], [(4,5), (5,6)], [(1,3), (4,8)] ) From sasa.bistrovic at ck.t-com.hr Thu Jun 12 11:38:34 2008 From: sasa.bistrovic at ck.t-com.hr (Saąa Bistrović) Date: Thu, 12 Jun 2008 17:38:34 +0200 Subject: FPC: Exception : Unknown Run-Time error : 210 Message-ID: Sa?a Bistrovi? Antuna Mihanvi?a 13 40000 ?akovec Croatia sasa.bistrovic at ck.t-com.hr FPC: Exception : Unknown Run-Time error : 210 Hi, I'm Sa?a from Croatia. And I have : Windows XP PRO SP3. Pentium II MMX 400MHz. 256 MB of RAM. I tried to compile fp.pas. But I get this error message : 'Running "c:\fpc\fpcbuild-2.2.0\fpcsrc\ide\fp.exe "' 'Starting value of ConsoleMode is $0000001F' 'Compiler Verison f p c b u i l d - 2 . 2 . 0 \ f p c s r c \ i d e \ f p . e x e ' + same unknown exe characters as for GBD Verison 'GBD Verison f p c b u i l d - 2 . 2 . 0 \ f p c s r c \ i d e \ f p . e x e ' + same unknown exe characters as for Compiler Verison 'Cygwin "C:\FPC\222A5D~1.0\BIN\I386-W~1\cygwin1.dll" version 1005.18.0.0' 'An unhandled exception occurred at $004A74E6' 'Exception : Unknown Run-Time error : 210' ' $004A74E6 TSWITCHES__ADDBOOLEANITEM, line 602 of c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/FPSwitch.pas' ' $004A92F4 INITSWITCHES, line 1150 of c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/FPSwitch.pas' ' $004020DF main, line 382 of c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/fp.pas' From mal at egenix.com Wed Jun 4 04:37:39 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 04 Jun 2008 10:37:39 +0200 Subject: a python phpmyadmin like program In-Reply-To: References: Message-ID: <48465453.9080605@egenix.com> On 2008-06-03 20:49, Gandalf wrote: > is their any graphic program for handling sqlite like phpmyadmin or > access in python? If you run Firefox: https://addons.mozilla.org/en-US/firefox/addon/5817 -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jun 04 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania 32 days to go :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From mathewedward at gmail.com Tue Jun 10 22:53:05 2008 From: mathewedward at gmail.com (mathewedward) Date: Tue, 10 Jun 2008 19:53:05 -0700 (PDT) Subject: Earn $5000 + /mo Just by clicking Ads :: all u need is a internet connection Message-ID: <7c0930d3-e51d-411c-87bc-fc975d58a0f8@a9g2000prl.googlegroups.com> Did you know there are sites that are willing to pay you to click Ads? Did you also know that it's FREE to sign up to them? You can earn moneyonline, right now, there are already tens of thousands of people that are paid to work at home, some are making a tidy sum just by clickingon a link. PTC's or Paid to Click Sites offer FREE Memberships so you can make cash at home right away. Some Get Paid to Click Sites evenoffer you cash in your account just for signing up. Many PTC's we havelisted are well paying so earnings are great even if you're clickingalone. Earnings Example ? You click 10 ads per day = $0.10 ? 20 referrals click 10 ads per day = $2.00 ? Your daily earnings = $2.10 ? Your weekly earnings = $14.70 ? Your monthly earnings = $63.00 You Can Check Out The Payment Proofs at my site .. at . http://tinyurl.com/6dwknm Here are some the great resources we have prepared for You..... ? PTC Guide => http://tinyurl.com/55l6ql ? The PTC Directory => http://tinyurl.com/5qe7p7 ? Scam Alert => http://tinyurl.com/5q6vyf ? Top Rated => http://tinyurl.com/5gycuk Some Of the Top PTC Programs 07bux => http://tinyurl.com/5zwrq8 Buxear => http://tinyurl.com/5nsaku Bux.to => http://tinyurl.com/6pzzls Angelbux => http://tinyurl.com/58nlah 10Bux => http://tinyurl.com/6rezpq FoxCash => http://tinyurl.com/3oxu7k World-bux => http://tinyurl.com/3tz97z From ivan.illarionov at gmail.com Thu Jun 5 14:38:01 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 5 Jun 2008 11:38:01 -0700 (PDT) Subject: Tuples part 2 References: <6d3e6d40-63a6-40d1-8ea4-5ddf40238d8d@m44g2000hsc.googlegroups.com> <99bc30fb-532a-4c4f-9f5e-e7a18c28d2a5@z72g2000hsb.googlegroups.com> <0ecaaa47-3ad4-4f67-9d48-94d5d1951bc6@y21g2000hsf.googlegroups.com> Message-ID: On 5 ???, 21:22, George Sakkis wrote: > On Jun 5, 11:48 am, Ivan Illarionov wrote: > > > > > On 5 ???, 19:38, George Sakkis wrote: > > > > On Jun 5, 11:21 am, Ivan Illarionov wrote: > > > > > On 5 ???, 18:56, Ivan Illarionov wrote: > > > > > > On 5 ???, 18:19, "victor.hera... at gmail.com" > > > > > wrote: > > > > > > > On Jun 5, 3:49 pm, Ivan Illarionov wrote: > > > > > > > > On 5 ???, 01:57, "victor.hera... at gmail.com" > > > > > > > wrote: > > > > > > > > > Hi Everyone, > > > > > > > > > i have another question. What if i wanted to make n tuples, each with > > > > > > > > a list of coordinates. For example : > > > > > > > > > coords = list() > > > > > > > > for h in xrange(1,11,1): > > > > > > > > for i in xrange(1, 5, 1) : > > > > > > > > for j in xrange(1, 5, 1) : > > > > > > > > for k in xrange(1,2,1) : > > > > > > > > coords.append((i,j,k)) > > > > > > > > lista+str(h)= tuple coords > > > > > > > > print tuple(coords) > > > > > > > > > so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do > > > > > > > > it the way i show you above but it is not working properly. I wish you > > > > > > > > could help me with that. Thanks again, > > > > > > > >>> from itertools import repeat, izip > > > > > > > >>> coords = tuple((i,j,k) for i in xrange(1,5) for j in xrange(1,5) for k in xrange(1,2)) > > > > > > > >>> locals().update(("tuple%s" % i, coord) for i, coord in izip(xrange(1,11), repeat(coords))) > > > > > > > >>> tuple1 > > > > > > > > ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (2, 1, 1), (2, 2, 1), (2, > > > > > > > 3, 1), (2 > > > > > > > , 4, 1), (3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1), (4, 1, 1), (4, 2, > > > > > > > 1), (4, 3 > > > > > > > , 1), (4, 4, 1)) > > > > > > > > Does this help? > > > > > > > > But I don't understand why you need this? > > > > > > > > Ivan > > > > > > > Hi, > > > > > > > What i need is, for example: > > > > > > > tuple 1=((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)) > > > > > > > tuple 2=((2, 1, 1), (2, 2, 1), (2, 3, 1), (2, 4, 1)) > > > > > > > tuple 3=((3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1)) > > > > > > > and so on. Please help me and sorry for not taking the time to post my > > > > > > questions properly. > > > > > > > Victor > > > > > > Or even so: > > > > > > locals().update(("tuple_%s" % i, tuple((i,j,k) for j in range(1,5) for > > > > > k in range(1,2))) for i in range(1,5)) > > > > > > Ivan > > > > > Tried to make it readable: > > > > > def iter_coords(i): > > > > for j in xrange(1,5): > > > > for k in xrange(1,2): > > > > yield i, j, k > > > > > def iter_vars(): > > > > for i in xrange(1, 5): > > > > yield "tuple_%s" % i, tuple(iter_coords(i)) > > > > > locals().update(dict(iter_vars())) > > > > locals().update() works by accident here because it's in global scope; > > > it doesn't work within a function. > > > > Use a proper data structure, like a dict or a list, and access each > > > tuple list as 'tuples[n]' instead of 'tuple_n'. > > > > George > > > OP wanted variables and I showed him how to do this. I agree that a > > list or a dict would be better. > > > Ivan > > Generating variable names at runtime doesn't work for locals and it is > a bad solution for globals in 99.9% of the cases. It is usually more > helpful to point someone who can't even express his problem clearly to > the right direction, rather than taking his pseudocode literally and > coming up with a semi-working translation. > > George Understanding of how to create variables dynamically can be good for OP's learning curve even though it's a bad solution in this particular case. I agree that it was my mistake to not point him in the right direction. Ivan From jonathan at findmeon.com Wed Jun 11 13:17:40 2008 From: jonathan at findmeon.com (Jonathan Vanasco) Date: Wed, 11 Jun 2008 10:17:40 -0700 (PDT) Subject: question about import Message-ID: <886765d0-2be7-4a66-b838-032aebae0622@d1g2000hsg.googlegroups.com> I'm a little unclear about import / __import__ I'm exploring dynamically importing modules for a project, and ran into this behavior works as expected: app = __import__( myapp ) appModel = __import__( myapp.model ) but... appname= 'myapp' app = __import__( "%s" % appname ) appModel = __import__( "%s.model" % appname ) In the latter example, app and appModel will always seem to be imported as 'myapp' , and I've yet to find a way to address the .model namespace I know 'dynamically importing modules' is cursed upon -- and I'm likely rewriting hundreds of line of codes so I can work around this with a registration system -- however I'd like to understand why this occurs and know if what i'm trying is even possible. From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 9 04:35:16 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 09 Jun 2008 10:35:16 +0200 Subject: Q re documentation Python style In-Reply-To: References: Message-ID: <484ceaf7$0$7877$426a74cc@news.free.fr> kj a ?crit : (snip) > I think that sometimes even simple functions require a lot of > documentation. For example, I want to document a function that > takes a dictionary as argument, and this dictionary is expected to > have 5 keys. (When the number of mandatory arguments gets above > 4, I find that it's too difficult to remember their order, so I > resort to using a dictionary as the single argument.) Python supports keyword (named) arguments, so you don't have to remembed the order, ie: def func(arg1, arg2, arg3, arg4): # code here func(arg2=42, arg4="toto", arg3="truc", arg1="foo") Also, with good enough naming (perhaps one of the most difficult part of programming FWIW), you don't necessarily need an exhaustive documentation of each and every detail. (snip) > Then again, I suppose that Python's relative formal rigidity is > considered by many to be a strength. Which means that, to be > comfortable with Python, one has to learn to like this (relatively) > rigid structure... Or to learn how to hook into the system. If you want to put the doc before or after the function's body, it is not a big problem: # doc after the function's body: def func(args): # code here func.__doc__ = """ doc here ... """ # doc before the function's body: def document(doc): def _document(func): func.__doc__ = doc return func return _document @document(""" doc here and here and here etc... """) def func(): # code here I wouldn't personnaly use any of the above styles, but as far as I'm concerned, I don't write exhaustive docstrings. Good naming (somehow one of the hardest part in programming IMHO) and simplicity (small simple functions doing one thing each) already provide some part of the documentation IMHO, and code always provides the most exhaustive documentation you'll ever find !-) From arnodel at googlemail.com Sun Jun 1 03:18:23 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 01 Jun 2008 08:18:23 +0100 Subject: Bring object 'out of' Class? References: Message-ID: dave writes: > Hello, > > I'm currently on the class section of my self-taught journey and have > a question about classes: is it possible to bring a object created > inside the class definitions outside the class so it can be accessed > in the interpreter? > > For example, right now I'm working (within Allen Downey's Python > Programmer book) with creating a 'hand' of cards. I want to be able > to deal to 'x' amount of cards to 'x' amount of hands and then be able > to manipulate those hands afterwards. I'm not sure if even what I'm > asking is possible or if I'm getting ahead of myself. > > As always, thanks for all your help. My learning is greatly enhanced > with everyone's input on this board. Please feel free to > comment/critique the code... > > Here is the section of code that deals hands (but doesn't do anything > past that): > > def deal_cards(self, num_of_hands, num): > '''deals x amount of cards(num) to each hand''' > for i in range(num_of_hands): > handname = Hand('hand%d' % i) > self.deal(handname, num) > print '::::%s::::' % (handname.label), '\n', handname, '\n' > You need to use a 'return' statement: def deal_cards(self, num_of_hands, num): '''deals x amount of cards(num) to each hand''' hands = [] for i in range(num_of_hands): newhand = Hand('hand%d' % i) self.deal(newhand, num) hands.append(newhand) print '::::%s::::' % (handname.label), '\n', handname, '\n' return Hand Then you can write: >>> hands = deck.deal_cards(4, 5) # On fait une belotte? And I don't see the need of defining 'Hand' inside 'Deck'. HTH -- Arnaud From musiccomposition at gmail.com Wed Jun 25 22:49:02 2008 From: musiccomposition at gmail.com (Benjamin) Date: Wed, 25 Jun 2008 19:49:02 -0700 (PDT) Subject: Threads, GIL and re.match() performance References: Message-ID: <25be11e7-157c-4af0-be3a-fa7a6c9c3acc@m3g2000hsc.googlegroups.com> On Jun 25, 9:05?am, Mirko Dziadzka wrote: > > 1) Is there a reason for this? I think it is because the Python re library uses the Python C-API which is not threadsafe. > 2) Is the regex library not thread-safe? > 3) Is it possible, to release the GIL in re.match() to > ? ?get more performance? From sajmikins at gmail.com Mon Jun 23 00:53:28 2008 From: sajmikins at gmail.com (Simon Forman) Date: Sun, 22 Jun 2008 21:53:28 -0700 (PDT) Subject: Tkinter canvas drag/drop obstacle References: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> Message-ID: On Jun 22, 7:41?pm, Peter Pearson wrote: > On Fri, 20 Jun 2008 13:41:35 -0300, Guilherme Polo wrote: > > On Fri, Jun 20, 2008 at 1:11 PM, Peter Pearson wrote: > >> Tkinter makes it very easy to drag jpeg images around on a > >> canvas, but I would like to have a "target" change color when > >> the cursor dragging an image passes over it. ?I seem to be > >> blocked by the fact that the callbacks that might tell the > >> target that the mouse has entered it (, , > >> even ) aren't called if the mouse's button is down. > >> What am I missing? ?Have I failed to find the right Tkinter > >> document? ?Is Tkinter the wrong tool for this job? ?Thanks. > > > I believe the only way to achieve this is binding to the > > entire canvas, then checking if the x, y coords are inside the > > "target". > > Ugh. ?OK, thanks. > > -- > To email me, substitute nowhere->spamcop, invalid->net. Yep, but it's not so bad: from Tkinter import * c = Canvas() c.pack() i = c.create_oval(1, 1, 100, 100, fill='green') def cb(e): items = c.find_overlapping( e.x, e.y, e.x + 1, e.y + 1 ) if not items: return print items c.bind("", cb) mainloop() The c.find_overlapping() method returns a tuple. I believe the item ids in the tuple (if any) will be in the same order as the items Z order on the canvas, so "items[-1]" should always be the "topmost" graphic item (again, if any.) From mensanator at aol.com Mon Jun 2 15:42:12 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 2 Jun 2008 12:42:12 -0700 (PDT) Subject: Formatting Output References: <6e94b4dc-5920-447e-9971-96ec6a48b9ce@c58g2000hsc.googlegroups.com> Message-ID: <6ea2e85a-d00c-4228-98be-431205fceb7b@34g2000hsf.googlegroups.com> On Jun 2, 3:38?am, Chris wrote: > On Jun 2, 9:34?am, "victor.hera... at gmail.com" > > wrote: > > Hi, > > > i am building a little script and i want to output a series of columns > > more or less like this: > > > 1 ?5 ?6 > > 2 ?2 ?8 > > 2 ?9 ?5 > > > The matter is that i don't know in advance how many columns there will > > be. By the way, each column will be actually FLOATs, not INTs. How can > > i do this ? Any help welcome. Regards, > > > Victor > > import sys > float_list = [1.0, 5.0, 6.0, 2.0, 2.0, 8.0, 2.0, 9.0, 5.0] > num_columns = 3 > for i,item in enumerate(float_list): > ? ? sys.stdout.write('%.4f\t' % item) > ? ? if not (i+1) % num_columns: > ? ? ? ? sys.stdout.write('\n') > > Problem with this approach is it doesn't cater for instances where you > exceed the standard 80 characters for a terminal window. That wouldn't be a problem if being re-directed to a file. A bigger problem would be if his list were actually [1.0,2.0,2.0,5.0,2.0,9.0,6.0,8.0,5.0] but he still wanted it printed 1 5 6 2 2 8 2 9 5 as if he always wants 3 rows, but doesn't know how many columns it will take. In which case, he could do something like this: import sys float_list = [1.0,2.0,2.0,5.0,2.0,9.0,6.0,8.0,5.0] num_rows = 3 num_cols = divmod(len(float_list),num_rows) for r in xrange(num_rows): for c in xrange(num_cols[0]): sys.stdout.write('%.4f\t' % float_list[c*num_rows + r]) if num_cols[1]>0 and r References: Message-ID: <663744510806121546q4a425854o215bf7b473a95420@mail.gmail.com> > Hello , > following scenario > > list_current = [ "welcome", "search", "done", "result"] > list_ldap = [ "welcome", "hello"] > > result: > > list_toadd = [ "hello"] > > by words said , i want to check if list item from list_ldap exists in > list_current if not i want to add it to list_toadd. > > Thanks! > > D. list_toadd = [i for i in list_ldap if i not in list_current] seems to work. I'm sure there's a way to do it with set objects as well. -Steven From catalinfest at gmail.com Sun Jun 29 11:34:57 2008 From: catalinfest at gmail.com (catalinfest at gmail.com) Date: Sun, 29 Jun 2008 08:34:57 -0700 (PDT) Subject: gelato - nvidia and python Message-ID: <65fcd6a4-131e-4d7c-96b3-402296bf2a18@y21g2000hsf.googlegroups.com> Did somebody worked with gelato from nvidia and python? I have some C cod from books nvidia . This is : " GelatoAPI *r = GelatoAPI::CreateRenderer(); r->Camera ("main"); ... API calls through r ... r->Render ("main"); delete r; // Finished with this renderer " the code for python i create is only this : " python Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import gelato >>> from gelato import * >>> r=gelato.CreateRenderer >>> print r >>> dir(r) ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__str__'] " And I blocked here... Thank you . From socyl at 987jk.com.invalid Sat Jun 7 14:25:24 2008 From: socyl at 987jk.com.invalid (kj) Date: Sat, 7 Jun 2008 18:25:24 +0000 (UTC) Subject: How to send a POST request? References: Message-ID: Thanks to Jeff and subeen for the helpful comments and suggestions. Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From jamitwidme at gmail.com Mon Jun 30 12:55:28 2008 From: jamitwidme at gmail.com (jamitwidme at gmail.com) Date: Mon, 30 Jun 2008 09:55:28 -0700 (PDT) Subject: raw_input into Tkinter ? Message-ID: <634e2b50-45ba-4b93-89b4-0afd739adaf3@z66g2000hsc.googlegroups.com> Is there any way to type into a Tkinter frame window? I want to use raw_input() within a Tkinter frame. From kyosohma at gmail.com Tue Jun 17 14:37:09 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 17 Jun 2008 11:37:09 -0700 (PDT) Subject: text alignment References: <39d1c620-9923-46e7-999d-ed86c8b465ff@34g2000hsh.googlegroups.com> <114f3f4c-4004-488b-86c5-4bf6416e15bd@l42g2000hsc.googlegroups.com> <8d563101-53f0-41d3-a544-ee0ba1d58db5@m36g2000hse.googlegroups.com> Message-ID: <66b9d47c-2746-44de-b6cb-6e614519e15a@c65g2000hsa.googlegroups.com> On Jun 17, 12:59?pm, Gandalf wrote: > On Jun 17, 7:49?pm, Mike Driscoll wrote: > > > > > On Jun 17, 11:45?am, Gandalf wrote: > > > > On Jun 17, 6:43?pm, Gandalf wrote: > > > > > Hi every one. What is the similar python WX style property for CSS > > > >text-align? > > > > > I need this item text to start from the right direction: > > > > > aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60)) > > > > ? ? ? ? aaa.LoadPage('../../aa.html') > > > > > Thanks! > > > > *right to the left direction... > > > > And I'm using pythin 2.5 on XP (I forget to mention...) > > > The HtmlWindow widget can only display simple html. So, while you > > cannot use CSS, you should be able to use the simple html alignment > > directives. Check out the following site for pointers: > > >http://www.htmlite.com/lite008.php > > > If you want to be able to use CSS and javascript, you'll want to use > > the ActiveX_IEHtmlWindow (wx.lib.iewin) widget instead as it embeds > > Internet Explorer. > > > Mike > > well thanks it seems useful... > My question is about general items in WX and how to position them > inside an element without using CSS. It's only coincidence My item is > HtmlWindow Positioning the widgets within a container widgets (such as a wx.Window, wx.Panel or wx.Frame) is usually done with sizers. Something like this: mySizer.Add(myWidget, 0, wx.ALIGN_RIGHT) I've written a few tutorials on aligning widgets in various types of sizers. You might find them helpful. There are located here: http://www.blog.pythonlibrary.org You might also find this site useful too: http://www.zetcode.com/wxpython/layout/ Mike From kay.schluehr at gmx.net Sat Jun 7 14:37:53 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 7 Jun 2008 11:37:53 -0700 (PDT) Subject: ABC question: what is the purpose of the register() method? Message-ID: <22c53e8d-1f95-465f-932e-b0b0bbf148ba@x41g2000hsb.googlegroups.com> I was reading PEP 3119 (http://www.python.org/dev/peps/pep-3119/ ) and have done some experiments using Python 3.0a5. Now I'm somewhat puzzled about the purpose of the ABCMeta.register() method. One can use the register() method to register any class as a virtual subclass of any ABC. For example one can register `int` on `Iterable` and therefore it is a subclass which is confirmed in the issubclass check. What is that good for? This registration might even conflict with the implementation of __subclasscheck__. So one might expect that register(C) leads to an acceptance of a class as a subclass but this isnt't true if __subclasscheck__(C) rejects it. Why isn't __subclasscheck__ not sufficient? Example: -------------- class Interface(metaclass = ABCMeta): @classmethod def __subclasscheck__(cls, C): return cls.__abstractmethods__.issubset(C.__dict__) # some contract... class IAppendable(Interface): @abstractmethod def append(self, item): pass >>> issubclass(list, IAppendable) True >>> issubclass(tuple, IAppendable) False >>> IAppendable.register(int) >>> issubclass(int, IAppendable) False >>> import collections.Iterable as Iterable >>> Iterable.register(int) >>> issubclass(int, Iterable) True From hat at se-162.se.wtb.tue.nl Fri Jun 27 09:30:28 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 27 Jun 2008 15:30:28 +0200 Subject: shorten path to files References: Message-ID: On 2008-06-27, cesco wrote: > Hi, > > I need to retrieve the content of some files which are placed on a > network drive so in order to open them I need the full path to the > file. > Unfortunately some times the path is longer than 256 characters and in > Windows such a path is too long with the result that the file is not > found (though it is there). > > Is there any way around this? >From your description, it sounds like a OS problem, and not a Python problem. You may have better luck if you ask in a Win* newsgroup. Albert From rschroev_nospam_ml at fastmail.fm Fri Jun 13 06:20:27 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 13 Jun 2008 12:20:27 +0200 Subject: boolian logic In-Reply-To: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> References: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> Message-ID: marc wyburn schreef: > HI all, I'm a bit stuck with how to work out boolian logic. > > I'd like to say if A is not equal to B, C or D: > do something. > > I've tried > > if not var == A or B or C: > and various permutations but can't seem to get my head around it. I'm > pretty sure I need to know what is calulated first i.e the not or the > 'OR/AND's if var not in (A, B, C): do_something() -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From n.emami at gmail.com Wed Jun 18 05:10:57 2008 From: n.emami at gmail.com (Nader) Date: Wed, 18 Jun 2008 02:10:57 -0700 (PDT) Subject: reading from a gzip file Message-ID: <24f0b04f-1f34-41d4-9015-fe90e95819ba@m45g2000hsb.googlegroups.com> Hello, I have a gzip file and I try to read from this file withe the next statements: gunziped_file = gzip.GzipFile('gzip-file') input_file = open(gunziped_file,'r') But I get the nezt error message: Traceback (most recent call last): File "read_sfloc_files.py", line 131, in ? input_file = open(gunziped_file,'r') TypeError: coercing to Unicode: need string or buffer, instance found I think that I do some mistake. Would some body tell me what is my mistake? Nader From mnordhoff at mattnordhoff.com Thu Jun 19 06:14:11 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 19 Jun 2008 10:14:11 +0000 Subject: python/ruby question.. In-Reply-To: <3b017f08-2d42-4c65-9003-19ffc606234d@l64g2000hse.googlegroups.com> References: <3b017f08-2d42-4c65-9003-19ffc606234d@l64g2000hse.googlegroups.com> Message-ID: <485A3173.3080908@mattnordhoff.com> Mensanator wrote: > On Jun 18, 10:33?pm, "bruce" wrote: >> hi... >> >> can someone point me to where/how i would go about calling a ruby app from a >> python app, and having the python app being able to get a returned value >> from the ruby script. >> >> something like >> >> test.py >> ?a = os.exec(testruby.rb) >> >> testruby.py >> ?foo = 9 >> ?return foo >> >> i know this doesn't work... but i've been searching for hours on this with >> no luck.... (and yeah, i'm relatively new to both ruby/python!!) >> >> thanks > > Well, I don't know anything about Ruby, but here's > how I do it for C programs (compiled to .exe that > write to stdout). > > > import os > factor_program = 'factor! -d200 ' # factor!.exe from MIRACL > > n = > '50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749' > > # call external program and capture stdout > the_output = os.popen(factor_program+n).readlines() > > print 'n: %s' % n > for i in the_output: > print i, You're supposed to use the subprocess module. In this case, something like: import subprocess factor_program = ['factor!', '-d200'] ... p = subprocess.Popen(factor_program + [n], stdout=subprocess.PIPE) p.wait() # wait for it to finish; not sure how necessary it is the_output = p.stdout.readlines() See subprocess's documentation [1], which includes guides on replacing os.popen* and other functions with it. [1] -- From tjreedy at udel.edu Sun Jun 15 16:05:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 15 Jun 2008 16:05:02 -0400 Subject: randrange loops References: <6e424f2a-872d-4dd1-b28d-cf2a985895c9@j22g2000hsf.googlegroups.com> Message-ID: wrote in message news:6e424f2a-872d-4dd1-b28d-cf2a985895c9 at j22g2000hsf.googlegroups.com... | Hi, | | | I've created a method where the script defines twenty variables and | several of them should be random having a maximum and a minimum value. | | What I did was this: | | from random import randrange as rr, random | | self.tr2_vezes = self.rr(self.d_tr2_vezes[0],self.d_tr2_vezes[-1], | 1) # just an example, others are similar Are we to presume that self.rr is rr? | The minimum and maximum limits are never lower than -50 and higher | than 250 and are integer. | | Many times, not always, the problem is that the script just loops | forever and no value is chosen for the variable. | | What's happening here? What am I doing wrong? On what line does it 'loop forever'? Are you saying that the same code with same input sometimes works and sometimes does not? In any case, try to reduce it to the minumum that either always or sometimes fails. And post that. tjr From maric at aristote.info Fri Jun 27 12:36:04 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 27 Jun 2008 18:36:04 +0200 Subject: Use of the "is" statement In-Reply-To: References: Message-ID: <200806271836.05122.maric@aristote.info> Le Friday 27 June 2008 18:26:45 Christian Heimes, vous avez ?crit?: > Ask yourself if you are interested if f.tell() returns exactly the same > 0 object ("is") or a number that is equal to 0 ("=="). That said, "f.tell() == 0" and "f.tell() != 0" should be written "f.tell()" and "not f.tell()" in python. if not f.tell() : print 'at the beginning of the file" -- _____________ Maric Michaud From fc14301589 at icqmail.com Wed Jun 11 11:04:29 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Wed, 11 Jun 2008 23:04:29 +0800 Subject: catastrophic regexp, help! References: Message-ID: <484fe991_2@news.tm.net.my> On 12:20, mercoled? 11 giugno 2008 cirfu wrote: > patzln = re.compile("(\w* *)* zlatan ibrahimovic (\w* *)*") I think that I shouldn't put anything around the phrase you want to find. patzln = re.compile(r'.*(zlatan ibrahimovic){1,1}.*') this should do it for you. Unless searching into a special position. In the other hand, I'd like to understand how I can substitute a variable inside a pattern. if I do: import os, re EOL= os.linesep re_EOL= re.compile(r'[?P\s+2\t]')) for line in open('myfile','r').readlines(): print re_EOL.sub('',line) Will it remove tabs, spaces and end-of-line ? It's doing but no EOL :( -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From boris.smirnov at gmail.com Thu Jun 12 04:28:13 2008 From: boris.smirnov at gmail.com (boriq) Date: Thu, 12 Jun 2008 01:28:13 -0700 (PDT) Subject: suppress opening command window after using os.system command Message-ID: Hi, I'm using in my script command os.system('command') on Windows XP. Each time the os.system command is used, python opens an empty ms-dos command window (the black one) and then closes it. So when in one script the os.system command 50 times is used, I see 50 black windows. Is there a way of how to suppress this unnecessary command windows to be opened? thx. Boris From drobinow at gmail.com Wed Jun 11 12:42:33 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Wed, 11 Jun 2008 09:42:33 -0700 (PDT) Subject: Numpy array to gzip file References: Message-ID: <404de0ba-edd5-47ff-8b25-132aa0b5b570@c58g2000hsc.googlegroups.com> On Jun 11, 9:17 am, Sean Davis wrote: > I have a set of numpy arrays which I would like to save to a gzip > file. Here is an example without gzip: > > b=numpy.ones(1000000,dtype=numpy.uint8) > a=numpy.zeros(1000000,dtype=numpy.uint8) > fd = file('test.dat','wb') > a.tofile(fd) > b.tofile(fd) > fd.close() > > This works fine. However, this does not: > > fd = gzip.open('test.dat','wb') > a.tofile(fd) > > Traceback (most recent call last): > File "", line 1, in > IOError: first argument must be a string or open file > > In the bigger picture, I want to be able to write multiple numpy > arrays with some metadata to a binary file for very fast reading, and > these arrays are pretty compressible (strings of small integers), so I > can probably benefit in speed and file size by gzipping. > > Thanks, > Sean Use fd.write(a) The documentation says that gzip simulates most of the methods of a file object. Apparently that means it does not subclass it. numpy.tofile wants a file object Or something like that. From jgodoy at gmail.com Wed Jun 25 06:34:47 2008 From: jgodoy at gmail.com (Jorge Godoy) Date: Wed, 25 Jun 2008 07:34:47 -0300 Subject: Apache2 + Python WITHOUT mod_pytho References: <4f90e1e5-056e-4f61-866b-015a15030ebf@e39g2000hsf.googlegroups.com> Message-ID: pistacchio wrote: > Hi to all! > How can i configure apache2 so that it processes all .py files with > python _without_ using mod_python? > I'm on Ubuntu 8.4. I have no idea about how to do that in Ubuntu. Use fcgi or wsgi for your Python scripts. There should be recipes around for your distribution. -- Jorge Godoy From basti.wiesner at gmx.net Mon Jun 16 13:53:44 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Mon, 16 Jun 2008 19:53:44 +0200 Subject: bpython - fancy Python shell References: Message-ID: Wolfgang Grafen : > I couldn't get it work on Solaris (modified some lines for Python2.3). If solaris doesn't have a readline library, you might try to compile gnu readline, and recompile python (also a chance to get the current version 2.5) > One reason was that I had to download pyreadline separately > - I did than but now pyreadline requires either ironpython or > a windows installation. pyreadline is a windows-only thing. Since readline is a standard module on most unix systems and linux, there was no need to implement pyreadline for these systems. It would have been difficult anyway, since the windows console is completely different to unix consoles (which are fairly compatible to each other, a outcome of POSIX efforts). -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From steven.p.clark at gmail.com Tue Jun 10 17:46:06 2008 From: steven.p.clark at gmail.com (Steven Clark) Date: Tue, 10 Jun 2008 17:46:06 -0400 Subject: can't assign to literal In-Reply-To: References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> Message-ID: <663744510806101446r60b18458oc8335c36adb5fb79@mail.gmail.com> On Tue, Jun 10, 2008 at 5:30 PM, maehhheeyy wrote: > On Jun 10, 1:21 pm, Matimus wrote: >> On Jun 10, 12:53 pm, maehhheeyy wrote: >> >> > this is stopping my program from running properly. is there something >> > wrong in my code when that happens? >> >> yes >> >> Post your code, or at least the full error message if you want more >> details. >> >> Matt > > for 1 in oids, vals head_oids: > SyntaxError: can't assign to literal > -- > http://mail.python.org/mailman/listinfo/python-list > Wow. http://catb.org/~esr/faqs/smart-questions.html From maric at aristote.info Tue Jun 24 01:44:57 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 24 Jun 2008 07:44:57 +0200 Subject: An idiom for code generation with exec In-Reply-To: <0967da3a-1fea-401e-896d-9c099b3054ce@c58g2000hsc.googlegroups.com> References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <0967da3a-1fea-401e-896d-9c099b3054ce@c58g2000hsc.googlegroups.com> Message-ID: <200806240744.58075.maric@aristote.info> Le Tuesday 24 June 2008 07:18:47 eliben, vous avez ?crit?: > > If code generation is not the best, and I fail to see any performance > > issue that could explain such a choice, except a misunderstanding of > > what "compilation" means in python, just don't use it, use closures or > > callable instances, there are many way to achieve this. > > And while we're on the topic of what compilation means in Python, I'm > not sure I fully understand the difference between compiled (.pyc) > code and exec-ed code. Is the exec-ed code turned to bytecode too, > i.e. it will be as efficient as compile-d code ? Yes, exactly the same, cpython always interprets compiled code, when a script is executed for example, it is parsed/compiled to bytecode by the interpreter before any execution. The .pyc/pyo files are just a cache created at import time to avoid the rather time consuming parsing stage. -- _____________ Maric Michaud From rhamph at gmail.com Wed Jun 11 13:49:08 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Wed, 11 Jun 2008 10:49:08 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <6e6df35e-e641-44d9-9f56-c0732306eec2@q27g2000prf.googlegroups.com> <13db98b5-ed2e-45ef-97ec-ad3caeeed10e@j1g2000prb.googlegroups.com> <074caf4a-de1e-4290-b688-30148786952c@z72g2000hsb.googlegroups.com> <776fd3e3-7c2e-45b1-8196-7cde93e72da3@w1g2000prd.googlegroups.com> Message-ID: <98d541c3-e974-4a8c-961c-2a59f6bf32ea@v26g2000prm.googlegroups.com> On Jun 11, 7:56 am, Fuzzyman wrote: > On Jun 11, 6:56 am, Rhamphoryncus wrote: > > > > > On Jun 10, 3:41 pm, Fuzzyman wrote: > > > > On Jun 10, 2:03 am, Rhamphoryncus wrote: > > > How does that protect code like this? > > > f = open('somefile', 'w') > > # interruption here > > try: > > ... > > finally: > > ... > > How does it *not* protect you if you write this instead: > > f = None > try: > f = open('somefile', 'w') > ... > finally: > if f is not None: > ... Yeah, that should be safe, so long as the open call itself is protected. > > > The calculation is 'coarse grained' (it can call into .NET APIs that > > > can take a relatively long time to return) - so polling for exit > > > wouldn't work anyway. We also run user code and can't expect their > > > code to poll for exit conditions. > > > Do those .NET get interrupted at arbitrary points? Is this > > "untrusted" user code also audited for correctness? (Although I'd bet > > you simply document what you do and blame the user if something > > breaks.) > > We don't audit our user code - of course. We do document and assist > them as necessary. Changing to a more restrictive model still wouldn't > meet our use case and put *more* of a burden on our users. > > Our situation is not the only one. In general there are situations > where you may want to put a long running calulcation on a background > thread and you *know* that it is safe to interrupt - but Python > currently won't let you. > > > I'm not saying it can't be made to work in your specific case - it > > likely does work well for you. I'm saying it can't work *in > > general*. Stretching it out for general use turns those little cracks > > into massive canyons. A language needs a general mechanism that does > > work - such as a polite cancellation API. > > Neither *works in general* - polite cancellation *doesn't* work for > our us. That's my point - you probably want *both* for different use > cases. :-) Yeah, but mine's less icky. ;) I think the ideal for you would be a separate process. I'd also suggest a restricted VM only in a thread, but that probably wouldn't work for those long-running .NET APIs. Now, if those long- running .NET APIs did polite cancellation, then you could combine that with a restricted VM to get what you need. I think what bothers me is, even if those external APIs support polite cancellation properly, your forced interruptions will bleed over and mess them up. There needs to be a way of containing it better. Writing them in another language (as C is used for most of Python's builtins today) isn't a reasonable requirement. From bborcic at gmail.com Mon Jun 23 05:39:44 2008 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 23 Jun 2008 11:39:44 +0200 Subject: listcomprehension, add elements? In-Reply-To: <510c6f38-24f8-431e-9b37-c70ed91b3ee2@z24g2000prf.googlegroups.com> References: <13452c64-ef91-49a2-bb73-7f33c088660e@d45g2000hsc.googlegroups.com> <7dc3d1d6-12d7-4a9e-ac7a-91406610e106@d19g2000prm.googlegroups.com> <510c6f38-24f8-431e-9b37-c70ed91b3ee2@z24g2000prf.googlegroups.com> Message-ID: John Machin wrote: > > Instead of sum(a + b for a, b in zip(foo, bar)) > why not use sum(foo) + sum(bar) > ? or even sum(foo+bar) as may apply. Cheers, BB From ptmcg at austin.rr.com Mon Jun 16 23:23:13 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 16 Jun 2008 20:23:13 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <4856e80c$0$30401$9b622d9e@news.freenet.de> Message-ID: <97b828d8-e64c-47db-8b8e-d403e8076756@x35g2000hsb.googlegroups.com> On Jun 16, 5:24?pm, "Martin v. L?wis" wrote: > > ? ? ``odict.byindex(index)`` > > > ? ? ? ? Index-based lookup is supported by ``byindex()`` which returns > > ? ? ? ? the key/value pair for an index, that is, the "position" of a > > ? ? ? ? key in the ordered dict. ?0 is the first key/value pair, -1 > > ? ? ? ? the last. > > > ? ? ? ? >>> d.byindex(2) > > ? ? ? ? ('foo', 'bar') > > For this API, I think it's important to make some performance > guarantees. It seems fairly difficult to make byindex O(1), and > simultaneously also make insertion/deletion better than O(n). > > IOW, the PEP should somehow specify which operations are efficient, > and which ones aren't. > > Regards, > Martin My guess is that the two main memory allocate/deallocate cases are 1) appending a new item to the end, and 2) GC'ing the entire data structure. I would optimize these 2 at the expense of all others. -- Paul From luislupe at gmail.com Sun Jun 15 17:59:17 2008 From: luislupe at gmail.com (luislupe at gmail.com) Date: Sun, 15 Jun 2008 14:59:17 -0700 (PDT) Subject: randrange loops References: <6e424f2a-872d-4dd1-b28d-cf2a985895c9@j22g2000hsf.googlegroups.com> Message-ID: <2ac304b0-cfac-4571-95b7-66bea1a22794@l42g2000hsc.googlegroups.com> On 15 Jun, 21:05, "Terry Reedy" wrote: > wrote in message > > news:6e424f2a-872d-4dd1-b28d-cf2a985895c9 at j22g2000hsf.googlegroups.com... > | Hi, > | > | > | I've created a method where the script defines twenty variables and > | several of them should be random having a maximum and a minimum value. > | > | What I did was this: > | > | from random import randrange as rr, random > | > | self.tr2_vezes = self.rr(self.d_tr2_vezes[0],self.d_tr2_vezes[-1], > | 1) # just an example, others are similar > > Are we to presume that self.rr is rr? > > | The minimum and maximum limits are never lower than -50 and higher > | than 250 and are integer. > | > | Many times, not always, the problem is that the script just loops > | forever and no value is chosen for the variable. > | > | What's happening here? What am I doing wrong? > > On what line does it 'loop forever'? > Are you saying that the same code with same input sometimes works and > sometimes does not? In any case, try to reduce it to the minumum that > either always or sometimes fails. And post that. > > tjr I tried to reproduce the error in a small script. Python's error message always returned this kind of error: Traceback (most recent call last): File "individuo.py", line 584, in ind.criarAleatorio() File "individuo.py", line 247, in criarAleatorio self.criarTr2_vezes() File "individuo.py", line 185, in criarTr2_vezes self.tr2_vezes = self.rr(self.d_tr2_vezes[0],self.d_tr2_vezes[-1], 1) File "/usr/lib/python2.5/random.py", line 158, in randrange istart = int(start) KeyboardInterrupt I got mislead by this. The loop was about a while statement that compared values from two of the random variables. It was a '>=' and it should be a '>'. Thank you for your messages. Luis From tdahsu at gmail.com Fri Jun 13 12:29:01 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Fri, 13 Jun 2008 09:29:01 -0700 (PDT) Subject: Iterate creating variables? References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> <6bfhj5F3b47fmU1@mid.uni-berlin.de> <6bfj7bF3c3npoU1@mid.uni-berlin.de> Message-ID: <417fa772-1d72-478c-b088-b062f415250c@f36g2000hsa.googlegroups.com> On Jun 13, 12:19?pm, Calvin Spealman wrote: > On Jun 13, 2008, at 11:56 AM, tda... at gmail.com wrote: > > > > > On Jun 13, 11:48 am, "Diez B. Roggisch" wrote: > >> tda... at gmail.com schrieb: > > >>> On Jun 13, 11:21 am, "Diez B. Roggisch" wrote: > >>>> tda... at gmail.com schrieb: > > >>>>> I have twenty-five checkboxes I need to create (don't ask): > >>>>> self.checkbox1 = ... > >>>>> self.checkbox2 = ... > >>>>> . > >>>>> . > >>>>> . > >>>>> self.checkbox25 = ... > >>>>> Right now, my code has 25 lines in it, one for each checkbox, ? > >>>>> since > >>>>> these are all variables. > >>>>> Is there a way to write a loop so that I can have fewer lines ? > >>>>> of code > >>>>> but still keep the variables? > >>>>> I've tried: > >>>>> for o in xrange(25): > >>>>> ? ? self.checkbox[o] = ... > >>>>> which didn't work, and > >>>>> for o in xrange(25): > >>>>> ? ? self.checkbox[''%d'%(o)] = ... > >>>>> which also didn't work. > >>>>> Both give the error message: "Attribute error: Main.App has no > >>>>> attribute "checkbox"", which clearly indicates that I'm not ? > >>>>> keeping > >>>>> the "variability" aspect I want. > >>>>> Is there a way? > >>>> Keep either a list or dictionary around. Like this: > > >>>> checkboxes = [] > > >>>> for o in xrange(25): > >>>> ? ? ?checkboxes.append(....create a checkbox...) > > >>>> self.checkboxes = checkboxes > > >>>> Diez > > >>> I don't understand... how do I then complete the assignment ? > >>> statement? > > >>> If I have: > > >>> self.checkbox1 = xrc.XRCCTRL(self.panel01, 'Checkbox1') > >>> . > >>> . > >>> . > >>> self.checkbox25 = xrc.XRCCTRL(self.panel01, 'Checkbox25') > > >>> using your method, wouldn't I still need to figure out my original > >>> question? > > >>> If I have a list of checkboxes, then I'll have: > > >>> checkboxes = [checkbox1, checkbox2 ... checkbox25] > > >>> in which case I'd still need to figure out how to get the ? > >>> variable at > >>> the end of checkbox to do the rest of the "=" statement. > > >> I don't fully understand that. But if your code is uniform and looks > >> like the above, it appears that > > >> for o in xrange(25): > >> ? ? ?checkboxes.append(xrc.XRCCTRL(self.panel01, 'Checkbox%i' % o)) > > >> is the way to go. > > >> Diez > > > Thank you, this is much closer to where I need to be... > > > The issue is (and this is the part that you don't know, because I > > didn't tell you!) is that I later need to call methods on > > "self.checkbox1", for instance: > > > self.checkbox1.GetValue() > > self.checkbox[1].GetValue() is only two more characters and more ? > readable, because it expresses that you have this list of checkboxes, ? > where as "self.checkbox1" could be an odd name and all on its own, no ? > others at all, etc. > > Variable variable names are a good thing to avoid. Thats why we have ? > containers. > > > > > to determine if the box is checked or not. > > > I should have included that piece in the initial problem description; > > my apologies. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I don't think I'm being clear enough. Thanks to everyone for their help. From robin at alldunn.com Wed Jun 25 16:00:16 2008 From: robin at alldunn.com (Robin Dunn) Date: Wed, 25 Jun 2008 13:00:16 -0700 Subject: [wxpython-users] ANN: wxPython 2.8.8.0 In-Reply-To: <771741b20806251251m2345486ek7121533bdddae778@mail.gmail.com> References: <48629A74.2030109@alldunn.com> <771741b20806251251m2345486ek7121533bdddae778@mail.gmail.com> Message-ID: <4862A3D0.6010600@alldunn.com> Mario Lacunza wrote: > Hello Robin, > > Are available repos for Ubuntu Hardy?? Not yet. I hope to get set up for a Hardy build in the next few days, but you may be able to use the gutsy packages in the meantime. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From dan at catfolks.net Tue Jun 3 14:38:09 2008 From: dan at catfolks.net (Daniel Mahoney) Date: Tue, 03 Jun 2008 13:38:09 -0500 Subject: Handling some isolated iso-8859-1 characters Message-ID: I'm working on an app that's processing Usenet messages. I'm making a connection to my NNTP feed and grabbing the headers for the groups I'm interested in, saving the info to disk, and doing some post-processing. I'm finding a few bizarre characters and I'm not sure how to handle them pythonically. One of the lines I'm finding this problem with contains: 137050 Cleo and I have an anouncement! "Mlle. =?iso-8859-1?Q?Ana=EFs?=" Sun, 21 Nov 2004 16:21:50 -0500 4478 69 Xref: sn-us rec.pets.cats.community:137050 The interesting patch is the string that reads "=?iso-8859-1?Q?Ana=EFs?=". An HTML rendering of what this string should look would be "Anaïs". What I'm doing now is a brute-force substitution from the version in the file to the HTML version. That's ugly. What's a better way to translate that string? Or is my problem that I'm grabbing the headers from the NNTP server incorrectly? From deets at nospam.web.de Thu Jun 12 10:02:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 12 Jun 2008 16:02:19 +0200 Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> Message-ID: <6bcokhF3b2mo7U1@mid.uni-berlin.de> Mark wrote: > Hi all, > > I have a scenario where I have a list like this: > > User Score > 1 0 > 1 1 > 1 5 > 2 3 > 2 1 > 3 2 > 4 3 > 4 3 > 4 2 > > And I need to add up the score for each user to get something like > this: > > User Score > 1 6 > 2 4 > 3 2 > 4 8 > > Is this possible? If so, how can I do it? I've tried looping through > the arrays and not had much luck so far. > > Any help much appreciated, Show us your efforts in code so far. Especially what the actual data looks like. Then we can suggest a solution. Diez From google at mrabarnett.plus.com Wed Jun 11 04:32:52 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 11 Jun 2008 01:32:52 -0700 (PDT) Subject: can't assign to literal References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> Message-ID: <1a244dc4-4d10-491d-8ec7-224f3a1f0df5@m73g2000hsh.googlegroups.com> On Jun 10, 10:57 pm, "Steven Clark" wrote: > > for 1 in oids, vals head_oids: > > SyntaxError: can't assign to literal > > -- > > 1 is a literal, you can't assign it to something. Are you trying to > use it as a variable name? Slightly OT, but is there an editor that can display digits in a different colour to letters? From none at this.time Mon Jun 2 10:48:10 2008 From: none at this.time (The Pythonista) Date: Mon, 02 Jun 2008 10:48:10 -0400 Subject: Greetings, fellow Pythonistas! Message-ID: <13328$4844082a$30292@news.teranews.com> Hello, all! This post is to announce a new Python-oriented blog. See my .sig for the URL. I also have a question: is there any "official" method for getting listed on Planet Python? Thanks! A fellow Pythonista -- code.py: A blog about life, the universe, and Python http://pythonista.wordpress.com ** Posted from http://www.teranews.com ** From spectrumdt at gmail.com Wed Jun 4 12:12:18 2008 From: spectrumdt at gmail.com (spectrumdt at gmail.com) Date: Wed, 4 Jun 2008 09:12:18 -0700 (PDT) Subject: Extending Python with C: Can I specify another C compiler? Message-ID: <625c63a6-8f71-48db-9f6a-e3f43b487472@56g2000hsm.googlegroups.com> Hello. I am trying to extend my Python program with some C code. This thread is sort of a follow-up to another thread of mine, linked below. I don't know what the conventions are in this newsgroup about creating new threads vs. staying in existing ones, but I figured I'd rather make a new one with a title pertaining to my current problem. http://groups.google.com/group/comp.lang.python/browse_thread/thread/d60449f4db19f731# Anyway, my question is this: When compiling my C code to include in Python, using a Python script with the function distutils.core.setup... can I choose which C compiler to use? On my system it defaults to gcc, but I would like to use mpicc instead (C compiler for MPI, Message Passing Interface). Can I do this? My system, in case it matters, is Fedora Linux. Thanks in advance. From martin at v.loewis.de Tue Jun 17 01:33:55 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 17 Jun 2008 07:33:55 +0200 Subject: Python GC does not work as it should be In-Reply-To: References: Message-ID: <48574cc3$0$9714$9b622d9e@news.freenet.de> > Yes I did my job, i had mention it before. but an application would not > consist mine only, it could be incorporate your c extension module(s), and > others, means problem could be from my side, yours, or others. Though > forcing to reset the state would not mean fixing the real problem, but > making sure the GC would always try to do its job is important as python > itself used as an integrator engine no matter whether it succeed or not. Python does not support the Microsoft structured exceptions at all, and there is nothing that can be done about it. There are many many many places in the that would work incorrectly if a structured exception occurred, including many which lead to significant memory leaks or completely block the interpreter (as it won't return the GIL. That it can also happen in GC is just a tiny detail of the problem. If you think you absolutely need to have that work, just change the code and use a modified Python DLL. Regards, Martin From metalkeys404 at gmail.com Thu Jun 26 13:07:36 2008 From: metalkeys404 at gmail.com (Ampedesign) Date: Thu, 26 Jun 2008 10:07:36 -0700 (PDT) Subject: I Need A Placeholder References: Message-ID: <8c4665a8-7f47-4657-8621-38aafc0ea4d7@q24g2000prf.googlegroups.com> On Jun 26, 10:06?am, Daniel Mahoney wrote: > On Thu, 26 Jun 2008 10:03:47 -0700, Ampedesign wrote: > > I'm trying to build a try/except case, and I want to have the except > > function like such: > > > try: > > ? ? ? # Do some code here > > ? ? ? var = 1 ? ? ? ? # For example > > except: > > ? ? ? #Do nothing here > > > The only problem is if I leave a comment only in the except block, I > > get an error back saying that the except block is not properly > > formatted, since it has no content other than a comment. > > > So if anyone could suggest some code to put there as a placeholder > > that would be wonderful. > > "pass" would work fine. > > try: > ? ? ?# Do something that can throw an exception > except: > ? ? ?pass Thanks. That will work perfectly. From lawtonpaul at gmail.com Mon Jun 16 20:55:10 2008 From: lawtonpaul at gmail.com (takayuki) Date: Mon, 16 Jun 2008 17:55:10 -0700 (PDT) Subject: newbie question: for loop within for loop confusion References: <7504caa1-7941-4166-a46c-fd192cbf0d01@i76g2000hsf.googlegroups.com> Message-ID: <2b1a834f-d7d8-4a55-8e3e-65f7add59460@v1g2000pra.googlegroups.com> On Jun 17, 6:34 am, Thomas Hill wrote: > On Jun 15, 6:23 pm, takayuki wrote: > > > def hasnolet(avoid): > > fin = open('animals.txt') > > for line in fin: > > word = line.strip() > > for letter in avoid: > > if letter in word: > > break > > else: > > print word > > You're using the split command correctly, but you're not filtering > correctly. Consider this: > > ---begin--- > fin = open('animals.txt') > "\n".join(["%s" % line for line in fin if len(line.strip('abcd')) == > len(line)]) > ----end---- > > Let's go slow. > > "\n".join([...]) > > 1. Take everything that is in the following list, and print each one > with a carriage return appended to it. > > "\n".join(["%s" % line for line in fin ...]) > > 2. For each line in fin, create a string that only consists of what > currently in the line variable, using string substitution. > > "\n".join(["%s" % line for line in fin if len(line.strip('abcd')) == > len(line)]) > > 3. Only do #2 if the length of the line after stripping out the > unnecessary characters is the same length as the line originally. This > way we filter out the lines we don't want. If we wanted the lines that > have been filtered, we can change "==" to "!=" or "<=". > > Now, I read "Dive Into Python" first, which through these early on in > the book. If your eyes cross looking at this, write it down and read > it again after you get a little farther into the book you're reading Thomas, thanks for the reply. I'm early on in my python adventure so I'm not there yet on the strip command nuances. I'm reading "How to think like a python programmer" first. It's great. Then "Learning python". I've read parts of Dive into Python and will work through it fully when I'm a little farther along. takayuki From pcdhSpamMeSenseless at electrooptical.net Tue Jun 17 08:13:40 2008 From: pcdhSpamMeSenseless at electrooptical.net (Phil Hobbs) Date: Tue, 17 Jun 2008 08:13:40 -0400 Subject: 32 bit or 64 bit? In-Reply-To: <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> Message-ID: <4857AA74.2080205@electrooptical.net> ram.rachum at gmail.com wrote: > On Jun 15, 7:43 pm, Peter Otten <__pete... at web.de> wrote: >> ram.rac... at gmail.com wrote: >>> On Jun 15, 6:58 pm, Christian Meesters wrote: >>>>> I do need speed. Is there an option? >>>> Mind telling us what you *actually* want to achieve? (What do you want to >>>> calculate?) >>>> Christian >>> Physical simulations of objects with near-lightspeed velocity. >> How did you determine that standard python floats are not good enough? > > I have a physical system set up in which a body is supposed to > accelerate and to get very close to lightspeed, while never really > attaining it. After approx. 680 seconds, Python gets stuck and tells > me the object has passed lightspeed. I put the same equations in > Mathematica, again I get the same mistake around 680 seconds. So I > think, I have a problem with my model! Then I pump up the > WorkingPrecision in Mathematica to about 10. I run the same equations > again, and it works! At least for the first 10,000 seconds, the object > does not pass lightspeed. > I concluded that I need Python to work at a higher precision. > >> Everything beyond that is unlikely to be supported by the hardware and will >> therefore introduce a speed penalty. >> > > I have thought of that as well. However I have no choice. I must do > these calculations. If you know of any way that is supported by the > hardware, it will be terrific, but for now the slower things will have > to do. You need to change your representation. Try redoing the algebra using (c-v) as the independent variable, and calculate that. Cheers, Phil Hobbs From gherron at islandtraining.com Thu Jun 26 13:07:46 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 26 Jun 2008 10:07:46 -0700 Subject: I Need A Placeholder In-Reply-To: References: Message-ID: <4863CCE2.10801@islandtraining.com> Ampedesign wrote: > I'm trying to build a try/except case, and I want to have the except > function like such: > > try: > # Do some code here > var = 1 # For example > except: > #Do nothing here > > try: # Do some code here var = 1 # For example except: pass Gary Herron > The only problem is if I leave a comment only in the except block, I > get an error back saying that the except block is not properly > formatted, since it has no content other than a comment. > > So if anyone could suggest some code to put there as a placeholder > that would be wonderful. > -- > http://mail.python.org/mailman/listinfo/python-list > From jason.scheirer at gmail.com Fri Jun 13 15:29:09 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Fri, 13 Jun 2008 12:29:09 -0700 (PDT) Subject: Iterate creating variables? References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> Message-ID: <6b671d56-1060-4fd4-86ca-b36a1e4c936f@m44g2000hsc.googlegroups.com> On Jun 13, 8:11?am, tda... at gmail.com wrote: > I have twenty-five checkboxes I need to create (don't ask): > > self.checkbox1 = ... > self.checkbox2 = ... > . > . > . > self.checkbox25 = ... > > Right now, my code has 25 lines in it, one for each checkbox, since > these are all variables. > > Is there a way to write a loop so that I can have fewer lines of code > but still keep the variables? > > I've tried: > > for o in xrange(25): > ? ? self.checkbox[o] = ... > > which didn't work, and > > for o in xrange(25): > ? ? self.checkbox[''%d'%(o)] = ... > > which also didn't work. > > Both give the error message: "Attribute error: Main.App has no > attribute "checkbox"", which clearly indicates that I'm not keeping > the "variability" aspect I want. > > Is there a way? > > I appreciate any and all answers! > > Thanks! for x in xrange(1, 26): setattr(self, 'checkbox_%i' % x, ...) From python at rcn.com Fri Jun 20 09:36:48 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 20 Jun 2008 06:36:48 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> Message-ID: On Jun 20, 5:03?am, eliben wrote: > I've rewritten it using a dynamically generated procedure > for each field, that does hard coded access to its data. For example: > > def get_counter(packet): > ? data = packet[2:6] > ? data.reverse() > ? return data > > This gave me a huge speedup, because each field now had its specific > function sitting in a dict that quickly extracted the field's data > from a given packet. > > Now I'm rewriting this program in Python and am wondering about the > idiomatic way to use exec (in Perl, eval() replaces both eval and exec > of Python). FWIW, when I had a similar challenge for dynamic coding, I just generated a py file and then imported it. This technique was nice because can also work with Pyrex or Psyco. Also, the code above can be simplified to: get_counter = lambda packet: packet[5:1:-1] Since function calls are expensive in python, you can also gain speed by parsing multiple fields at a time: header, timetag, counter = parse(packet) Raymond From kamhung.soh at gmail.com Tue Jun 10 00:34:01 2008 From: kamhung.soh at gmail.com (Kam-Hung Soh) Date: Tue, 10 Jun 2008 14:34:01 +1000 Subject: Separators inside a var name In-Reply-To: References: Message-ID: Rainy wrote: > I have a stylistic question. In most languages words in var. name are > separated by underscores or cap letters, resulting in var names like > var_name, VarName and varName. I don't like that very much because all > 3 ways of naming look bad and/or hard to type. From what I understand, > scheme can have variables like var-name. I'm curious about reasons > that python chose to disallow this. Another question I have is what > other languages allow this naming scheme? Were there any languages > that allowed space as a separator? What would be a practical way to > separate variables from keywords in that case? "some long variable > name", 'just a string', or maybe using 2 spaces: one var + other > var + third var ? I think being able to easy have very long names > for vars that are easy to type would be a fairly significant > advantage. I know I'm probably being too obsessive about this, but > that didn't stop me from posting. Comments? > -- > http://mail.python.org/mailman/listinfo/python-list > Groovy allows spaces in method names. See following request and thread: http://jira.codehaus.org/browse/GROOVY-2857 -- Kam-Hung Soh Software Salariman From jarausch at igpm.rwth-aachen.de Mon Jun 23 04:50:44 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Mon, 23 Jun 2008 10:50:44 +0200 Subject: [2to3] Bug converting import Message-ID: <6c96f5F3eb8hnU1@mid.dfncis.de> Hi Given the following two files in the same directory Master.py: ---------- #!/usr/bin/python import Slave Slave.main() and Slave.py: --------- def main() : print "Hello World" Invoking Master.py under python-2.5.2 works just fine. 2to3 converts these to Master.py: ---------- from . import Slave Slave.main() I have added the first line #!/usr/local/bin/python3.0 manually Slave.py: --------- def main() : print("Hello World") Now, when I invoke Master.py I get Traceback (most recent call last): File "Master.py", line 2, in from . import Slave ValueError: Attempted relative import in non-package thanks for looking into it, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From bruno.42.desthuilliers at websiteburo.invalid Wed Jun 25 11:11:47 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 25 Jun 2008 17:11:47 +0200 Subject: IDE on the level of Eclipse or DEVc++? In-Reply-To: References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> <486214ae$0$9742$426a34cc@news.free.fr> <87ej6lq02c.fsf@benfinney.id.au> Message-ID: <48626033$0$1295$426a74cc@news.free.fr> cokofreedom at gmail.com a ?crit : > On Jun 25, 12:38 pm, Jorge Godoy wrote: >> Ben Finney wrote: >>> Bruno Desthuilliers writes: >>>> If you're into clickodroms, you may want to have a look at Eric too. >>>> As far as i'm concerned, I still wait for something that would be >>>> worth dropping emacs + python-mode + ecb. >>> I'm having the most success with this combination, yes. Though ecb is >>> rather non-Emacs-like in its configuration, and seems to strongly >>> expect to be run in graphical mode, it is still very powerful. >> Heh... I'm another one that keeps trying new things but comes back to Emacs all the time. >> >> Eclipse is too heavy, NetBeans has a poor support, Eric is too "mousy"... >> >> -- >> Jorge Godoy > > How is emacs on a windows platform? err... alien ?-) From johnjsal at NOSPAMgmail.com Wed Jun 18 09:56:29 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 18 Jun 2008 09:56:29 -0400 Subject: Buffer size when receiving data through a socket? References: <20080616202135.41c407de.johnjsal@NOSPAMgmail.com> <03985958$0$8452$c3e8da3@news.astraweb.com> Message-ID: <485913ac$0$28627$c3e8da3@news.astraweb.com> "Dennis Lee Bieber" wrote in message news:vrudnYYHF6EnLcXVnZ2dnUVZ_oPinZ2d at earthlink.com... > The first if is checking for lack of interactive input -- and, as > coded, will never break out as ANY response to the > prompt will have a > newline attached. > > Try with raw_input("> ").strip() instead Well, I know the first if block works properly. Pressing just ENTER will exit the loop and close the client socket. > The second if is checking for empty receive block... And since > .recv() blocks until it has something to return (as I recall) it may not > be of use... Interesting point. I'm not sure if it works that way though. I *think* I tried sending an empty string from the server back to the client, and as expected it exited the loop and closed the client, which doesn't make sense to me, since an empty string could be perfectly valid return data. I opted to remove the second if statement and see where that takes me. :) From robert.kern at gmail.com Thu Jun 12 16:48:37 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 12 Jun 2008 15:48:37 -0500 Subject: Mapping None. Why? In-Reply-To: References: Message-ID: Paddy wrote: > On looking up map on Wikipedia there is no mention of this special > behaviour, > So my question is why? My question is why you are looking up the semantics of Python functions on Wikipedia instead of the Python documentation. I don't see any particular discussion of map() there at all. Am I missing something? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mishok13 at gmail.com Tue Jun 3 17:35:46 2008 From: mishok13 at gmail.com (Andrii V. Mishkovskyi) Date: Wed, 4 Jun 2008 00:35:46 +0300 Subject: Ideas for master's thesis In-Reply-To: References: Message-ID: <192840a00806031435r2a682079s6d83dc8e835d90a8@mail.gmail.com> 2008/6/4 Larry Bugbee : >> I would like to do something with this language, yet >> I don't know if there are any needs/science fields, that could be used >> as a basis for a thesis. > > Personally, I'd like to see *optional* data typing added to Python > perhaps along the lines of what was done in Pyrex. You declare the > data type when you know it, or when it matters, and skip it > otherwise. Your paper could analyze its pros and cons, analyze any > potential performance gains, and recommend how to implement it. Your > professor will suggest some additional questions. > > I suspect, if the type be known and declared, the interpreter could be > streamlined and quicker, you might get asserts for free, and perhaps, > Python becomes even more self-documenting. Perhaps I've missed it, > but I haven't seen a strong analytical case made for or against > optional data typing. Your paper? I think what you are talking about is already implemented in Python 3.0 as annotations. Forgive me if I missed your point. > > Larry > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Wbr, Andrii Mishkovskyi. He's got a heart of a little child, and he keeps it in a jar on his desk. From tjreedy at udel.edu Fri Jun 13 18:03:26 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 13 Jun 2008 18:03:26 -0400 Subject: why can i still able to reproduce the SimpleHTTPServer bug whichis said fixed 3 years ago? References: <4e307e0f0806130002u6795c55ejce02b71753df33ae@mail.gmail.com> Message-ID: "Gabriel Genellina" wrote in message news:op.ucokc3o6x6zn5v at gabriel2.softlabbsas.com.ar... En Fri, 13 Jun 2008 04:02:48 -0300, Leo Jay escribi?: > http://bugs.python.org/issue1097597 > > in my python 2.5.2, i still find these code in SimpleHTTPServer.py, > is that deliberate? According to http://bugs.python.org/issue839496 it should have been corrected, but apparently the patch was only applied to the 2.4 maintenance branch, not to the trunk. Both 2.5 and 2.6 have the same problem. 3.0 doesn't have this problem but probably it was fixed independently. =========================== I reopened this so it will appear on the weekly bug report, in case the original committer does not see it. From Gilles at Wed Jun 4 12:26:35 2008 From: Gilles at (nospam@nospam.com) Date: Wed, 04 Jun 2008 18:26:35 +0200 Subject: [XP] Batch-print bunch of RTF files? Message-ID: Hello, I have about two hundred individual RTF files to print from an XP host. Word 2000 doesn't seem to have this feature, so I'm looking for a way to print those RTF files from an ActivePython script. Would someone have some working code handy? Thank you. From fabiofz at gmail.com Thu Jun 19 12:11:06 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Thu, 19 Jun 2008 13:11:06 -0300 Subject: Pydev 1.3.18 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.18 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Auto-import: Groups imports when possible. * Auto-import: Doesn't bring imports for completions already in the document even if a parse is not successful. * Organize Imports (ctrl+shift+O): Suggests imports to the undefined tokens in the editor. * Import quick-fix: Icons correspondent to the element being imported. Release Highlights in Pydev: ---------------------------------------------- * Executing external programs: Using Runtime.exec(String[] cmdargs) instead of a string with the generated command (fixes problems regarding having spaces in the installation). * Organize Imports (ctrl+shift+O): Imports can be grouped. * Cygwin: sys.executable in cygwin was not returning '.exe' in the end of the executable as it should. * Additional paths for PYTHONPATH (Patch from Eric Wittmann): extension point allows plugins to contribute paths to the PYTHONPATH. * Code-completion: typing '.' won't apply the selected completion, but will still request a new one with the current contents. * Pydev Package Explorer: Problem while trying to show active editor on the pydev package explorer. What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com From gagsl-py2 at yahoo.com.ar Mon Jun 16 01:02:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 16 Jun 2008 02:02:28 -0300 Subject: A package import question References: <15e4667e0806131601r14759c54jac431a8fc531414d@mail.gmail.com> <15e4667e0806131838p7258b00by66db0fe8393ddfa5@mail.gmail.com> Message-ID: En Fri, 13 Jun 2008 22:38:24 -0300, Dan Yamins escribi?: >> Gabriel, thanks. I understood about the fact that import only loads the > first time, but didn't realize that "del" only removes the bound reference > to the object, not as I had hoped the thing from the namespace itself. > > Also, I did _try_ to use reload. however, that failed since .archive was no > longer an attribute associated with Operations: > > >>> import Operations.archive > >>> del Operations.archive > >>> reload(Operations.archive) > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'archive' I don't get *why* do you want to remove the 'archive' attribute before reloading the module. Just reload it *without* using `del` previously. > It seems unfortunately that the "del" operation on the one hand doesn't > really remove the .archive from memory but just it's bound name, but > nonetheless prevents me from reloading the object kept in memory. > > I guess I'm trying to find a clean way to remove all the attributes > associated with a module when I reload it. Is there any way to do this? > (The operation of recursively searching through the attributes of the module > and deleting those first seems to be bad since when I did that and then try > to _reload_ the module, the attributes I deleted are _not_ reloaded.) When you reload a module, new definitions for existing names replace the old objects; new names are added; old names without a new value keep the previous value. (That is, objects are *replaced* and *added* but not *removed*). Isn't it enough? Or do you actually want to be sure that old names, now unused, are no longer available? -- Gabriel Genellina From __peter__ at web.de Thu Jun 26 05:40:49 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 26 Jun 2008 11:40:49 +0200 Subject: Looping-related Memory Leak References: <94312edc-babb-4c1b-8db1-233404aa4a02@i76g2000hsf.googlegroups.com> Message-ID: Tom Davis wrote: > I am having a problem where a long-running function will cause a > memory leak / balloon for reasons I cannot figure out. Essentially, I > loop through a directory of pickled files, load them, and run some > other functions on them. In every case, each function uses only local > variables and I even made sure to use `del` on each variable at the > end of the loop. However, as the loop progresses the amount of memory > used steadily increases. > > I had a related problem before where I would loop through a very large > data-set of files and cache objects that were used to parse or > otherwise operate on different files in the data-set. Once again, > only local variables were used in the cached object's methods. After > a while it got to the point where simply running these methods on the > data took so long that I had to terminate the process (think, first > iteration .01sec, 1000th iteration 10sec). The solution I found was > to cause the cached objects to become "stale" after a certain number > of uses and be deleted and re-instantiated. Here the alleged "memory leak" is clearly the cache, and the slowdown is caused by garbage collector. The solution is to turn it off with gc.disable() during phases where your programm allocates huge amounts of objects with the intent of keeping them for a longer time. > However, in the current case, there is no caching being done at all. > Only local variables are involved. It would seem that over time > objects take up more memory even when there are no attributes being > added to them or altered. Has anyone experienced similar anomalies? > Is this behavior to be expected for some other reason? If not, is > there a common fix for it, i.e. manual GC or something? Unless you post a script demonstrating the leak I will assume you are overlooking a reference that keeps your data alive -- whether it's a true global or within a long-running function doesn't really matter. Peter From tomkur2006-takehome at yahoo.com Fri Jun 27 21:17:22 2008 From: tomkur2006-takehome at yahoo.com (tom) Date: Fri, 27 Jun 2008 18:17:22 -0700 (PDT) Subject: httplib HTTP: Logging request message Message-ID: <57053381-d73a-4099-af6b-da672b8718be@i36g2000prf.googlegroups.com> With module httplid, I can do conn.request("POST", "/target", params, headers) Now, I want to log the request message that is sent by the request method. I don't don't see a method for that task. Any suggestion? For a response, I can log the response message by using the call method. Though, I have to get rid of the extra strings "replay: " and "header: ". data = response.read() print data /***what the print call will output***/ reply: 'HTTP/1.0 204 \r\n' header: Content-Length: 0 From byte8bits at gmail.com Wed Jun 18 10:28:38 2008 From: byte8bits at gmail.com (brad) Date: Wed, 18 Jun 2008 10:28:38 -0400 Subject: Looking for lots of words in lots of files Message-ID: Just wondering if anyone has ever solved this efficiently... not looking for specific solutions tho... just ideas. I have one thousand words and one thousand files. I need to read the files to see if some of the words are in the files. I can stop reading a file once I find 10 of the words in it. It's easy for me to do this with a few dozen words, but a thousand words is too large for an RE and too inefficient to loop, etc. Any suggestions? Thanks From martin at v.loewis.de Mon Jun 16 18:24:12 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 17 Jun 2008 00:24:12 +0200 Subject: PEP 372 -- Adding an ordered directory to collections In-Reply-To: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> Message-ID: <4856e80c$0$30401$9b622d9e@news.freenet.de> > ``odict.byindex(index)`` > > Index-based lookup is supported by ``byindex()`` which returns > the key/value pair for an index, that is, the "position" of a > key in the ordered dict. 0 is the first key/value pair, -1 > the last. > > >>> d.byindex(2) > ('foo', 'bar') For this API, I think it's important to make some performance guarantees. It seems fairly difficult to make byindex O(1), and simultaneously also make insertion/deletion better than O(n). IOW, the PEP should somehow specify which operations are efficient, and which ones aren't. Regards, Martin From sjmachin at lexicon.net Sun Jun 15 18:25:57 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 15 Jun 2008 15:25:57 -0700 (PDT) Subject: Hard to understand 'eval' References: <485381e7_2@news.tm.net.my> <4854e4a7_2@news.tm.net.my> <0eSdnazUa_iJGcjVnZ2dnUVZ_jadnZ2d@earthlink.com> Message-ID: <4c82ca10-ce6e-4f04-93df-00e57fb8e1c3@g16g2000pri.googlegroups.com> On Jun 16, 7:05 am, Dennis Lee Bieber wrote: > On Sun, 15 Jun 2008 17:45:12 +0800, TheSaint > declaimed the following in comp.lang.python: > > > is it an if....elif....elif probing only the first matching case and drop the > > remaining checks? > > Unless the compile/interpret pass is very unoptimized, once a branch > has been taken, the others should be totally skipped. > Don't you mean "Unless the "compile/interpret pass is VERY VERY BROKEN", as in "omits to drop in a jump to the end of the 'if' statement after each chunk of action code"? From dyamins at gmail.com Tue Jun 17 18:21:50 2008 From: dyamins at gmail.com (Dan Yamins) Date: Tue, 17 Jun 2008 18:21:50 -0400 Subject: Execfile issue Message-ID: <15e4667e0806171521p57eb7834r80e9e25afd0e84c2@mail.gmail.com> I'm having (what I assume is) a simple problem regarding the way import and execfile interact. I apologize in advance for my naivete. Lets say I have the function: def Func1(): print dir() execfile('testfile') print dir() X and the file #file: testfile X = 3 Then, when I run Func1 , I get the output: >>> Func1() [] ['X'] Traceback (most recent call last): File "", line 1, in File "", line 5, in Func1 NameError: global name 'X' is not defined SO, I have three questions: 1) Naively, I would think that the call to "execfile" in Func1 would act as if the line was replaced with the lines of 'testfile'. But obviously not, in some way that has to do with the subtlety of the python compilation process. Can someone explain exactly what the problem is? 2) Why would something show up in the dir() call, but not be defined (e.g. like 'X' did in the second dir() call in Func1()) ? 3) Is there any way to fix this that does not involved (essentially in one way or another) importing "testfile" as a py module? I would like to avoid that scenario for a variety of reasons ... Thanks! Dan -------------- next part -------------- An HTML attachment was scrubbed... URL: From subhabrata.iisc at hotmail.com Fri Jun 27 07:22:57 2008 From: subhabrata.iisc at hotmail.com (subhabrata.iisc at hotmail.com) Date: Fri, 27 Jun 2008 04:22:57 -0700 (PDT) Subject: Question on List References: <7f03fa3f-c8fd-45a8-b4a5-d7c66982aa4a@q27g2000prf.googlegroups.com> <8131e1be-a767-42c0-9409-b7353c7466ab@y38g2000hsy.googlegroups.com> Message-ID: <60e130f4-edea-49fa-9193-7c739ae90afe@g16g2000pri.googlegroups.com> Hi Chris, I solved the problem some other way round but thanx for your suggestion, I'll review it also. Best Regards, Subhabrata. Chris wrote: > On Jun 27, 9:51?am, subhabrata.i... at hotmail.com wrote: > > Dear All, > > I am trying to write the following code: > > > > def try1(n): > > ? ? ? ? a1="God Godess Borother Sister Family" > > ? ? ? ? a2=a1.split() > > ? ? ? ? a3=raw_input("PRINT A WORD") > > ? ? ? ? a4=a1.find(a3) > > ? ? ? ? print a4 > > ? ? ? ? a5=[] > > ? ? ? ? if a4>0: > > ? ? ? ? ? ? ? ? a5=a2.index(a3) > > ? ? ? ? ? ? ? ? a6=a5+1 > > ? ? ? ? ? ? ? ? a7=a2[a6] > > ? ? ? ? ? ? ? ? print "The new word is" > > ? ? ? ? ? ? ? ? print a7 > > ? ? ? ? ? ? ? ? a8=a5.append(a7) > > ? ? ? ? ? ? ? ? print a5 > > ? ? ? ? elif a4<0: > > ? ? ? ? ? ? ? ? a11=a3 > > ? ? ? ? ? ? ? ? print "The word is not availiable in String" > > ? ? ? ? ? ? ? ? print a11 > > ? ? ? ? ? ? ? ? a6=a5.append(a11) > > ? ? ? ? ? ? ? ? print a5 > > ? ? ? ? else: > > ? ? ? ? ? ? ? ? print "Error" > > > > Now, my question is I like to see a5 or the empty list as appended > > with elements. Results I am getting is a5 giving single value like > > ['God'],['Godess']... but I like to see it as ['God','Godess'...] etc. > > Am I going wrong? > > Do I have to rethink it in some other way? > > If any one can kindly let me know. > > Best Regards, > > Subhabrata. > > First notes, the string .find() method return -1 for not found and > zero or above if the search string is present. Remember you count > from zero. Secondly, list .append() methods do not return a new list > but modify the list in place. Thirdly, the .index() method of a list > requires an integer and not a string. And lastly, indentation should > be 4 spaces not 8. > > Just doing a sloppy job on the code (and my interpretation of what you > wanted) > > def try1(n): > new_list = [] > input_string="God Godess Borother Sister Family" > while n: > user_selection=raw_input("PRINT A WORD") > if input_string.find(user_selection) > -1: > s = input_string.split() > i = [i for i,j in enumerate(s) if j == user_selection] > new_word = s[i+1] > print 'The new word is %s' % new_word > new_list.append(new_word) > print new_list > else: > print 'User selection of "%s" not in the string.' % > user_selection > new_list.append(user_selection) > print new_list > n -= 1 > > Obviously I'm going to assume that the code you posted excluded your > loop control for the "try n amount of times". What was most likely > the cause is that you loop through your structure for every attempt of > the n times but each time you reset your list when you re-create it. > > Hope that helps some. > Chris From wolfgang.grafen at ericsson.com Mon Jun 16 05:25:50 2008 From: wolfgang.grafen at ericsson.com (Wolfgang Grafen) Date: Mon, 16 Jun 2008 11:25:50 +0200 Subject: PEP 372 -- Adding an ordered directory to collections In-Reply-To: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> Message-ID: <4856319E.9050006@ericsson.com> Armin Ronacher schrieb: > Other implementations of ordered dicts in various Python projects or > standalone libraries, that inspired the API proposed here, are: > > - `odict in Babel`_ > - `OrderedDict in Django`_ > - `The odict module`_ > - `ordereddict`_ (a C implementation of the odict module) > - `StableDict`_ > - `Armin Rigo's OrderedDict`_ > > > .. _odict in Babel: http://babel.edgewall.org/browser/trunk/babel/util.py?rev=374#L178 > .. _OrderedDict in Django: > http://code.djangoproject.com/browser/django/trunk/django/utils/datastructures.py?rev=7140#L53 > .. _The odict module: http://www.voidspace.org.uk/python/odict.html > .. _ordereddict: http://www.xs4all.nl/~anthon/Python/ordereddict/ > .. _StableDict: http://pypi.python.org/pypi/StableDict/0.2 > .. _Armin Rigo's OrderedDict: http://codespeak.net/svn/user/arigo/hack/pyfuse/OrderedDict.py I want add to this list my seqdict package, maybe the first implementation of an ordered dict in Python? http://home.arcor.de/wolfgang.grafen/Python/Modules/Modules.html I have never seen a real world dictionary which wasn't in order, so I ever felt the Python dictionary was not complete. I support the idea of an ordered dictionary in Python. Best regards Wolfgang From pavlovevidence at gmail.com Sat Jun 28 19:09:40 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 28 Jun 2008 16:09:40 -0700 (PDT) Subject: Pygame, how to show window without loop? no loop=popupand close... References: <8ecb6375-356a-4e73-be21-18ffe0f5c4f2@r66g2000hsg.googlegroups.com> <4d886194-7afb-46ff-8731-52cc82ad38d5@m45g2000hsb.googlegroups.com> <062d0d88-4f22-4a50-8cf4-411b629f4fb0@m45g2000hsb.googlegroups.com> Message-ID: <433841b8-ec5e-47aa-99de-3cc7ee0b3f83@y21g2000hsf.googlegroups.com> On Jun 28, 6:49 pm, defn noob wrote: > On 28 Juni, 08:32, Carl Banks wrote: > > > On Jun 27, 10:58 pm, defn noob wrote: > > > > right. im an idiot anyway. i can just draw the lines before entering > > > the loop, problem solved... > > > Do not do that; it'll create a busy loop and use 100% of CPU. Use > > pygame.event.wait() instead. It waits for an event to occur, without > > using CPU cycles. > > > Carl Banks > > pygame.init() > screen = pygame.display.set_mode(size) > > while 1: > for event in pygame.event.get(): > if event.type == pygame.QUIT: sys.exit() > screen.fill(screencolor) > draw((500, 20), 5) > pygame.display.flip() > pygame.event.wait() > > running that i cant close the program... what must i do? create an > event at mouse click? A. pygame.event.wait is used in lieu of pygame.event.get B. RTFM. I suggested pygame.event.wait with the expectation that you would refer to the pygame documentation to learn how to use it yourself. Carl Banks From mnordhoff at mattnordhoff.com Thu Jun 19 18:37:09 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 19 Jun 2008 22:37:09 +0000 Subject: Simple Class/Variable passing question In-Reply-To: <8a0cb1c6-8b54-4123-8f94-c0e0d465a1e9@e39g2000hsf.googlegroups.com> References: <8a0cb1c6-8b54-4123-8f94-c0e0d465a1e9@e39g2000hsf.googlegroups.com> Message-ID: <485ADF95.5060000@mattnordhoff.com> monkeyboy wrote: > Hello, > > I'm new to python, and PythonCard. In the code below, I'm trying to > create a member variable (self.currValue) of the class, then just pass > it to a simple function (MainOutputRoutine) to increment it. I thought > Python "passed by reference" all variables, but the member variable > doesn't seem to be incremented. If I make the function just increment > the member variable directly, without passing it in, it works fine? > > In the code below, "self.currValue" stays at 5, and value evaluates to > 1? Any insight would be appreciated... > > > class TestModel(model.Background): > > def on_initialize(self,event): > self.currValue = 5 > > def on_startBtn_mouseClick(self, event): > self.MainOutputRoutine(self.currValue) > self.OutputRoutine(self.currValue) > > def OutputRoutine(self,value): > self.components.txtBox1.text = str(value) > > def MainOutputRoutine(self,value): > value = value + 1 That's not how Python works. When you call "self.MainOutputRoutine(self.currValue)", in that method's scope, the local name "value" points to the same object as self.currValue does. When you do "value = value + 1", the local name "value" now points to a different object. That has no bearing on self.currValue. Err, I can't find a guide here. Um, read the language spec? I dunno. However: >>> my_list = [1] >>> def function(l): ... l.append(2) >>> function(my_list) >>> my_list [1, 2] That's because function() is *mutating* the list; it's not changing what the "l" name points to. It's calling the "append" method of the list object, which changes said list object. If it were doing, say, "l = 42", that would only rebind the function's local name "l": >>> my_list = [1] >>> def function(l): ... l = 42 >>> function(my_list) >>> my_list [1] Note that strings and integers are immutable, so whenever you think you're mutating them (e.g. "s.replace('a', 'b')" or "i += 1"), you're actually getting a whole new, different object, with all that that implies. -- From jared.grubb at gmail.com Fri Jun 27 13:54:45 2008 From: jared.grubb at gmail.com (Jared Grubb) Date: Fri, 27 Jun 2008 10:54:45 -0700 Subject: Hamming Distance Message-ID: <925822270806271054j57905cf4lc4568e5e075c3ed0@mail.gmail.com> Matimus, I was surprised that "lazy" was the algorithm that won your time tests, and I saw a way to improve it even better (algorithm is O(# ones in number) rather than O(# bits in number)) def lazy2(a, b, bits=32): x = (a ^ b) & ((1 << bits) - 1) tot = 0 while x: tot += 1 x &= x-1 return tot # times on my system (run a few times just to check for sure) python -mtimeit -s"from ham import *" "test(lazy)" 10000 loops, best of 3: 121 usec per loop python -mtimeit -s"from ham import *" "test(lazy2)" 10000 loops, best of 3: 62.4 usec per loop Check my math, but I think that's correct. Here's my derivation (but it's been a while since my Boolean algebra days, so I may've made a mistake!) It sounds right, though, since subtracting one in two's complement flips the rightmost one and inverts the zeros to the right of it. So, x & (x-1) would remove the rightmost one. Right? Long Derivation: The "trick" to finding the rightmost one in a number: pos = x ^ (x-1) It has to do with how two's-complement works. In our algorithm above, we are trying to count them, so we want to flip off the bits one by one from the right. So in each loop: x = x & ~pos But, then you notice you can simplify it even more (let y=x-1) and use mult/add syntax for & and | and use X=~x and Y=~y x * ~(x ^ y) x * ~(xY+Xy) [ def of ^ ] x * (~(xY)*~(Xy)) [ DeMoires Law ] x * ( (X+y)*(x+Y) ) [ inversion] x * (X+y) * (x+Y) [ associative] (xX+xy)*(x+Y) [ distributive ] xy*(x+Y) [ xX = 0 ] xy+xyY [ distrib ] xy [yY = 0] So, x &= x-1 On 19 Jun 2008, at 17:37, Matimus wrote: On Jun 19, 4:27 pm, godavemon wrote: I need to calculate the Hamming Distance of two integers. The hamming distance is the number of bits in two integers that don't match. I thought there'd be a function in math or scipy but i haven't been able to find one. This is my function but it seems like there should be a faster way. I do this computation many times and speed up is important. def hamdist( a, b , bits = 32): def _hamdist( x, bits): if bits: return (x & 1) + _hamdist(x >> 1, bits-1) return x & 1 return _hamdist( a ^ b, bits) Another alternative would be to convert the XOR to a binary string and count the # of 1's. Which would be fastest? Are there better alternatives? Thanks! I see no good reason to use recursion for this type of thing. Here are some of my attempts: [code] from math import log def yours(a, b , bits = 32): def _hamdist( x, bits): if bits: return (x & 1) + _hamdist(x >> 1, bits-1) return x & 1 return _hamdist(a ^ b, bits) def simple(a, b, bits=32): x = a ^ b return sum((x >> i & 1) for i in xrange(bits)) def lazy(a, b, bits=32): x = (a ^ b) & ((1 << bits) - 1) tot = 0 while x: tot += x & 1 x >>= 1 return tot def fancy(a, b, bits=32): x = (a ^ b) & ((1 << bits) - 1) tot = 0 while x: tot += 1 x ^= 1 << int(log(x, 2)) return tot test_vals = ( ((0xffffffff, 0), 32), ((0,0), 0), ((1,0), 1), ((0x80000000, 0), 1), ((0x55555555, 0), 16) ) def test(f): test_vals = ( ((0xffffffff, 0), 32), # ALL ((0,0), 0), # None ((1,0), 1), # First ((0x80000000, 0), 1), # Last ((0x55555555, 0), 16), # Every Other ((0xffff, 0), 16), # First Half ((0xffff0000, 0), 16), # Last Half ) for i, (args, exp) in enumerate(test_vals): if f(*args) != exp: return 0 return 1 if __name__ == "__main__": for f in (yours, simple, lazy, fancy): if not test(f): print "%s failed"%f.__name__ [/code] The python module `timeit` is handy for testing speed: python -mtimeit -s"from hamdist import *" "test(yours)" 10000 loops, best of 3: 95.1 usec per loop python -mtimeit -s"from hamdist import *" "test(simple)" 10000 loops, best of 3: 65.3 usec per loop python -mtimeit -s"from hamdist import *" "test(lazy)" 10000 loops, best of 3: 59.8 usec per loop python -mtimeit -s"from hamdist import *" "test(fancy)" 10000 loops, best of 3: 77.2 usec per loop Even the ridiculous `fancy` version beat the recursive version. Matt -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From anandology at gmail.com Sat Jun 21 06:28:13 2008 From: anandology at gmail.com (Anand) Date: Sat, 21 Jun 2008 03:28:13 -0700 (PDT) Subject: exec with custom dict Message-ID: <3ad8d167-7436-4688-9a34-72169804f97e@x1g2000prh.googlegroups.com> Hi, I am trying to use exec with custom dict. I am trying to print the value of variable x in 2 places. It is printing it at the first place and failing at the second place. class Env(dict): def __getitem__(self, key): return self.get(key, key) code = """ print x def f(): return x """ env = Env() exec(code, env) print env['f']() Here is the output I'm getting. x Traceback (most recent call last): File "a.py", line 14, in print env['f']() File "", line 3, in f NameError: global name 'x' is not defined Can somebody explain me what is happening? -Anand From musiccomposition at gmail.com Fri Jun 27 21:57:02 2008 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 27 Jun 2008 18:57:02 -0700 (PDT) Subject: Embedded Python Import problem References: Message-ID: <63950245-6995-4eff-b77d-2c3962366844@b1g2000hsg.googlegroups.com> On Jun 27, 5:47?pm, sleek wrote: > I am having trouble with the following code: > > PyObject *module = PyImport_ImportModule(modulename); > if (module == NULL) { > > ? ? PyObject* et, *ev, *etr; > ? ? PyErr_Fetch(&et, &ev, &etr); > ? ? PyObject* traceback = PyImport_ImportModule("traceback"); > ? ? PyObject* tb = PyObject_CallMethodObjArgs(traceback, > PyString_FromString("format_exception"), et, ev, etr, NULL); This is probably failing and returning NULL; When you call PyObject_Str on NULL, you get "." > > ? ? char *message = PyString_AsString(PyObject_Str(tb)); > ? ? ... > ? ? ... > > } From jeffrey at fro.man Wed Jun 18 16:54:01 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Wed, 18 Jun 2008 13:54:01 -0700 Subject: Ternary operator alternative in Ptyhon References: <485947df$0$869$ba4acef3@news.orange.fr> Message-ID: jeremie fouche wrote: > You can also use : > self.SomeField = params.has_key("mykey") and params["mykey"] or None Have caution with this solution: it may not provide the desired result in the case where params["mykey"] is a false value, such as 0, or [] Jeffrey From jkugler at bigfoot.com Thu Jun 26 13:13:58 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Thu, 26 Jun 2008 09:13:58 -0800 Subject: I Need A Placeholder References: Message-ID: Ampedesign wrote: > I'm trying to build a try/except case, and I want to have the except > function like such: > > try: > # Do some code here > var = 1 # For example > except: > #Do nothing here > > The only problem is if I leave a comment only in the except block, I > get an error back saying that the except block is not properly > formatted, since it has no content other than a comment. > > So if anyone could suggest some code to put there as a placeholder > that would be wonderful. except: pass is the usual technique there. j From Lie.1296 at gmail.com Wed Jun 25 13:49:31 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 25 Jun 2008 10:49:31 -0700 (PDT) Subject: Question: How do I format printing in python References: Message-ID: <98d2a6fc-bcd3-44b8-bcf6-7059859683ff@c19g2000prf.googlegroups.com> On Jun 24, 12:12?am, joemacbusin... at yahoo.com wrote: > Hi All, > > How do I format printed data in python? > I could not find this in the Python Reference Manual:http://docs.python.org/ref/print.html > Nor could I find it in Matloff's great tutorial:http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf > > For example, how do I turn this: > > 512 Jun 5 2004 X11r6 > 22 Jan 17 2005 a2p > 22 Jan 17 2005 acctcom > 5374 Sep 15 2002 acledit > 5664 May 13 2004 aclget > 12020 May 13 2004 aclput > 115734 Jun 2 2004 adb > 46518 Jun 4 2004 admin > 66750 Sep 16 2002 ali > 1453 Sep 15 2002 alias > 28150 Jun 4 2004 alog > 15 May 12 2005 alstat > > into this: > > 512 ? ? ? ?Jun ? 5 ? 2004 ? ?X11r6 > 22 ? ? ? ? Jan ? 17 ?2005 ? ?a2p > 22 ? ? ? ? Jan ? 17 ?2005 ? ?acctcom > 5374 ? ? ? Sep ? 15 ?2002 ? ?acledit > 5664 ? ? ? May ? 13 ?2004 ? ?aclget > 12020 ? ? ?May ? 13 ?2004 ? ?aclput > 115734 ? ? Jun ? 2 ? 2004 ? ?adb > 46518 ? ? ?Jun ? 4 ? 2004 ? ?admin > 66750 ? ? ?Sep ? 16 ?2002 ? ?ali > 1453 ? ? ? Sep ? 15 ?2002 ? ?alias > 28150 ? ? ?Jun ? 4 ? 2004 ? ?alog > 15 ? ? ? ? May ? 12 ?2005 ? ?alstat > > Thank you There is string formatting print formatspecifier_string % data_sequence The format specifier is similar to the one used in C's printf, and data sequence may be tuple or list. Dictionary may also be used for data, but it has its own way to specify string formatting since dictionary is unordered but "indexed" by the dict key. From Lie.1296 at gmail.com Tue Jun 3 06:52:15 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 3 Jun 2008 03:52:15 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <5ea78616-e955-4ee0-8e60-a22734ec31be@79g2000hsk.googlegroups.com> Message-ID: <207cafc4-ba3a-47cb-95d6-50b2b709b84b@j33g2000pri.googlegroups.com> On May 24, 9:14?pm, Fuzzyman wrote: > On May 24, 2:58 pm, Ben Finney > wrote: > > > Sh4wn writes: > > > first, python is one of my fav languages, and i'll definitely keep > > > developing with it. But, there's 1 one thing what I -really- miss: > > > data hiding. I know member vars are private when you prefix them with > > > 2 underscores, but I hate prefixing my vars, I'd rather add a keyword > > > before it. > > > From whom are you trying to hide your attributes? > > Actually, 'data hiding', although vastly overused by the static crowd > can be a reasonable thing to want. > > For example, at Resolver Systems we expose the spreadsheet object > model to our users. It hasa public, documented, API - plus a host of > undocumented internally used methods. > > We would really *much* rather hide these, because anything our > customers start using (whether documented or not) we will probably > have to continue supporting and maintaining. > > The 'we told you not to use that' approach, when applied to paying > customers doesn't really work... all they see is that you broke their > spreadsheet code by changing your API. > > You can make members truly private by proxying, but it is a bit > ungainly. Then don't document it, or separate internal documentation (which is never to pass through the wall) and public documentation (which your users use). Nobody would (apart from your dev team and anyone told by your dev team, which means you may fire the person for "lack of discipline") know that there is such a thing and in consequence wouldn't use it. Don't tell your user not to use something, just don't tell them that it exists and they won't use it. From mccredie at gmail.com Tue Jun 17 17:03:48 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 17 Jun 2008 14:03:48 -0700 (PDT) Subject: 2d graphics - drawing a vescica piscis in Python References: <02c29cf2-5281-4c6f-966c-cb47101529ee@26g2000hsk.googlegroups.com> Message-ID: <7c4301f6-9ec4-4d40-91ea-2b0425c193b7@u36g2000prf.googlegroups.com> On Jun 17, 12:45?pm, Terrence Brannon wrote: > Hello, I have written a program to draw a vescica piscis en.wikipedia.org/wiki/Vesica_piscis> > > from turtle import * > > def main(): > ? ? setup(width=400, height=400) > > ? ? r = 50 > ? ? color("black") > ? ? circle(r) > ? ? color("white") > ? ? forward(r) > ? ? color("black") > ? ? circle(r) > ? ? x = raw_input('please enter a string:') > > if __name__ == '__main__': > ? ? main() > > ... but I would like the following: > > 1 - I dont like how the bottom of the first circle is not complete > 2 - I would like for the left circle to be filled with verticle lines > and the right circle to be filled with horizontal lines, so that the > vescica piscis is cross-hatched. > > And finally, is turtle the "best" option for what I'm doing? pyCairo > looked a bit hard to get going with, but very powerful. sping looked a > bit alpha/beta. I would just draw on the tk canvas: >>> import Tkinter as tk >>> can = tk.Canvas() >>> can.pack(fill=tk.BOTH, expand=True) >>> c1 = can.create_oval(10,10,110,110) >>> c2 = can.create_oval(60,10,170,110) You can draw cross hatching using can.create_line(...). Have fun, Matt From sri_annauni at yahoo.co.in Sat Jun 14 17:38:41 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Sun, 15 Jun 2008 03:08:41 +0530 (IST) Subject: Socket Programming Message-ID: <841331.49664.qm@web7903.mail.in.yahoo.com> Hi, Is there any way(method) to find whether the socket got closed or not?? Thanks, Srini Best Jokes, Best Friends, Best Food and more. Go to http://in.promos.yahoo.com/groups/bestofyahoo/ From sam at mitre.org Thu Jun 5 10:29:18 2008 From: sam at mitre.org (Samuel Bayer) Date: Thu, 05 Jun 2008 10:29:18 -0400 Subject: select.poll in MacOS Leopard? Message-ID: <4847F83E.80002@mitre.org> All - The Python that comes with MacOS 10.5 doesn't have select.poll. The MacOS X build from python.org does, and works fine in 10.5. Any idea why the Apple build is broken? Anybody come across this before? Thanks in advance - Sam Bayer The MITRE Corporation sam at mitre.org From tjreedy at udel.edu Thu Jun 26 18:24:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 26 Jun 2008 18:24:15 -0400 Subject: list previous or following list elements In-Reply-To: References: Message-ID: antar2 wrote: > Hello > > > Suppose I have a textfile (text1.txt) with following four words: I see seven. Just say 'list of words' > > Apple > balcony > cartridge > damned > paper > bold > typewriter > > and I want to have a python script that prints the words following the > word starting with the letter b (which would be cartridge) or > differently put, a script that prints the element following a > specified element: > > I am more experienced in Perl, and a beginner in python > > I wrote a script that - of course - does not work, that should print > the element in a list following the element that starts with a b I believe wordlist = open('words.txt','r').read().split('\n') should give you the list in Python. In any case, wordlist = ['Apple','balcony', 'cartridge', 'damned', 'paper', 'bold', 'typewriter'] for i, word in enumerate(wordlist): if word[0] == 'b': print(wordlist[i+1]) # 3.0 break #prints cartridge (in 3.0) From pavlovevidence at gmail.com Mon Jun 23 18:19:41 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 23 Jun 2008 15:19:41 -0700 (PDT) Subject: regexp: match only if previous matched? References: <95ccceb7-c628-49f8-95bc-17f3740b1b27@m3g2000hsc.googlegroups.com> Message-ID: <33df6dd4-1df3-4dbc-8740-6605ae83efef@y21g2000hsf.googlegroups.com> On Jun 23, 6:02?pm, cirfu wrote: > I need to extract prices froma html-document. > > [0-9]*\$ matches 112$ 45$ etc but also just a $. why that shouldnt > really matter and it is unlikely anyway to appear a $sign with no > price attahced to it I still want to prevent it. > > How do I avoid matching "$"? It has to be "nbr$". The answer to your question is to use a + instead of *. + matches 1 or more elements, * matches zero or more. The second point to mention is that, at least where I come from, the currency symbol comes before the number: $112 and $45 In which case your regexp should be somehting like this: \$[0-9]+ Carl Banks From sean_mcilroy at yahoo.com Sat Jun 28 16:22:21 2008 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: Sat, 28 Jun 2008 13:22:21 -0700 (PDT) Subject: tictactoe (reprise) Message-ID: <8510f91b-bbc1-4ebf-8426-d7cd376e2daa@w8g2000prd.googlegroups.com> """ AUTHOR: Sean McIlroy LANGUAGE: Python 2.5 OVERVIEW: instances of "tictactoeplayer" play optimal tictactoe SPECIALIZED TYPES: player={ex,oh}; empty={blank}; cell=player+empty; board=[cell] TYPE RELATIONS: bool(c)==True for any c in cell """ ex, oh, blank = 'X', '0', ' ' linear = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8], [2,4,6]] lines = lambda board: [[board[i] for i in x] for x in linear] mover = lambda board: board.count(ex)==board.count(oh) and ex or oh opponent = lambda player: player==ex and oh or ex makesthreat = lambda player, cells: cells.count(blank)==1 and opponent(player) not in cells numthreats = lambda player, board: len([x for x in lines(board) if makesthreat(player,x)]) haswon = lambda player, board: [player]*3 in lines(board) marked = lambda board, index: [(board[i],mover(board))[i==index] for i in range(9)] display = lambda board: '\n\n' + '\n-+-+-\n'.join(['|'.join(board[3*i: 3*(i+1)]) for i in range(3)]) + '\n\n' blankindices = lambda board: [i for i in range(9) if board[i]==blank] isfinished = lambda board: blankindices(board)==[] or [ex]*3 in lines(board) or [oh]*3 in lines(board) numownthreats = lambda board: numthreats(mover(board),board) numopponentsthreats = lambda board: numthreats(opponent(mover(board)),board) outcomevalue = lambda board: haswon(opponent(mover(board)),board) and (-1) or haswon(mover(board),board) and (+1) or 0 assessment = lambda board: [outcomevalue(board), (-1)*numopponentsthreats(board),(+1)*numownthreats(board)] value = lambda board, index: blankindices(board) in [[],[index]] and assessment(marked(board,index)) or \ min([assessment(marked(marked(board,index),i)) for i in blankindices(board)if not i==index]) blankindexvalues = lambda board: [value(board,i) for i in blankindices(board)] analogisoptimal = lambda list1, list2, optimum: [x for (i,x) in enumerate(list1) if list2[i]==optimum(list2)] optimalblankindices = lambda board: blankindices(board) and analogisoptimal(blankindices(board),blankindexvalues(board),max) optimalmoves = lambda board: [marked(board,i) for i in optimalblankindices(board)] centergrabs = lambda board: [marked(board,i) for i in [4] if i in blankindices(board)] cornergrabs = lambda board: [marked(board,i) for i in [0,2,6,8] if i in blankindices(board)] tictactoemove = lambda board: len(blankindices(board)) in [8,9] and (centergrabs(board) or cornergrabs(board))[0] or \ optimalmoves(board) and optimalmoves(board)[0] or isfinished(board) and board class tictactoeplayer: def __init__(self): globals()['mark'] = self.mark globals()['newgame'] = self.newgame globals()['turn'] = self.turn print 'ENTER mark(i) TO PLACE A MARK ON THE i-TH CELL' print '123' + '\n' + '456' + '\n' + '789' print 'ENTER newgame() TO START A NEW GAME' print 'ENTER turn() TO GIVE UP YOUR TURN' self.newgame() def mark(self,offbyoneindex): self.board = marked(self.board,offbyoneindex-1) print 'your move:' + display(self.board) self.turn() def newgame(self): self.board = [blank]*9 print 'new game:' + display(self.board) def turn(self): self.board = tictactoemove(self.board) print 'my move:' + display(self.board) From nick at craig-wood.com Wed Jun 11 04:30:57 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 11 Jun 2008 03:30:57 -0500 Subject: mysql to sqlite References: Message-ID: Gandalf wrote: > I'm trying to convert mysql database to sqlite. is their any free tool > that does that? > I can convert my mysql db to XML file through phpmyadmin, will it be > easier to convert from XML to SQlite then from Mysql? I'd probably create the sqlite tables first by editing the database schemas produced by mysqldump to make the acceptable to feed to sqlite. I would then write a script which connects to both databases at once and copies the table data across. (At least that is what I did last time I needed to do that which was from MSSQL->MySQL). You'll find that different databases have subtly different ways of doing things (eg autoincrement fields on mysql) so you'll most likely need a custom script anyway. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From gandalf at shopzeus.com Fri Jun 6 09:54:06 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 06 Jun 2008 15:54:06 +0200 Subject: How to kill a thread? In-Reply-To: <608040960806060522m32c4e6abp836684b15c98aac3@mail.gmail.com> References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <608040960806060522m32c4e6abp836684b15c98aac3@mail.gmail.com> Message-ID: <4849417E.90605@shopzeus.com> > > def run(self): > while True: > if exit_event.isSet(): > # Thread exiting > return > try: > data = q_in.get(timeout = .5) > except Queue.Empty: > continue > # ... process data > > And then in the MainThread I do exit_event.set() and wait for all > threads to exit. It's a pretty awkward solution but works. > > BTW Guys, is something like Thread.kill() planned for the future? Or > is there a reason not to have it? Python threads are cooperative. I think there was a discussion about this, about a year ago or so. The answer was that in CPython, the interpreter has this GIL. Python threads are always running on the same processor, but they are not "native". There are operating system functions to kill a thread but you must not use them because it can crash the interpreter. Python MUST clean up object reference counts, manage memory etc. The OS function would kill the thread in a way so that it would be impossible to fee up memory, and also the interpreter can be left in bad state. I'm not sure about the details, but the short answer is that it is not planned. Many programmers said that you have to write cooperative threads anyway. Killing threads forcedly is not a good idea in any language. I hope others will correct me if I'm wrong. Best, Laszlo From akineko at gmail.com Thu Jun 26 21:00:18 2008 From: akineko at gmail.com (akineko) Date: Thu, 26 Jun 2008 18:00:18 -0700 (PDT) Subject: What happened to _tkinter.so? Message-ID: <38a292f9-d127-48cd-8e06-62ce7ab6d62f@u6g2000prc.googlegroups.com> Hello Python developers, I have noticed something curious while I was investigating a problem with the PyInstaller. In my environment, the PyInstaller couldn't find TCL/TK installation path even I have it. I found the PyInstaller uses output from ldd to find the a path to TCL/TK libraries. But no dynamic libraries under my Python 5 lib-dynload directoty contain a path to TCL/TK libraries. When I posted this problem to the PyInstaller newsgroup, a guy responded that he didn't have such problem. After several exchanges, what we found was his lib-dynload directory contains _tkinter.so (even he has the same Python2.5.2) while my lib- dynload directory doesn't have it. He installed the Python using package tool (no fresh compile) while I installed my Python from src (clean compile). I recompiled Python 2.4 and confirmed that Python 2.4 creates _tkinter.so. After browsing the Makefile under Python 2.5, I had an impression that Python 2.5 no longer uses _tkinter.so. Am I correct? If that is the case, I need to warn the PyInstaller developers that the scheme to find TCL/TK path is no longer valid. Any comments will be highly appreciated. Thank you for your attention. Aki Niimura From andreas.tawn at ubisoft.com Fri Jun 13 05:30:50 2008 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Fri, 13 Jun 2008 11:30:50 +0200 Subject: boolian logic In-Reply-To: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> References: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> Message-ID: <8AEDA5E3386EA742B8C24C95FF0C7580042EA82B@PDC-MAIL3.ubisoft.org> if a != b and a != c and a != d: doStuff() else: doOtherStuff() Cheers, Drea >HI all, I'm a bit stuck with how to work out boolian logic. > >I'd like to say if A is not equal to B, C or D: > do something. > >I've tried > >if not var == A or B or C: >and various permutations but can't seem to get my head around it. I'm >pretty sure I need to know what is calulated first i.e the not or the >'OR/AND's > >thanks, Marc. From userprogoogle-139 at yahoo.co.uk Wed Jun 25 05:38:47 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Wed, 25 Jun 2008 02:38:47 -0700 (PDT) Subject: Mobile Devices Message-ID: Hi, I have been scouting around online for information on how to use Python and a GUI toolikit to develop mobile devices. At present I am using wxPython for desktop apps and would like to continue using that if possible. Anyway, I would like to know what people would recommend for developing mobile applications which can run on Windows Mobile and Mac OS X (iPhone etc)? It would also be cool if the same apps could run where possible (or atleast part of them) on desktop machines as well. Any tips, experiences etc welcome. This is really to stimulate some general discussion. Best, rod From larry.bates at websafe.com` Thu Jun 26 22:15:34 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 26 Jun 2008 21:15:34 -0500 Subject: python interface to Firefox and Thunderbird In-Reply-To: <6c5dab9f-3521-4434-8100-65ad1fe207d0@i36g2000prf.googlegroups.com> References: <6c5dab9f-3521-4434-8100-65ad1fe207d0@i36g2000prf.googlegroups.com> Message-ID: yardennis wrote: > Hi, > > I need python moudles that can > > auto install python 2.5 (web install or a EXE file) > > auto download and install Firefox3 and Thunderbird 2 > auto import from IE 6, 7 and OE 5,6 and Outlook > > read contacts and emails from Thunderbird store > read Firefox 3 bookmarks, history, cookies and password > > Can anyone point to a open source solution ? > > If you know of any freelancer that can help me develop the module > please let me know. > > Thanks > > Dennis > yardennis at gmail dot com The reason you haven't gotten any responses is that you didn't provide adequate information> You didn't say what O/S, so I have to guess that since you said Outlook it must be windows. - Auto download and install FF3/TB2. Why? Dowload the installers and put them somewhere (CD/ROM, Flash Drive, etc) , then write a batch file that installs them. - Auto download and install Python. Same as FF/TB. Get setup.exe from ActiveState Python. - Auto import from IE 6, 7 and OE 5,6 and Outlook. Auto import what into what? Is OE Outlook Express? What do you want to import and what are you importing into? - Read contacts and emails from Thunderbird store. Why? Wouldn't it be easier to read them from the POP3/IMAP server? - Read Firefox 3 bookmarks, history, cookies and password. There are plug-ins that allow you to export these items (at least bookmarks and passwords). History/cookies can be easily cleared by the users. If you want to monitor sites visited, there are better ways. As you can see we will need to know more about what you are trying to accomplish to help more. -Larry From mccredie at gmail.com Fri Jun 20 17:10:27 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 20 Jun 2008 14:10:27 -0700 (PDT) Subject: Tkinter canvas drag/drop obstacle References: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> <09ec833f-7751-4991-8d09-45c200fb4c18@z72g2000hsb.googlegroups.com> Message-ID: On Jun 20, 11:10?am, Matimus wrote: > On Jun 20, 9:11?am, Peter Pearson wrote: > > > Tkinter makes it very easy to drag jpeg images around on a > > canvas, but I would like to have a "target" change color when > > the cursor dragging an image passes over it. ?I seem to be > > blocked by the fact that the callbacks that might tell the > > target that the mouse has entered it (, , > > even ) aren't called if the mouse's button is down. > > What am I missing? ?Have I failed to find the right Tkinter > > document? ?Is Tkinter the wrong tool for this job? ?Thanks. > > > -- > > To email me, substitute nowhere->spamcop, invalid->net. > > I have used a combination of and . You might also > throw in a event to keep track of whether or not the mouse > button was down when it entered the widget or not. > > Depending on what you really want to do though, you might take > advantage of the 'active' state: > > import Tkinter as tk > > can = tk.Canvas() > can.pack(fill=tk.BOTH, expand=True) > > can.create_rectangle( > ? ? ? ? 10,10,100,100, > ? ? ? ? fill="black", > ? ? ? ? activewidth=5, > ? ? ? ? activeoutline="blue" > ? ? ? ? ) > > can.mainloop() > > The 'active*' options take effect when the mouse is on top of that > item. > > If all you are _really_ interested in is a visual indicator, this > should work for you. Note that there is also a disabled state. I only > discovered this by looking at the options available and guessing. > > >>> from pprint import pprint > >>> import Tkinter as tk > >>> can = tk.Canvas() > >>> can.pack(fill=tk.BOTH, expand=True) > >>> r = can.create_rectangle(10,10,100,100) > >>> pprint(can.itemconfig(r)) > > {'activedash': ('activedash', '', '', '', ''), > ?'activefill': ('activefill', '', '', '', ''), > ?'activeoutline': ('activeoutline', '', '', '', ''), > ?'activeoutlinestipple': ('activeoutlinestipple', '', '', '', ''), > ?'activestipple': ('activestipple', '', '', '', ''), > ?'activewidth': ('activewidth', '', '', '0.0', '0.0'), > ?'dash': ('dash', '', '', '', ''), > ?'dashoffset': ('dashoffset', '', '', '0', '0'), > ?'disableddash': ('disableddash', '', '', '', ''), > ?'disabledfill': ('disabledfill', '', '', '', ''), > ?'disabledoutline': ('disabledoutline', '', '', '', ''), > ?'disabledoutlinestipple': ('disabledoutlinestipple', '', '', '', ''), > ?'disabledstipple': ('disabledstipple', '', '', '', ''), > ?'disabledwidth': ('disabledwidth', '', '', '0.0', '0'), > ?'fill': ('fill', '', '', '', ''), > ?'offset': ('offset', '', '', '0,0', '0,0'), > ?'outline': ('outline', '', '', 'black', 'black'), > ?'outlineoffset': ('outlineoffset', '', '', '0,0', '0,0'), > ?'outlinestipple': ('outlinestipple', '', '', '', ''), > ?'state': ('state', '', '', '', ''), > ?'stipple': ('stipple', '', '', '', ''), > ?'tags': ('tags', '', '', '', ''), > ?'width': ('width', '', '', '1.0', '1.0')} > > The 'state' option can be set to 'normal', 'hidden' or 'disabled'. So > if you want to make your canvas items look different when they are > disabled, set the disabled* options and set 'state' to 'disabled'. > > Matt I appologize. I didn't actually test this before posting the code, but if you have the mouse button down before entering an item on the canvas, even the active state doesn't seem apply. So, well, I hope someone finds this information useful, but I guess it isn't going to solve the original posters issue. Matt From rhamph at gmail.com Sat Jun 14 13:04:15 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Sat, 14 Jun 2008 10:04:15 -0700 (PDT) Subject: Automatically restarting system calls? References: Message-ID: On Jun 13, 10:41 am, Dan Stromberg wrote: > I wrote a script(1) replacement in python (http://stromberg.dnsalias.org/ > ~dstromberg/pypty/), but I'm encountering a problem in it. > > I think I know the solution to the problem, but I'd've thought python was > high level enough that this solution isn't required, so I wanted to > inquire about it here. > > Specifically, the program has a signal handler for window size changes. > And if the window is resized during an os.write() (for example), I get a > python exception about needing to restart the system call. > > In C, I know you're supposed to wrap your system calls with while loops > until you don't get an ERESTART, but does one really need to wrap all of > one's os.write()'s (for example) with such while loops in python? Unfortunately, signals are sometimes used to intentionally interrupt system calls, so we can't always loop on ERESTART. However, os.write() is a low level API. Maybe file.write() or socket.send() would be a little more robust? From cwitts at gmail.com Thu Jun 12 09:22:25 2008 From: cwitts at gmail.com (Chris) Date: Thu, 12 Jun 2008 06:22:25 -0700 (PDT) Subject: get keys with the same values References: <7334507d-24e7-43f9-baa3-4e9e87eb20fa@w7g2000hsa.googlegroups.com> Message-ID: <017bbfe2-9ba7-4e8c-bb9c-fec923fd54a8@z72g2000hsb.googlegroups.com> On Jun 12, 2:15?pm, Nader wrote: > On Jun 12, 2:05 pm, Chris wrote: > > > > > On Jun 12, 1:48 pm, Nader wrote: > > > > On Jun 12, 1:35 pm, bearophileH... at lycos.com wrote: > > > > > Nader: > > > > > > d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} > > > > > I will something as : > > > > > d.keys(where their values are the same) > > > > > That's magic. > > > > > > With this statement I can get two lists for this example: > > > > > l1= ['a','e'] > > > > > l2=['b','d'] > > > > > Would somebody tell me how I can do it? > > > > > You can create a new dict where the keys are the values of the input > > > > dict and the values are a list of the keys of the original dict. So > > > > scanning the keys, values of the input dict, you can fill the second > > > > dict. Then you can scan the second dict, and create a list that > > > > contains only value lists longer than one. > > > > > Bye, > > > > bearophile > > > > Is it niet possible with one or two statement, maybe with list > > > comprehension. For exmple: > > > > l = [(k,v) for k in d.keys() for v in d.values() | en here we need > > > some extra logic (v = 1)] > > > > I don;t konw how we can define a logic statement in a list > > > comprehension. > > > It will be very compact, if it would possible. > > > > Nader > > > If you are going to use this reverse look-up alot you'd be better off > > building another dictionary with the original values being keys and > > the original keys being values, if it is used infrequently enough you > > can search for it with result_list = [k for k,v in dictionary.items() > > if v == search_value] > > Thank you! It is the anwser which I was looking for. [(k,v) for k,v > in ?d.items() if v is pattern]. > But I don't understand what tou mean of "reverse look-up a lot"! I > have to read some informations inclusive (latitudes and longitudes) > form a file and after some processing to save part of this information > to other file. > Why do I make a new dictionary? > > Nader If you are just going to perform the lookup once or twice then it's fine to traverse (step through) your original dictionary. If you are going to look up data often though it might be a better idea to build another dictionary with the reverse of your original dictionary as it will yield faster results. For example, your original dictionary of values is built and then you perform a handful of operations and move on, then use the list comprehension to get your data and move on. If, on the other hand, you build your dictionary and then maybe iterate over a file and need to look-up the information for every line in the file it would be better suited to build a new dictionary that transposed the key and value pairs for less resource intensive and faster operation. eg: reverse_dict = {} for k,v in original_dict: if v in reverse_dict: reverse_dict[v].append(k) else: reverse_dict[v] = [k] Then once that is built and you want to find which keys in the original dictionary have the value of "1" you can just do "list_of_keys = reverse_dict[1]". Essentially if you are going to do alot of searching for values that match values found in a dictionary you would be better off to create the new data structure. Hope that helps. From Russ.Paielli at gmail.com Wed Jun 11 02:11:02 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 10 Jun 2008 23:11:02 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <4847d39d$0$7614$426a74cc@news.free.fr> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> <484cf5f6$0$15495$426a74cc@news.free.fr> <127975a3-b3d9-4799-9673-b292ec8d37e3@x19g2000prg.googlegroups.com> <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> <484e3526$0$30894$426a74cc@news.free.fr> <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> <783c55ec-a294-4600-91d9-4a0d78632c49@t12g2000prg.googlegroups.com> Message-ID: <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> On Jun 10, 11:58 am, Jonathan Gardner > Who cares what the type of an object is? Only the machine. Being able > to tell, in advance, what the type of a variable is is a premature > optimization. Tools like psyco prove that computers (really, > programmers) nowadays are smart enough to figure things out the right > way without any hints from the developer. Static typing is no longer > necessary in today's world. You couldn't be more wrong. Even Guido recognizes the potential value of static typing, which is why he is easing it into Python as on optional feature. He recognizes, correctly, that it can detect errors earlier and facilitate more efficient execution. But there's another, more significant potential benefit for safety-critical and mission- critical applications: static typing facilitates advanced static analysis of software. To get an idea of what that is about, take a look at http://www.sofcheck.com Here is an excerpt from their website: "SofCheck?s advanced static error detection solutions find bugs in programs before programs are run. By mathematically analyzing every line of software, considering every possible input, and every path through the program, SofCheck?s solutions find any and all errors that cause a program to crash or produce an undefined result." Me again: static analysis does not replace traditional dynamic and unit testing, but it is far more advanced and finds many errors very quickly that might require weeks or months of dynamic testing -- or might not be found at all with dynamic testing until the product is in the field. With more and more automation of safety-critical systems these days, we need this more than ever. Your assertion that "Static typing is no longer necessary in today's world," is just plain naive. > Who cares about private declarations, or interface declarations at > all? It is only a message to the developers. If you have a problem > with your users doing the right thing, that is a social problem, not a > technical one, and the solution is social, not technical. Yes, it is > work, but it is not coding---it is explaining to other living, > breathing human beings how to do a specific task, which is what you > should have been doing from the start. You may be right to an extent for small or medium-sized non-critical projects, but you are certainly not right in general. I read something a while back about the flight software for the Boeing 777. I think it was something like 3,000,000 lines of Ada code. Normally, for a project of that magnitude the final integration would be expected to take something like three months. However, the precise interface specs and encapsulation methods in Ada allowed the integration to be completed in just three days. By your recommended method of social interaction, that would be one hell of a lot of talking! I realize that Python is not designed for such large projects, but don't you think certain general principles can be learned anyway? Perhaps the benefits of interface specs and encapsulation are not as obvious for smaller projects, but certainly they are not zero. From bearophileHUGS at lycos.com Tue Jun 17 13:09:18 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 17 Jun 2008 10:09:18 -0700 (PDT) Subject: Pattern Matching Over Python Lists References: <21a9c996-75ff-4f7c-b7e9-c94247f65674@c58g2000hsc.googlegroups.com> <87ej6w6ql6.fsf@internal.daycos.com> Message-ID: <61ea5c70-4352-4d2f-a0ef-62eb76ba933a@m36g2000hse.googlegroups.com> Kirk Strauser: > Hint: recursion. Your general algorithm will be something like: Another solution is to use a better (different) language, that has built-in pattern matching, or allows to create one. Bye, bearophile From expertleong at gmail.com Mon Jun 30 22:59:09 2008 From: expertleong at gmail.com (Hongster) Date: Mon, 30 Jun 2008 19:59:09 -0700 (PDT) Subject: Functions associated with a class. References: Message-ID: <56c16601-569c-4eec-9497-c5803eee051c@g16g2000pri.googlegroups.com> Like what you mentioned, each class has a set of methods and properties (variables). Example of a class: Human Properties of a Human class: height, weight, birthday, occupation, ... Methods of a Human class: eat(food), move(speed, destination), sleep(), ... Methods of a class is just an ordinary function, with an "self" parameter (by convention). You can define more than 1 arguments for a function. Tom = Human() Dick = Human() Tom.eat(corn) Dick.eat(potato) Tom and Dick are both instances of a Human class. They are not arguments. "corn" and "potato" contain values that are passed to the eat() function as argument. The '.' notation is used to indicate which instance's method/property you are referring to. The 'x' and 'y' you mentioned are just different instances, they are not arguments. This is my first post, hopes it helps. On Jul 1, 7:44?am, Kurda Yon wrote: > Hi, > > I start to learn the object oriented programing in Python. As far as I > understood, every class has a set of corresponding methods and > variables. For me it is easy to understand a method as a one-argument > function associated with a class. For example, if I call "x.calc" and > "y.calc" and if "x" and "y" belongs to different classes I, actually, > call to different function (the first one is associated with the first > class and the second one with the second class). If "x" and "y" > belongs to the same class, the "x.calc" and "y.calc" refer to the same > function (but called with different arguments ("x" and "y", > respectively)). > > In the above described case we have one-argument function. But what > should we do if we one two have a two-argument function. For example, > we want to have a method "calc" which take two objects and returns one > value. How do we call this method? Like "x&y.calc"? Or just calc(x,y)? > In the case of the one-argument functions Pythons automatically decide > which function to call (associated with the first class or with the > second class). Will it be the same in the case of the two-argument > function. > > I am not sure that I am clear. If I am not clear, just ask me. I will > try to reformulate my questions. > > Thank you. From martin at v.loewis.de Tue Jun 10 02:56:15 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 10 Jun 2008 08:56:15 +0200 Subject: Cannot install python under Win32 In-Reply-To: <82d86466-0b90-47aa-af40-f52b52eb2526@d77g2000hsb.googlegroups.com> References: <82d86466-0b90-47aa-af40-f52b52eb2526@d77g2000hsb.googlegroups.com> Message-ID: <484e258f$0$13627$9b622d9e@news.freenet.de> > Hello, I have tried to install python 2.5.1 and 2.5.2 with the same > error. The installer starts fine, but when it gets to the part that > says "Status: Copying new files" it terminates with an error code of > 2356. > > Does anyone have a clue to what to do? Run the installer with msiexec /i /l*v py.log, then study py.log to find out what went wrong. Are you by any chance running the installer from a SUBSTed drive? Regards, Martin From apardon at forel.vub.ac.be Wed Jun 4 02:41:44 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Jun 2008 06:41:44 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <5ea78616-e955-4ee0-8e60-a22734ec31be@79g2000hsk.googlegroups.com> <7f1a9057-83c7-4ca6-8fd8-38195db45865@s33g2000pri.googlegroups.com> Message-ID: On 2008-06-03, Lie wrote: > > Python has an extremely good design because the BDFL doesn't just > listen to everyone and create a product that tries to please > everybody, no, he listens to those that have good ideas and tells the > stupid ideas to go away and he applies a subjective decision which > more often than not leads to a better python. I agree that Guido van Rossum has done an excellent job. That doesn't mean he has to be painted as unfailable in which the ideais he accepts are good ideas and those he rejects are bad ideas almost by definition. Guido has been known to change his mind, which is an admirabele quality, but it does show that at some point he rejected a good idea or accepted a bad idea. -- Antoon Pardon From cwitts at gmail.com Fri Jun 6 05:45:37 2008 From: cwitts at gmail.com (Chris) Date: Fri, 6 Jun 2008 02:45:37 -0700 (PDT) Subject: import cherrypy2 References: <0853b1cc-33bb-416e-9b2e-0fa146ede1c1@79g2000hsk.googlegroups.com> Message-ID: <7c00f301-5d49-4f49-98fd-d0f5e72aa135@c65g2000hsa.googlegroups.com> On Jun 6, 10:59?am, luca72 wrote: > On 6 Giu, 10:31, Chris wrote: > > > > > On Jun 6, 10:22 am, luca72 wrote: > > > > Hello i can't import cherrypy2 but i don't know why this is the sys > > > path: > > > > '', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > > setuptools-0.6c7-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > > python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg', '/home/pirataja/ > > > opo.net/python/lib/python2.5/site-packages/TurboKid-1.0.4-py2.5.egg', > > > '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > > TurboJson-1.1.2-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > > python2.5/site-packages/TurboCheetah-1.0-py2.5.egg', '/home/pirataja/ > > > opo.net/python/lib/python2.5/site-packages/simplejson-1.9.1-py2.5- > > > linux-i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site- > > > packages/RuleDispatch-0.5a0.dev_r2306-py2.5-linux-i686.egg', '/home/ > > > pirataja/opo.net/python/lib/python2.5/site-packages/PasteScript-1.6.2- > > > py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > > FormEncode-1.0.1-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > > python2.5/site-packages/DecoratorTools-1.7-py2.5.egg', '/home/pirataja/ > > > opo.net/python/lib/python2.5/site-packages/configobj-4.5.2-py2.5.egg', > > > '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > > CherryPy-2.3.0-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > > python2.5/site-packages/kid-0.9.6-py2.5.egg', '/home/pirataja/opo.net/ > > > python/lib/python2.5/site-packages/Cheetah-2.0.1-py2.5-linux- > > > i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > > PyProtocols-1.0a0dev_r2302-py2.5-linux-i686.egg', '/home/pirataja/ > > > opo.net/python/lib/python2.5/site-packages/PasteDeploy-1.3.1- > > > py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > > > Paste-1.7-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > > > python25.zip', '/home/pirataja/pirata-jacopo.net/python/lib/ > > > python2.5', '/home/pirataja/opo.net/python/lib/python2.5/plat- > > > linux2', > > > '/home/pirataja/opo.net/python/lib/python2.5/lib-tk', > > > '/home/pirataja/opo.net/python/lib/python2.5/lib-dynload', '/home/ > > > pirataja/opo.net/python/lib/python2.5/site-packages'] > > > > For my is all ok but whe i do import cherrypy2 i get no mudule name > > > cherrypy2 > > > > Regards > > > > Luca > > > because it's "import cherrypy" and not "import cherrypy2" > > sorry but from another python installation i import cherrypy2 as > cherrypy and all works > > Regards > > Luca Did you install Lino on the other installation ? http://lino.sourceforge.net/src/3.html It's the only mention of a cherrypy2 I know of. From ptmcg at austin.rr.com Tue Jun 3 12:15:10 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 3 Jun 2008 09:15:10 -0700 (PDT) Subject: trinity school defender References: Message-ID: <94969559-96f0-4e72-ae1d-4d3bb5273fab@m73g2000hsh.googlegroups.com> On Jun 3, 10:26?am, Dino Dragovic wrote: > u gorenavedenom flajeru u 8. redu: > > "postoji vi?e od 60.000 virusa i drugih ?tetnih programa " > > samo virusa ima nekoliko stotina tisuca, zajedno sa potencijalno stetim > aplikacijama i ostalim malicioznim kodom brojka ide preko milion.... castironpi, call your office... From upton at virginia.edu Tue Jun 10 11:49:12 2008 From: upton at virginia.edu (Dan Upton) Date: Tue, 10 Jun 2008 11:49:12 -0400 Subject: Does the python library of Google Data API is truly free? In-Reply-To: <18115776-edf7-41b8-a5e9-639847c57a6a@x41g2000hsb.googlegroups.com> References: <3ac654b2-61b4-44ce-8e03-75f2344d5869@s50g2000hsb.googlegroups.com> <6fb57ab1-b0d2-4b7d-93c1-b919ca0e51a0@i36g2000prf.googlegroups.com> <3a296d00-d4e0-4f03-b6b3-bef4c5d628dd@x35g2000hsb.googlegroups.com> <6b5mloF3aeui4U1@mid.uni-berlin.de> <18115776-edf7-41b8-a5e9-639847c57a6a@x41g2000hsb.googlegroups.com> Message-ID: <5504f9ac0806100849s316e1907l391f1fd7603f3f65@mail.gmail.com> >> Or if they prohibit you to host malicious, offending or otherwise >> problematic content served by the free apache - is that "against free >> software?" > Please, don't be demagogue. Please don't be [a] troll....? I fail to see what is so hard to understand about the difference between free software and services provided via free software. From markjturner at gmail.com Thu Jun 12 11:37:16 2008 From: markjturner at gmail.com (Mark) Date: Thu, 12 Jun 2008 08:37:16 -0700 (PDT) Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <6bcokhF3b2mo7U1@mid.uni-berlin.de> <485131a1$0$11175$c3e8da3@news.astraweb.com> Message-ID: On Jun 12, 3:45?pm, Aidan wrote: > Aidan wrote: > > Mark wrote: > >> John, it's a QuerySet coming from a database in Django. I don't know > >> enough about the structure of this object to go into detail I'm > >> afraid. > > >> Aidan, I got an error trying your suggestion: 'zip argument #2 must > >> support iteration', I don't know what this means! > > > well, if we can create 2 iterable sequences one which contains the user > > the other the scores, it should work > > > the error means that the second argument to the zip function was not an > > iterable, such as a list tuple or string > > > can you show me the lines you're using to retrieve the data sets from > > the database? then i might be able to tell you how to build the 2 lists > > you need. > > wait you already did... > > predictions = Prediction.objects.all() > pairs = [(p.predictor.id,p.predictionscore) for p in predictions] > > those 2 lines will will build a list of user/score pairs. ?you can then > replace the call to zip with pairs > > any luck? Thanks Aidan, this works great! Thanks also to everyone else, I'm sure your suggestions would have worked too if I'd been competent enough to do them properly! From koblas at gmail.com Wed Jun 4 13:35:05 2008 From: koblas at gmail.com (koblas) Date: Wed, 4 Jun 2008 10:35:05 -0700 (PDT) Subject: Import removing first module component Message-ID: <75481b47-87ec-4a84-8063-7abbdb286d62@u6g2000prc.googlegroups.com> Have the following line: import notewave.runner.LMTP Yeilding the following error: ImportError: No module named runner.LMTP For the life of me I don't understand why the first component "notewave" is being stripped off, when the import is happening. Thanks, From bruno.desthuilliers at gmail.com Wed Jun 25 15:29:06 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 25 Jun 2008 12:29:06 -0700 (PDT) Subject: reading from list with paths References: <6c1ed580-259a-4df2-b389-ecf38296a138@25g2000hsx.googlegroups.com> Message-ID: <69ac18bf-a9a4-45ed-aa74-ccdf2b5f0570@i76g2000hsf.googlegroups.com> On 25 juin, 20:59, antar2 wrote: > Hello, > (snip repost of the very same question) > I already got one answer for this question, but it did not work For which definition of "did not work" ? How is your code ? What did you expect, and what did you get ? Sorry to ask these questions, but my crystal ball is currently down for maintainance... From bronger at physik.rwth-aachen.de Sat Jun 14 15:47:39 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 14 Jun 2008 21:47:39 +0200 Subject: Making wxPython a standard module? References: <6bidd7F3bg8usU1@mid.uni-berlin.de> Message-ID: <87fxrfx0h0.fsf@physik.rwth-aachen.de> Hall?chen! Grant Edwards writes: > On 2008-06-14, Diez B. Roggisch wrote: > >>>> And on a personal note: I find it *buttugly*. >>> >>> Do you mind explaining "why" you find it *buttugly*? > > [...] > >> For the curious: Not the look & feel (albeit I prefer KDE on >> linux over Gnome, which is a Qt/GTK thing and thus affects wx >> look & feel as well), but the code & the designers. > > I've never used any of the designers, but I agree 100% that > wxPython code is nasty ugly. wxPython has a very un-Pythonic API > that's is, IMO, difficult to use. I know that such requests may start a never-ending thread but I'd really like to know what you mean with this. I had almost no GUI experience when I started to use wxPython, yet it was a pleasure for me. Really, aesthetics of the source is important to me being a hobby programmer, and I don't like wxPython's camel case and getters and setters. However, even many (if not most) core Python modules don't respect PEP8 or don't use current language features. Besides, passing function names as strings is also a wart, and *I* have simply never understood signal and slots. Maybe we should accept that there is no silver bullet in GUI toolkits, and any personal preferences amongst the Big Four are just a matter of taste. This "un-Pythonic" thing is arbitrary and unfair wording in my opinion. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From sjmachin at lexicon.net Sun Jun 22 19:39:44 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 22 Jun 2008 16:39:44 -0700 (PDT) Subject: listcomprehension, add elements? References: <13452c64-ef91-49a2-bb73-7f33c088660e@d45g2000hsc.googlegroups.com> <7dc3d1d6-12d7-4a9e-ac7a-91406610e106@d19g2000prm.googlegroups.com> Message-ID: <510c6f38-24f8-431e-9b37-c70ed91b3ee2@z24g2000prf.googlegroups.com> On Jun 23, 9:23 am, Paul Hankin wrote: > On Jun 23, 10:32 am, cirfu wrote: > > > [a+b for a,b in zip(xrange(1,51), xrange(50,0,-1))] > > > [51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, > > 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, > > 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51] > > > i want to add all the elemtns a s well. can i do this all in a > > listcomprehension? > > > i can do this ofc: > > reduce(lambda x,y:x+y,[a+b for a,b in zip(xrange(1,51), > > xrange(50,0,-1))]) > > > but reduce is a functional way of doing it, what is the more pythonic > > way of doing this? > > Use the builtin 'sum' function. > > sum(a + b for a, b in zip(xrange(1, 51), xrange(50, 0, -1))) > Instead of sum(a + b for a, b in zip(foo, bar)) why not use sum(foo) + sum(bar) ? From fc14301589 at icqmail.com Thu Jun 12 03:38:37 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Thu, 12 Jun 2008 15:38:37 +0800 Subject: My fight with classes :) References: <484fde63_1@news.tm.net.my> Message-ID: <4850d287_2@news.tm.net.my> On 04:51, gioved? 12 giugno 2008 Terry Reedy wrote: First of all a big thank you, all. > def makeappender(): > data = ['',''] > def appender(val): > > return appender I'll give it a try. I just doubting if the data will be shared outside the function. Actually, my practice goes to send all variables to the functions and expecting a returned value. Usually I'm not relying on that module's variables are read inside a function. Probably I got wrong learning or experiences. > For multiple functions, use classes. That's what I'm leaning to :) Then I re-elaborated the class according your points and now it's what I wanted to be. :) (last time I forgot to past the first line) Here it comes: class StrJoin: """ Join a pair of strings according to the leading first letter A or D, it returns a list of 2 elements""" def __init__(self): self.valueA= '' self.valueD= '' def append(self, value): if not isinstance(value, str): raise TypeError, 'Wrong type concatenation' if value.lower().startswith('a'): self.valueA += value if value.lower().startswith('d'): self.valueD += value return [self.valueA ,self.valueD] def __getitem__(self,idx): if idx > 1 : return self if idx == 0 : return self.valueA if idx == 1 : return self.valueD __call__= append def __repr__(self): return '['+ self.valueA+ ','+ self.valueD+ ']' And the shell >>: >>> from utilities import StrJoin as zx >>> k = zx() >>> k [,] >>> k('add') ['add', ''] >>> k[2] [add,] >>> k[1] '' >>> k[0] 'add' >>> k('dad') ['add', 'dad'] >>> k('sad') ['add', 'dad'] >>> k('Alfa') ['addAlfa', 'dad'] >>> k('Dude') ['addAlfa', 'dadDude'] >>> k('Omega') ['addAlfa', 'dadDude'] >>> k('Dome') ['addAlfa', 'dadDudeDome'] >>> k.append[k] Traceback (most recent call last): File "", line 1, in TypeError: 'instancemethod' object is unsubscriptable >>> k(89) Traceback (most recent call last): File "", line 1, in File "utilities.py", line 33, in append raise TypeError, 'Wrong type concatenation' TypeError: Wrong type concatenation >>> Mostly I'll use the call option. I also like to pass it into a function in order to modularize the loop where it gets started. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From nick at craig-wood.com Tue Jun 24 04:32:11 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 24 Jun 2008 03:32:11 -0500 Subject: MD5 hash for url and utf unicode converting to ascii References: Message-ID: joe shoemaker wrote: > I would like to convert url into md5 hash. My question is that md5 > hash will create collision at 2^64. If you do long(value,16), where > value is the md5 hash string, would value returned from long(value, > 16) be unique as long as md5 hashed string is unique? when you move > md5 hashed string to long, where will the collision occur, at anything > >= 2^64? > > hash = md5.new() > hash.update("some_url_") > value = hash.digest() > value_in_int = long(value, 16) #would this be unique as long as > hashed string is unique(i.e < 2^64) > hash = md5.new() hash.update("some_url_") value = hash.digest() > value_in_int = long(value, 16) #would this be unique as long as hashed > string is unique(i.e < 2^64) MD5 Sums don't guarantee uniqueness for any length of string. If your hash had as many or more bits in as the input string then there are hashes which are guaranteed unique, but MD5 isn't one of them. You could (lets say) AES encrypt the string instead. > Do I need to also convert the value to base64.encodestring(value)? > What is the purpose of base64.encodestring? To turn the buffer into printable characters. You can do it like this also... >>> import md5 >>> hash = md5.new() >>> hash.update("some_url_") >>> value = hash.digest() >>> value '\xc9\x11}\x8f?64\x83\xf3\xcaPz\x1d!\xddd' >>> value.encode("hex") 'c9117d8f3f363483f3ca507a1d21dd64' >>> long(value.encode("hex"), 16) 267265642849753964132104960801656397156L >>> > For unicode encoding, I can do, md5.update(value.encode('utf-8')) to > give me ascii values. Yes that would be fine -- Nick Craig-Wood -- http://www.craig-wood.com/nick From chrisspen at gmail.com Thu Jun 19 20:44:09 2008 From: chrisspen at gmail.com (Chris) Date: Thu, 19 Jun 2008 17:44:09 -0700 (PDT) Subject: Pattern Matching Over Python Lists References: <21a9c996-75ff-4f7c-b7e9-c94247f65674@c58g2000hsc.googlegroups.com> <87ej6w6ql6.fsf@internal.daycos.com> <61ea5c70-4352-4d2f-a0ef-62eb76ba933a@m36g2000hse.googlegroups.com> Message-ID: <0796be8f-647c-4d19-86e5-e2472fb2daa3@34g2000hsh.googlegroups.com> Thanks for your help. Those weren't quite what I was looking for, but I ended up figuring it out on my own. Turns out you can actually search nested Python lists using simple regular expressions. From martin at marcher.name Mon Jun 2 10:23:00 2008 From: martin at marcher.name (Martin Marcher) Date: Mon, 2 Jun 2008 16:23:00 +0200 Subject: Python's doc problems: sort In-Reply-To: <929d5ce9-9063-4e6c-98aa-89526f89fba3@y18g2000pre.googlegroups.com> References: <929d5ce9-9063-4e6c-98aa-89526f89fba3@y18g2000pre.googlegroups.com> Message-ID: <5fa6c12e0806020723r306bb44dx99aaa0696210ce3b@mail.gmail.com> Hi, On Wed, Apr 30, 2008 at 4:48 AM, xahlee at gmail.com wrote: > For example, in last week, that page is fetched 550 times. > The second most popular page, trails quite a distance. Here's the top yup that was me, i have access to a couple of machines and wanted to test some intercommunication, I faked most of the user agent strings but still was locked out by popular pages. I then figured it would be much better to fetch a useless page a couple of times. Sorry for the lognoise... /martin -- http://www.xing.com/profile/Martin_Marcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From deets at nospam.web.de Thu Jun 12 15:32:10 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 12 Jun 2008 21:32:10 +0200 Subject: Mapping None. Why? In-Reply-To: References: Message-ID: <6bdbtuF3aqe92U1@mid.uni-berlin.de> Paddy schrieb: > Iam wondering why the peculiar behavior of map when the function in > given as None: > > Help on built-in function map in module __builtin__: > > map(...) > map(function, sequence[, sequence, ...]) -> list > > Return a list of the results of applying the function to the items > of > the argument sequence(s). If more than one sequence is given, the > function is called with an argument list consisting of the > corresponding > item of each sequence, substituting None for missing values when > not all > sequences have the same length. If the function is None, return a > list of > the items of the sequence (or a list of tuples if more than one > sequence). > > > It seems as the action whith none is the same as using a function of > lambda *x: x > As in the following example: > >>>> l1 = 'asdf' >>>> l2 = 'qwertyuip' >>>> l3 = range(3) >>>> l1,l2,l3 > ('asdf', 'qwertyuip', [0, 1, 2]) >>>> map(lambda *x: x, l1,l2,l3) == map(None, l1,l2,l3) > True > > > On looking up map on Wikipedia there is no mention of this special > behaviour, > So my question is why? Because it is undefined what should happen in case of no function given at all - and because there is no identity function in python pre-defined, it could be considered sensible to make None the quivalent of that function. And it only follows that *if* you imply a function even though there is None given, that the passed tuple is returned. I don't see anything on wikipedia that defines any other behavior. Diez Diez From ptmcg at austin.rr.com Wed Jun 18 15:51:16 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 18 Jun 2008 12:51:16 -0700 (PDT) Subject: Does '!=' equivelent to 'is not' References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> <20080617120941.GE7349@dragontoe.org> Message-ID: <0fcecc82-0edd-4f57-865a-b2e558577281@x35g2000hsb.googlegroups.com> On Jun 18, 2:22?pm, Lie wrote: > > I'm not a native English speaker, although I think my parents would > have liked me to be more straightforward when talking, cause I tend to > say things like "possibly", "maybe", "probably", and other ambiguous > expressions to the extent that it has frustrated them now and then. Well, at least you *talk* to your parents! Mostly what I get from my kids is, "can I borrow 10 dollars?" -- Paul From saqib.ali.75 at gmail.com Fri Jun 20 16:17:54 2008 From: saqib.ali.75 at gmail.com (susan_ali@hotmail.com) Date: Fri, 20 Jun 2008 13:17:54 -0700 (PDT) Subject: How do I create a new Node using pulldom? Message-ID: I'm using xml.dom.pulldom to parse through an XML file. I use expandNode() to scrutinize certain blocks of it that I'm interested in. Once I find a block of XML in the input file that I'm interested in, I need to add my own block ..... to the pulldom tree I'm building in memory. The documentation on PullDom is worse than atrocious. It is simply non- existant. I can't even find a simple explanation of what the functions are named and what arguments they take. Sheesh. When I have a node N of the tree, I think that I can use N.appendChild() to do what I want (just guessing from the function name which I can see). appendChild takes 1 argument -- a new node. But I don't know how to create such a node. Can someone out there please post a code fragment showing how to create a pulldom node? The simpler and more commented it is the better. THANKS!!! - Saqib From ludvig.ericson at gmail.com Tue Jun 24 17:35:38 2008 From: ludvig.ericson at gmail.com (ludvig.ericson at gmail.com) Date: Tue, 24 Jun 2008 14:35:38 -0700 (PDT) Subject: logging module's documentation lies? Message-ID: Quote from the docs: FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s" logging.basicConfig(format=FORMAT) d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} logging.warning("Protocol problem: %s", "connection reset", extra=d) would print something like 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset If we try to run that exact example, which doesn't seem logically flawed in any way: >>> import logging >>> FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s" >>> logging.basicConfig(format=FORMAT) >>> d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} >>> logging.warning("Protocol problem: %s", "connection reset", extra=d) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/site-packages/logging/__init__.py", line 1266, in warning apply(root.warning, (msg,)+args, kwargs) File "/usr/lib/python2.5/site-packages/logging/__init__.py", line 969, in warning apply(self._log, (WARNING, msg, args), kwargs) TypeError: _log() got an unexpected keyword argument 'extra' I tried using **d instead, no show. I tried extra=d in Python 2.4, no show. I tried **d in Python 2.4, no show. So, my question unto the lot of you is: Do the docs for the logging module lie to me? URL: http://docs.python.org/lib/module-logging.html From hv at tbz-pariv.de Tue Jun 3 08:05:56 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Tue, 03 Jun 2008 14:05:56 +0200 Subject: Image Processing (batch) Message-ID: <6akqd5F37rofnU1@mid.individual.net> Hi, I tried PIL for image batch processing. But somehow I don't like it - Font-Selection: You need to give the name of the font file. - Drawing on an image needs a different object that pasting and saving. - The handbook is from Dec. 2006. What image libraries do you suggest? I think there are these alternatives: - Python binding for image magick - python-gtk - python-gdk-imlib - call convert (imagemagick) with subprocess. This is how I did it up to now. But I want to avoid it. Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From bruno.42.desthuilliers at websiteburo.invalid Fri Jun 13 03:00:35 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 13 Jun 2008 09:00:35 +0200 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: References: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> <4850e95d$0$10444$426a74cc@news.free.fr> Message-ID: <48521aae$0$7558$426a74cc@news.free.fr> Duncan Booth a ?crit : > Bruno Desthuilliers wrote: > >> FWIW, metaclasses do have a class attribute that refers to itself !-) >> > One metaclass (i.e. type) has a class attribute that refers to itself. > > Other metaclasses have a class attribute that refers to the metaclass's > metaclass. I can't think of any situation where a metaclass would be its > own metaclass except for 'type' itself, but then I think I've got a > headache trying to think about this Yeps, same pattern here :-/ Thanks for the correction, anyway. (snip) From pistacchio at gmail.com Wed Jun 25 05:13:42 2008 From: pistacchio at gmail.com (pistacchio) Date: Wed, 25 Jun 2008 02:13:42 -0700 (PDT) Subject: Apache2 + Python WITHOUT mod_pytho Message-ID: <4f90e1e5-056e-4f61-866b-015a15030ebf@e39g2000hsf.googlegroups.com> Hi to all! How can i configure apache2 so that it processes all .py files with python _without_ using mod_python? I'm on Ubuntu 8.4. currently my /etc/apache2/sites-available/default file reads: __________________________ NameVirtualHost * ServerAdmin webmaster at localhost DocumentRoot /var/www/ Options FollowSymLinks AllowOverride None #Options +ExecCGI Indexes FollowSymLinks MultiViews Options All AllowOverride None Order allow,deny Allow from all #AddHandler mod_python .py #PythonHandler mod_python.publisher #PythonDebug On ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all ErrorLog /var/log/apache2/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/apache2/access.log combined ServerSignature On Alias /doc/ "/usr/share/doc/" Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 __________________________ Thanks in advance Gustavo From bioinf at physics.iisc.ernet.in Fri Jun 13 02:59:08 2008 From: bioinf at physics.iisc.ernet.in (bioinf at physics.iisc.ernet.in) Date: Fri, 13 Jun 2008 12:29:08 +0530 (IST) Subject: error showing file not found Message-ID: <3183.10.16.30.11.1213340348.squirrel@physics.iisc.ernet.in> Hi, I am new to python.I have installed Biopython in Windows.I am working using IDLE.When I want to get structure of local pdb file it is showing error that "no such file or directory".Can anybody tell what is the problem. -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From bob at mellowood.ca Thu Jun 12 13:51:31 2008 From: bob at mellowood.ca (bvdp) Date: Thu, 12 Jun 2008 10:51:31 -0700 Subject: Simple and safe evaluator References: <80b23a5a-8613-4232-8954-7f7e4181322e@k37g2000hsf.googlegroups.com> Message-ID: Matimus wrote: > On Jun 11, 9:16 pm, George Sakkis wrote: >> On Jun 11, 8:15 pm, bvdp wrote: >> >> >> >>> Matimus wrote: >>>> The solution I posted should work and is safe. It may not seem very >>>> readable, but it is using Pythons internal parser to parse the passed >>>> in string into an abstract symbol tree (rather than code). Normally >>>> Python would just use the ast internally to create code. Instead I've >>>> written the code to do that. By avoiding anything but simple operators >>>> and literals it is guaranteed safe. >>> Just wondering ... how safe would: >>> eval(s, {"__builtins__":None}, {} ) >>> be? From my testing it seems that it parses out numbers properly (int >>> and float) and does simple math like +, -, **, etc. It doesn't do >>> functions like int(), sin(), etc ... but that is fine for my puposes. >>> Just playing a bit, it seems to give the same results as your code using >>> ast does. I may be missing something! >> Probably you do; within a couple of minutes I came up with this: >> >>>>> s = """ >> ... (t for t in 42 .__class__.__base__.__subclasses__() >> ... if t.__name__ == 'file').next()('/etc/passwd') >> ... """>>> eval(s, {"__builtins__":None}, {} ) >> >> Traceback (most recent call last): >> File "", line 1, in >> File "", line 3, in >> IOError: file() constructor not accessible in restricted mode >> >> Not an exploit yet but I wouldn't be surprised if there is one. Unless >> you fully trust your users, an ast-based approach is your best bet. >> >> George > > You can get access to any new-style class that has been loaded. This > exploit works on my machine (Windows XP). > > [code] > # This assumes that ctypes was loaded, but keep in mind any classes > # that have been loaded are potentially accessible. > > import ctypes > > s = """ > ( > t for t in 42 .__class__.__base__.__subclasses__() > if t.__name__ == 'LibraryLoader' > ).next()( > ( > t for t in 42 .__class__.__base__.__subclasses__() > if t.__name__ == 'CDLL' > ).next() > ).msvcrt.system('dir') # replace 'dir' with something nasty > """ > > eval(s, {"__builtins__":None}, {}) > [/code] > > Matt Yes, this is probably a good point. But, I don't see this as an exploit in my program. Again, I could be wrong ... certainly not the first time that has happened :) In my case, the only way a user can use eval() is via my own parsing which restricts this to a limited usage. So, the code setting up the eval() exploit has to be entered via the "safe" eval to start with. So, IF the code you present can be installed from within my program's scripts ... then yes there can be a problem. But for the life of me I don't see how this is possible. In my program we're just looking at single lines in a script and doing commands based on the text. Setting/evaluating macros is one "command" and I just want a method to do something like "Set X 25 * 2" and passing the "25 * 2" string to python works. If the user creates a script with "Set X os.system('rm *')" and I used a clean eval() then we could have a meltdown ... but if we stick with the eval(s, {"__builtins__":None}, {}) I don't see how the malicious script could do the class modifications you suggest. I suppose that someone could modify my program code and then cause my eval() to fail (be unsafe). But, if we count on program modifications to be doorways to exploits then we might as well just pull the plug. Bob. From leodp at yahoo.com Mon Jun 30 05:47:52 2008 From: leodp at yahoo.com (leodp) Date: Mon, 30 Jun 2008 02:47:52 -0700 (PDT) Subject: Getting sorting order References: <7cb9ebb7-e722-41e1-bdf2-693954a21b92@j22g2000hsf.googlegroups.com> Message-ID: > Or provide a better explanation and an example. Do you mean something like > this? > Hi Peter, a small example: master=[1,4,3,2] slave1=['d','c','b','a'] slave2=[1,2,3,4] master.sort() # this is ok, but does not return infos on how the list was sorted slave1.sort(key=_maybe_something_here_referring_to_master_) slave2.sort(key=_maybe_something_here_referring_to_master_) Then I should get: master=[1,2,3,4] slave1=['d','a','b','c'] slave2=[1,4,3,2] Hope it is more clear now. Thanks, leodp From rcdailey at gmail.com Tue Jun 3 18:32:07 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 3 Jun 2008 17:32:07 -0500 Subject: Continuous Timer In-Reply-To: <48456b96$0$17165$742ec2ed@news.sonic.net> References: <496954360805301850u4ce63746vc8fcc84ad1b72824@mail.gmail.com> <48456b96$0$17165$742ec2ed@news.sonic.net> Message-ID: <496954360806031532o306d6481rce476c4237645960@mail.gmail.com> I just need a repeating timer, I could care less about microsecond accuracies. On Tue, Jun 3, 2008 at 11:19 AM, John Nagle wrote: > Gabriel Genellina wrote: > >> En Fri, 30 May 2008 22:50:13 -0300, Robert Dailey >> escribi?: >> >> Reading through the Python 2.5 docs, I'm seeing a Timer class in the >>> threading module, however I cannot find a timer object that will >>> continuously call a function of my choice every XXXX amount of >>> milliseconds. >>> For example, every 1000 milliseconds I want a function named Foo to be >>> called. This would continue to happen until I terminate the timer in my >>> main >>> thread. Thanks for the help. >>> >> >> Use an Event object; its wait() will provide the sleep time, and when it >> is set() the thread knows it has to exit. >> >> import threading >> import time >> >> def repeat(event, every, action): >> while True: >> event.wait(every) >> if event.isSet(): >> break >> action() >> > > Actually, to do this right, it's necessary to account for the time used > by > "action". The code above will run no sooner than the time "every" after > the COMPLETION of action. > > I've done this sort of thing under QNX, the real-time operating system, > which has better timing primitives, and seen the action executed within > a few microseconds of the correct time, every time. But that was in C++. > > If you're trying to do hard real time in Python on Linux or Windows, > don't expect reliable timing. Remember, Python isn't really preemptive, > because of the global interpreter lock and the lack of thread priorities. > > John Nagle > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Tue Jun 3 11:07:24 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 03 Jun 2008 17:07:24 +0200 Subject: Webpy vs Django? In-Reply-To: <7db4dfb2-1e50-4a89-a47b-7356119b2741@r66g2000hsg.googlegroups.com> References: <7db4dfb2-1e50-4a89-a47b-7356119b2741@r66g2000hsg.googlegroups.com> Message-ID: <48455e01$0$11974$426a74cc@news.free.fr> circularfunc at yahoo.se a ?crit : > i have been trying to get Django running for 2 days now and it drives > me crazy. > > i played with webpy a bit and it is easy to get going with. but django > seems like once you have it all up and running it will be easier. > just that the barrier of entry is much higher. Django is indeed a bit more complex than webpy. > is django worth it? seems so ridicoulusly hard to get it running. i > run into trouble every time i advance a little, firstin the > installationa nd now in the tutorial(creating polls). I'm a bit surprised by your report of having problems running Django. Deploying it on production can be a pain sometimes (well... I don't like sys-admin stuff anyway...), but running Django on the builtin test server with SQLite or MySQL is almost OOTB. > > what do you think of webpy for big projects that need performance? Nothing. Never tried it. From bignose+hates-spam at benfinney.id.au Mon Jun 16 08:50:22 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 16 Jun 2008 22:50:22 +1000 Subject: sorted or .sort() ? References: <99b0cc1e-1fb5-4581-8094-e50274acc2e8@k37g2000hsf.googlegroups.com> Message-ID: <87k5gpee7l.fsf@benfinney.id.au> Peter Bengtsson writes: > My poor understanding is that the difference between `sorted(somelist, > key=lambda x:...)` and `somelist.sort(lambda x,y...)` is that one > returns a new list and the other sorts in-place. Yes. > Does that mean that .sort() is more efficient and should be favored > when you can (i.e. when you don't mind changing the listish object)? No, it means you should choose the version that expresses what you actually want to do. Efficiency of the programmers ? including the unknown number of programmers who will have to read the code after you write it ? is in many cases a much more important criterion than efficiency of the CPU. People's time continues to be much more expensive than computer time, after all. -- \ "Are you pondering what I'm pondering?" "Umm, I think so, | `\ Brain, but what if the chicken won't wear the nylons?" -- | _o__) _Pinky and The Brain_ | Ben Finney From bruno.desthuilliers at gmail.com Wed Jun 25 15:34:45 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 25 Jun 2008 12:34:45 -0700 (PDT) Subject: Notice For All pyHook users References: <7e8718e7-2c75-4120-9ba3-dbd1669100f5@a1g2000hsb.googlegroups.com> Message-ID: <872f92c4-f04b-48b3-bd54-6ecd3727ce3c@a70g2000hsh.googlegroups.com> On 25 juin, 19:47, Gandalf wrote: > If you want to compile your program the new py2exe release 0.6.8 wont > work! > the pyhook function will be ignored > > you'll have to uninstall the 0.6.8 version and to install the 0.6.6 > instead > > it took me 2 days to find the solution. > > maybe some day someone will bump the same problem and find this > message through google py2exe bugtracker is here: http://sourceforge.net/tracker/?atid=115583&group_id=15583&func=browse and there's a page on the wiki named ProblemsToBeFixed: http://www.py2exe.org/index.cgi/ProblemsToBeFixed From omer at no-log.org Wed Jun 25 09:02:07 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Wed, 25 Jun 2008 15:02:07 +0200 Subject: newb question on strings In-Reply-To: References: Message-ID: <200806251502.07418.omer@no-log.org> Le Tuesday 24 June 2008 22:27:33 regex_jedi, vous avez ?crit?: > ok, I have looked a lot of places, and can't seem to get a clear > answer... > > I have a string called > each_theme > > Some values of the string may contain a single quote as in - > Happy > Sad > Nice > Frank's Laundry > Explosion > > Notice that the 4th value has a single quote in it. Well, I need to > make sure that the single quote is escaped before handing it off for > further processing to a class I later call for some other processing. > > So I thought, no big deal, I should be able to find a way to escape > the single quote on the string. I am a perl and PHP guy, so I do a > lot of regex stuff. I did a quick search and found someone had said > to use this re.sub function, so I tried. But the following doesn't > work. To be honest, I am a little lost with all the modules and > classes required to do simple math or string functions in Python. > None of it seems built it in.. its all import modules... Here is what > I am trying... > > # escape single quotes in theme name > re.sub('''(['"])''', r'\\\1', each_theme) > No python has no builtin support for regexp like perl. There's nothing wrong with your code, you just need to import the 're' module. Add this at the beginning of your script: import re But imho escaping the quote in the first part would be more readable than using triple quotes: >>> name = "Frank's Laundry" >>> re.sub(r"([\"'])", r"\\\1", name) "Frank\\'s Laundry" You'll find a list of all the standard modules in the python docs, including this one: http://docs.python.org/modindex.html http://docs.python.org/lib/module-re.html -- C?dric Lucantis From jason.scheirer at gmail.com Mon Jun 16 18:11:44 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Mon, 16 Jun 2008 15:11:44 -0700 (PDT) Subject: Please explain Python "__whatever__" construct. References: <02c8f509-2889-433b-a548-62ead677bd19@p39g2000prm.googlegroups.com> Message-ID: <48d3c41d-2a17-4017-b6d4-bd0bb2c8b194@d45g2000hsc.googlegroups.com> On Jun 16, 2:56?pm, bsag... at gmail.com wrote: > After a couple of weeks studying Python, I already have a few useful > scripts, including one that downloads 1500 Yahoo stock quotes in 6 > seconds. However, many things are puzzling to me. I keep on seeing > things like "__main__" in scripts. ?A more obscure example would be > "__add__" used in string concatenation. For example, I can use "Hello > "+"world (or just "Hello" "world") to join those two words. But I can > also use "Hello ".__add__("world"). When and why would I ever use > "__main__" or the many other "__whatever__" constructs? http://docs.python.org/lib/genindex.html#letter-_ From __peter__ at web.de Fri Jun 13 02:33:58 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Jun 2008 08:33:58 +0200 Subject: Plotting Graphs + Bestfit lines References: <1a919a2b-6430-4e2e-a190-2e00e43a6138@25g2000hsx.googlegroups.com> Message-ID: arslanburney at gmail.com wrote: > Hello. Ive got two functions here. Somehow the program does not go in > to the second function wehn i call it. The bestfit function. Could > some1 help me identify the problem. Heres the code: Same problem as before, you have to keep the Gnuplot instance alive if you want to see the graph. Note that instead of for i in range(len(uinput)): sigmaxy = uinput[i][0] * uinput[i][1] + sigmaxy you could write for x, y in uinput: sigmaxy += x * y High time to take a look into a good Python tutorial... # --- combine.py --- import Gnuplot def bestfit(uinput): sigmax = sigmay = sigmaxy = sigmaxwhl = sigmaxsq = 0 for i in range(len(uinput)): n = len(uinput) sigmax = uinput[i][0] + sigmax sigmay = uinput[i][1] + sigmay sigmaxy = uinput[i][0] * uinput [i][1] + sigmaxy sigmaxwhl = sigmax * sigmax sigmaxsq = uinput[i][0] * uinput[i][0] + sigmaxsq sigmaxsigmay = sigmax * sigmay num = sigmaxsigmay - (n * sigmaxy) den = sigmaxwhl - (n* sigmaxsq) num2 = (sigmax * sigmaxy) - (sigmay * sigmaxsq) gradient = num / den intercept = num2 / den m = gradient c = intercept p = Gnuplot.Gnuplot() p.plot ('%f * x+%f'%(m,c)) return p def plot(original, expected, actual): gp = Gnuplot.Gnuplot() gp('set data style lines') # Make the plot items plot1 = Gnuplot.PlotItems.Data(original, title="Original") plot2 = Gnuplot.PlotItems.Data(expected, title="Expected") plot3 = Gnuplot.PlotItems.Data(actual, title="Acutal") gp.plot(plot1, plot2, plot3) return gp def show_plots(original, expected, actual): gp = combine.plot( original, expected, actual) raw_input("first") gp = combine.bestfit(expected) raw_input("second") gp = combine.bestfit(actual) raw_input("third") # --- combine_main.py --- import combine combine.show_plots([(2,3), (4,8), (5,9), (6,2)], [(1,7), (3,3), (4,5), (5,6)], [(1,3), (3,10), (4,8), (7,9) ] ) From ppearson at nowhere.invalid Sun Jun 22 22:41:53 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: Sun, 22 Jun 2008 21:41:53 -0500 Subject: Tkinter canvas drag/drop obstacle References: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> Message-ID: On Fri, 20 Jun 2008 13:41:35 -0300, Guilherme Polo wrote: > On Fri, Jun 20, 2008 at 1:11 PM, Peter Pearson wrote: >> Tkinter makes it very easy to drag jpeg images around on a >> canvas, but I would like to have a "target" change color when >> the cursor dragging an image passes over it. I seem to be >> blocked by the fact that the callbacks that might tell the >> target that the mouse has entered it (, , >> even ) aren't called if the mouse's button is down. >> What am I missing? Have I failed to find the right Tkinter >> document? Is Tkinter the wrong tool for this job? Thanks. >> > > I believe the only way to achieve this is binding to the > entire canvas, then checking if the x, y coords are inside the > "target". Ugh. OK, thanks. -- To email me, substitute nowhere->spamcop, invalid->net. From deets at nospam.web.de Fri Jun 13 11:07:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 13 Jun 2008 17:07:30 +0200 Subject: weird iteration/assignment problem In-Reply-To: <61936860-de3f-4bb1-8806-08f9f21ad113@m36g2000hse.googlegroups.com> References: <61936860-de3f-4bb1-8806-08f9f21ad113@m36g2000hse.googlegroups.com> Message-ID: <6bfgpoF3bpl84U1@mid.uni-berlin.de> cirfu schrieb: > for i in xrange(0, len(texts)): > texts[i] = "yes" > > for i in texts: > i = "no" > > why is the first one working but not the second. i mean i see why the > firts one works but i dont udnerstand why the second doesnt. Because in the second you only bind the contents of texts to a name i. But that doesn't mean that i magically became an "alias" for texts[index] - it just happens to point at the same object. To accomplish what you want, the pythonic idiom is to use enumerate: for i, text in enumerate(texts): text[i] = "yes" Diez From dmitrey.kroshko at scipy.org Thu Jun 12 14:04:39 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Thu, 12 Jun 2008 11:04:39 -0700 (PDT) Subject: howto split string with both comma and semicolon delimiters Message-ID: <3e2540ab-1d2a-45a5-a5b6-3f7ae7a4efac@x35g2000hsb.googlegroups.com> hi all, howto split string with both comma and semicolon delimiters? i.e. (for example) get ['a','b','c'] from string "a,b;c" I have tried s.split(',;') but it don't work Thx, D. From cwitts at gmail.com Tue Jun 17 04:17:30 2008 From: cwitts at gmail.com (Chris) Date: Tue, 17 Jun 2008 01:17:30 -0700 (PDT) Subject: print problem References: <2MWdnYXqCY3yy8rVnZ2dnUVZ_sbinZ2d@posted.internode> Message-ID: On Jun 17, 8:15?am, pirata wrote: > I was trying to print a dot on console every second to indicates > running process, so I wrote, for example: > > for i in xrange(10): > ? ? print ".", > ? ? time.sleep(1) > > Idealy, a dot will be printed out each second. But there is nothing > print out until after 10 seconds, all 10 dots come out together. > > I've tried lose the comma in the print statement, and it works. > > Is that because of the print statement buffer the characters until > there is a new line character? > > Thanks import sys for i in xrange(10): sys.stdout.write('.') sys.stdout.flush() From pscott at uwc.ac.za Fri Jun 6 06:57:52 2008 From: pscott at uwc.ac.za (Paul Scott) Date: Fri, 06 Jun 2008 12:57:52 +0200 Subject: Convert Word .doc to Acrobat .pdf files In-Reply-To: <1dc26c3a0806060352k442475ccp6716b713268c161a@mail.gmail.com> References: <1dc26c3a0806060352k442475ccp6716b713268c161a@mail.gmail.com> Message-ID: <1212749872.6200.30.camel@paul-laptop> On Fri, 2008-06-06 at 16:22 +0530, Dinil Karun wrote: > hi, > > I am using the below code but i am getting a error saying pyUno module > not found. > can u please help. I just wrote the same thing! Take a look at http://cvs2.uwc.ac.za/trac/python_tools/browser/oooconv It should do what you want (and a little more). Sorry, the code quality is pretty bad, but I am in the process of cleaning it up still. --Paul -------------- next part -------------- All Email originating from UWC is covered by disclaimer http://www.uwc.ac.za/portal/public/portal_services/disclaimer.htm From fc14301589 at icqmail.com Sun Jun 15 05:58:24 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Sun, 15 Jun 2008 17:58:24 +0800 Subject: Configuration files References: <485419f0$0$5958$e4fe514c@dreader16.news.xs4all.nl> Message-ID: <4854e7c0_2@news.tm.net.my> On 04:11, domenica 15 giugno 2008 Daniel Fetchinson wrote: > Check this out: http://www.voidspace.org.uk/python/configobj.html > Let me add: cfgparse, iniparse I've look at all to find a simple solution for my interest, but I realized not a good result. I'm using three of them ConfigParser, cfgparse and optparse. Just to let read a configuration file and let user to subclass option at the console. If I'll get experienced by cfgparse I think I'll drop ConfigParser, because I'd like the idea to override file rules on console. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From deets at nospam.web.de Wed Jun 11 13:45:05 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 11 Jun 2008 19:45:05 +0200 Subject: question about import In-Reply-To: <886765d0-2be7-4a66-b838-032aebae0622@d1g2000hsg.googlegroups.com> References: <886765d0-2be7-4a66-b838-032aebae0622@d1g2000hsg.googlegroups.com> Message-ID: <6bah94F3b327sU1@mid.uni-berlin.de> Jonathan Vanasco schrieb: > I'm a little unclear about import / __import__ > > I'm exploring dynamically importing modules for a project, and ran > into this behavior > > works as expected: > app = __import__( myapp ) > appModel = __import__( myapp.model ) > > but... > appname= 'myapp' > app = __import__( "%s" % appname ) > appModel = __import__( "%s.model" % appname ) > > In the latter example, app and appModel will always seem to be > imported as 'myapp' , and I've yet to find a way to address the .model > namespace > > I know 'dynamically importing modules' is cursed upon -- and I'm > likely rewriting hundreds of line of codes so I can work around this > with a registration system -- however I'd like to understand why this > occurs and know if what i'm trying is even possible. Is it cursed upon? Didn't know that. However, __import__ only gives you the topmost module - in your case myapp. So you need to do it like this (untested): name = "a.b.c.d" mod = __import__(name) for part in name.split(".")[1:]: mod = getattr(mod, part) print mod Diez From noorhanabbas at yahoo.co.uk Thu Jun 5 12:19:51 2008 From: noorhanabbas at yahoo.co.uk (Noorhan Abbas) Date: Thu, 5 Jun 2008 16:19:51 +0000 (GMT) Subject: Loading Python programs on the net. Message-ID: <965558.33707.qm@web27401.mail.ukl.yahoo.com> Hello, I have developed a program in Python.? I need to put this program on the web. Could somebody advice me on the different tools that I can use to do this job. My python program basically displays a tree ctrl that allows users to choose from it and displays text as an output.? I need to develop a web page that displays this tree ctrl and accesses the text files to produce the output. Thank you very much, Nora. __________________________________________________________ Sent from Yahoo! Mail. A Smarter Email http://uk.docs.yahoo.com/nowyoucan.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From stdenton at sbcglobal.net Sat Jun 7 12:24:26 2008 From: stdenton at sbcglobal.net (Sam Denton) Date: Sat, 07 Jun 2008 11:24:26 -0500 Subject: Python and Flaming Thunder In-Reply-To: <4847ecf6$0$25178$c3e8da3@news.astraweb.com> References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <4847ecf6$0$25178$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > "Dave Parker" wrote in message > news:a95c09d9-94c3-4dac-9439-9176038d93d9 at w8g2000prd.googlegroups.com... > On May 20, 7:05 pm, Collin wrote: > > --- > For example, consider the two statements: > > x = 8 > x = 10 > > The reaction from most math teachers (and kids) was "one of those is > wrong because x can't equal 2 different things at the same time". > --- > > Aw, come on. I'm a novice programmer but even after reading the most basic > of introductions to a programming language I can tell that x is being > assigned one value, then another. I've long believed that '=' should be banned from programming languages. Use '==' for equality tests, and ':=' for assignments. From socyl at 987jk.com.invalid Fri Jun 13 12:05:06 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 13 Jun 2008 16:05:06 +0000 (UTC) Subject: Python noob's simple config problem References: Message-ID: In =?iso-8859-1?q?Robin_K=E5veland?= Hansen writes: >On Thu, 12 Jun 2008 21:32:34 +0000, kj wrote: >> I'm sure this is a simple, but recurrent, problem for which I can't hit >> on a totally satisfactory solution. >> >> As an example, suppose that I want write a module X that performs some >> database access. I expect that 99.999% of the time, during the >> foreseeable future, the database connection parameters will remain >> unchanged. The only exception that I envision for this would be during >> testing or debugging. >> >> Given all this, I am tempted to turn these connection parameters into >> hard-coded module attributes that I can always override (i.e. overwrite) >> when necessary. >> >> But for as long as I can remember the dogma has been that hard-coded >> values are bad, and that one should use other techniques, such as >> configuration files, or parameters to a suitable constructor, etc. >> >> This is where I begin to get confused: whose responsibility is it to >> know of and read the config file? I can think of two distinct >> scenarios: 1) module X is being used by a large, full-fledged >> application A that already uses a config file for its own configuration; >> 2) module X is being used by a simple script that has no need for a >> config file. In case 1 I'd be glad to let application A set module X's >> connection parameters using values read from its own (i.e. A's) config >> file; this minimizes the number of config files that need to be >> maintained. In case 2, however, it would be preferable for module X to >> read its connection params from its own (i.e. X's) config file. In this >> way the script won't have to bother setting some parameters that are in >> fact practically constant... >> >> After going round and round on this, my original idea of hard-coding the >> values as module attributes begins to look pretty attractive again. >> >> How would you handle such situations? >> >> Thanks! >> >> kynn >I think I would just abstract it away with a "getter" for the connection, >a function that takes some optional parameters, if not supplied, it >simply fetches them from a default configuration. Ie: >def connect(params=None): > if params is None: > return dblayer.connect(conf["default"]) > else: > return dblayer.connect(params) >Unless I have misunderstood you completely? Now people can change your >scripts config file, and if someone wants to use your code, they can use >the getter directly. >I hope this is of some help. Thanks! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From gh at ghaering.de Tue Jun 3 11:10:39 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 03 Jun 2008 17:10:39 +0200 Subject: UTC datetime.fromtimestamp In-Reply-To: References: Message-ID: Alok Kumar wrote: > Dear All, > > I have UTC datetime as > datetime.fromtimestamp(ParseDateTimeUTC("2007-12-06 20:37:05")) Just datetime.timedelta(days=1). -- Gerhard From paul at boddie.org.uk Thu Jun 19 05:17:13 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 19 Jun 2008 02:17:13 -0700 (PDT) Subject: Combining music or video files? References: <4855d5a5$0$11609$607ed4bc@cv.net> Message-ID: On 16 Jun, 04:53, John Salerno wrote: > Before I try this and destroy my computer :) I just wanted to see if > this would even work at all. Is it possible to read a binary file such > as an mp3 or an avi, put its contents into a new file, then read another > such file and append its contents to this same new file as well, thereby > making, for example, a single long video instead of two smaller ones? Probably not, as people have pointed out, but I imagine you could use GStreamer and a few processing pipelines, as I pointed out in a comment on the following article (for another task): http://jessenoller.com/2008/05/06/lazyweb-question-python-video-manipulation-libraries/ This is probably as close as you can get to treating the files as if they were simple things which can be concatenated. Paul From wmcbrine at users.sf.net Sun Jun 22 20:01:16 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Mon, 23 Jun 2008 00:01:16 GMT Subject: Learning Python: Code critique please References: <2f25e0ae-5828-4651-8ac6-55ba8bb50089@p25g2000pri.googlegroups.com> Message-ID: On Sun, 22 Jun 2008 08:44:25 -0500, Saul Spatz wrote: > macoovacany wrote: >> http://macoovacany.wordpress.com/ > When I tried to run it, I got all kinds of syntax errors because of > non-ASCII characters; namely, you have fancy left and right single and > double quotes. That's probably WordPress' doing. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From apardon at forel.vub.ac.be Mon Jun 2 05:38:43 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 2 Jun 2008 09:38:43 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> Message-ID: On 2008-05-24, Sh4wn wrote: > Hi, > > first, python is one of my fav languages, and i'll definitely keep > developing with it. But, there's 1 one thing what I -really- miss: > data hiding. I know member vars are private when you prefix them with > 2 underscores, but I hate prefixing my vars, I'd rather add a keyword > before it. > > Python advertises himself as a full OOP language, but why does it miss > one of the basic principles of OOP? Will it ever be added to python? > > Thanks in advance, > Lucas If you really need it, you can do data hiding in python. It just requires a bit more work. ----------------------------- Hide.py --------------------------------- class Rec(object): def __init__(__, **kwargs): for key,value in kwargs.items(): setattr(__, key, value) def __getitem__(self, key): return getattr(self, key) def __setitem__ (self, key, val): setattr(self, key, val) class Foo(object): def __init__(self): hidden = Rec(x=0, y=0) def SetX(val): hidden.x = val def SetY(val): hidden.y = val def GetX(): return hidden.x def GetY(): return hidden.y self.SetX = SetX self.SetY = SetY self.GetX = GetX self.GetY = GetY -------------------------------------------------------------------------- $ python Python 2.5.2 (r252:60911, Apr 17 2008, 13:15:05) [GCC 4.2.3 (Debian 4.2.3-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> From Hide import Foo >>> var = Foo() >>> var.GetX() 0 >>> var.SetX(5) >>> var.GetX() 5 >>> var.x Traceback (most recent call last): File "", line 1, in AttributeError: 'Foo' object has no attribute 'x' >>> var.hidden.x Traceback (most recent call last): File "", line 1, in AttributeError: 'Foo' object has no attribute 'hidden' -- Antoon Pardon From tilmaniac at gmail.com Fri Jun 6 17:13:16 2008 From: tilmaniac at gmail.com (Tilman Kispersky) Date: Fri, 6 Jun 2008 14:13:16 -0700 (PDT) Subject: Macro like functionality for shorthand variable names Message-ID: I have python code in a class method translated from C++ that looks sort of like this: >>> self.dydt[1] = self.a * (self.b * self.y[0] - self.y[1]) To make this more readable in C++ I had made macros to achieve this: #define du (dydt[1]) #define u (y[1]) #define V (y[0]) du = a * (b * V - u); I realize the value of not having macros in Python. They've tripped me up more than once in C++. My question is: Is there any way to write a shorterhand more readable version of the python code above? I'm doing several calculations one after the other and some of the lines are quite long. From matthieu.brucher at gmail.com Sat Jun 14 09:54:24 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Sat, 14 Jun 2008 15:54:24 +0200 Subject: Platform independent code? In-Reply-To: References: Message-ID: Hi, Python is a platform independent language, period. You can always excute a Python script with python script.py. Now, with Windows, you can execute the script by doucle-clicking on it. With Linux, it's different, you have to use the shebang line to execute a script with the correct interpreter. But this has nothing to do with the fact that Python is a platform independent language. Some modules may not be available on all platform, for the answer to this question, see the documentation of the module ;) Matthieu 2008/6/14 saneman : > I have read that Python is a platform independent language. But on this > page: > > http://docs.python.org/tut/node4.html#SECTION004220000000000000000 > > it seems that making a python script executable is platform dependant: > > 2.2.2 Executable Python Scripts > On BSD'ish Unix systems, Python scripts can be made directly executable, > like shell scripts, by putting the line > > > #! /usr/bin/env python > (assuming that the interpreter is on the user's PATH) at the beginning of > the script and giving the file an executable mode. The "#!" must be the > first two characters of the file. On some platforms, this first line must > end with a Unix-style line ending ("\n"), not a Mac OS ("\r") or Windows > ("\r\n") line ending. Note that the hash, or pound, character, "#", is used > to start a comment in Python. > > The script can be given an executable mode, or permission, using the chmod > command: > > > $ chmod +x myscript.py > > > > Are there any guidelines (API'S) that gurantees that the python code will be > platform independent? > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher From ubikvist at gmail.com Mon Jun 23 05:33:36 2008 From: ubikvist at gmail.com (ubikvist) Date: Mon, 23 Jun 2008 02:33:36 -0700 (PDT) Subject: Learning Python in a group References: <507738ef0806220343r3e9ea053neeec0baf0ccfdbe6@mail.gmail.com> <18c1e6480806220422x5d06c54byd23b249bb699691f@mail.gmail.com> <507738ef0806220452s74358615v44518469cf3b5f45@mail.gmail.com> <18c1e6480806220511s5117aef4gb4ec93bceb44a0ac@mail.gmail.com> Message-ID: <337ab3f9-5334-4737-baac-fded524e6d99@s50g2000hsb.googlegroups.com> I guess it's time to choose what a project your group will work at. Personally, I'm working at the project relating to text analysis, but it's rather specific because I use Russian texts. So, maybe we should to choose more 'international' implementation. -Ed From tjreedy at udel.edu Thu Jun 5 16:40:44 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 5 Jun 2008 16:40:44 -0400 Subject: line continuation for lines ending in "and" or "or" References: <90ee8b5d-1509-4463-aaab-f712f7e72d4b@j33g2000pri.googlegroups.com> <0d723e6d-f81b-4545-b406-fc60b20c5433@u6g2000prc.googlegroups.com> Message-ID: "Russ P." wrote in message news:0d723e6d-f81b-4545-b406-fc60b20c5433 at u6g2000prc.googlegroups.com... |. Well, it wouldn't be a bad idea for Python to do | what I thought it did, *plus* what I said it ought to do. A line ending in an operator is ambiguous in that it *could* indicate that the programmer intends to continue on the next line while it also could indicate that the programmer forgot to finish before hitting return, or that something got erased but not replaced. Moreover, the second possibility is actual (it actually happens) and not just theoretical. Moreover, the next line realistically could 'complete' the incomplete line 'by accident', so that the syntax bug would not get flagged. In such situations, some might lean toward the plausible guess choice, but Guido leans in the direction of choosing the bug interpretation. So he included the '\' mechanism. It is already used in strings to mean "do not take the next char literally", so having it mean "do not take the following end-of-line literally" is only a tiny step. Terry Jan Reedy From enlighten.power at gmail.com Fri Jun 6 21:20:00 2008 From: enlighten.power at gmail.com (Golu) Date: Fri, 6 Jun 2008 18:20:00 -0700 (PDT) Subject: need really help Message-ID: respected please help me i am really need of money please pay me through donation from my site. http://www.computersolution.co.cc i will be very thankful to you . please donate atleast 5$ or 2$ through my site http://www.computersolution.co.cc hope i will be able to clear my debts because of you all From stef.mientki at gmail.com Sun Jun 29 17:03:19 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 29 Jun 2008 23:03:19 +0200 Subject: list extension ? Message-ID: <4867F897.3020306@gmail.com> hello, I basically need a list with a few extra attributes, so I derived a new object from a list, and it works perfect. But I wonder why the newly derived list component is much more flexible ? # so here is the new list object class tGrid_List ( list ) : def __init__ ( self, value = [] ) : list.__init__ ( self, value ) # and with this new list component, I can add new attributes on the fly a = tGrid_list ( [ 2, 3 ] ) a.New_Attribute = 'some text' # I'm not allowed to this with the standard list a = [ 2, 3 ] a.New_Attribute = 'some text' <== ERROR Can someone explain this different behavior ? thanks, Stef Mientki From cjw at ncf.ca Mon Jun 23 10:38:57 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 23 Jun 2008 10:38:57 -0400 Subject: PyOpenGL New Installation Message-ID: I have just installed PyOpenGL and get a series of warning messages: Best match: PyOpenGL 3.0.0b3 Downloading http://downloads.sourceforge.net/pyopengl/PyOpenGL-3.0.0b3.zip?modtime=1213363873&big_mirror=0 Processing PyOpenGL-3.0.0b3.zip Running PyOpenGL-3.0.0b3\setup.py -q bdist_egg --dist-dir c:\docume~1\cjw\locals~1\temp\easy_install-hjyff7\PyOpenGL-3.0.0b3\egg-dist-tmp-iqd53p warning: no previously-included files matching '*.odt' found anywhere in distribution warning: no previously-included files matching '*.odp' found anywhere in distribution warning: no previously-included files matching '.cvsignore' found anywhere in distribution warning: no previously-included files matching '*.diff' found anywhere in distribution warning: no previously-included files found matching 'src\*.h' warning: no previously-included files found matching 'src\*.xml' warning: no previously-included files found matching 'src\*.zip' Adding pyopengl 3.0.0b3 to easy-install.pth file Installed c:\python25\lib\site-packages\pyopengl-3.0.0b3-py2.5.egg Processing dependencies for PyOpenGL Finished processing dependencies for PyOpenGL Could someone please advise the significance of these messages? Colin W. From alexnbryan at gmail.com Mon Jun 23 12:07:48 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Mon, 23 Jun 2008 11:07:48 -0500 Subject: Going from Tkinter to pyQT Message-ID: I had a guy on this mailing list tell me that pyQT is much better than Tkinter, and after looking into it a bit I think he is right. However, I can't find much on it. I want to know if there are any good books or online tutorials that would be helpful. I doubt there is one, but if there is one on going from Tkinter to pyQT, that would be amazing. Well if any of you guys have any tips or suggestions on any of this I would appreciate it. From bkasterm at gmail.com Sat Jun 21 16:49:38 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Sat, 21 Jun 2008 13:49:38 -0700 (PDT) Subject: String Concatenation O(n^2) (was: Re: Explaining Implementing a Binary Search Tree.) References: Message-ID: On Jun 17, 1:01?am, "Gabriel Genellina" wrote: > En Mon, 16 Jun 2008 07:34:06 -0300, Bart Kastermans escribi?: > > > Summary: can't verify big O claim, how to properly time this? > > > This is interesting. ?I had never attempted to verify a big O > > statement > > before, and decided that it would be worth trying. ?So I wrote some > > code to > > collect data, and I can't find that it goes quadratic. > > In your test code, you're concatenating only two strings, that's a *single* operation, and takes time proportional to the total length. > The quadratic behavior appears when you do *several* concatenations in a row (like in your original code, where += was used several times to build a result). > If you want to verify it, try joining N strings of size M (for varying values of N and M), and plot total time vs. N (for a given M value), and total time vs. M (for a given N value) and finally total time vs. (N*M), see what happens and post your findings again. > > -- > Gabriel Genellina I did the work and found that for trees it does not go quadratic at all, from the computations you suggest it is easy to get quadratic behavior though. Also this does not depend in any way I can see on the implementation by Python. Actual time might certainly improve by doing it differently (changing the constants), but the big O results won't. For pictures and math I have put it up on my blog again see: http://kasterma.wordpress.com/2008/06/21/complexity-of-string-concatenation-ii/ Thanks to everyone who commented so far on this subject. I had some good fun with it so far. Best, Bart From sjmachin at lexicon.net Sat Jun 21 10:29:40 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 21 Jun 2008 07:29:40 -0700 (PDT) Subject: Getting column names from a cursor using ODBC module? References: Message-ID: On Jun 22, 12:19 am, John Machin wrote: > On Jun 21, 11:58 pm, dana... at yahoo.com wrote: > > > Is there any way to retrieve column names from a cursor using the ODBC > > module? Or must I, in advance, create a dictionary of column position > > and column names for a particular table before I can access column > > values by column names? I'd prefer sticking with the ODBC module for > > now because it comes standard in Python. > > > I'm using Python 2.4 at the moment. > > Do you mean the odbc module? If so, it doesn't come standard in > Python; it's part of the win32 package. > > I haven't used it for years -- my preference on Windows these days > would be mxODBC if the client would pay the licence fee, otherwise > pyodbc. Sorry I'm not answering your question ... perhaps you should > be asking a different question :) > > Cheers, > John But to help you answer your question: if the module that you are using supports the 2.0 version of the database API (see http://www.python.org/dev/peps/pep-0249/), then it will support the cursor.description attribute, which gives you not only the name but the type and 5 other bits of info about each column. If it doesn't, I'd suggest moving on. HTH, John From bruno.42.desthuilliers at websiteburo.invalid Thu Jun 12 05:47:05 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 12 Jun 2008 11:47:05 +0200 Subject: My fight with classes :) In-Reply-To: <4850d287_2@news.tm.net.my> References: <484fde63_1@news.tm.net.my> <4850d287_2@news.tm.net.my> Message-ID: <4850f03a$0$17485$426a74cc@news.free.fr> TheSaint a ?crit : > On 04:51, gioved? 12 giugno 2008 Terry Reedy wrote: > > First of all a big thank you, all. > >> def makeappender(): >> data = ['',''] >> def appender(val): >> >> return appender > > I'll give it a try. I just doubting if the data will be shared outside the > function. Each time makeappender is called, it returns a new appender function object with it's own 'data' object. So 'data' won't be shared between different instances of the appender function. > Actually, my practice goes to send all variables to the functions and > expecting a returned value. Mostly a sane, sound and sensible approach IMHO - but doesn't work that well when the function needs to maintain own state between calls. > Usually I'm not relying on that module's > variables are read inside a function. Probably I got wrong learning or > experiences. As long as you only *read* module's globals from within a function, that's mostly ok. When you start *writing* them it may be time to reconsider the design (not that it's necessarily bad, but it's a possible signal that something is wrong). >> For multiple functions, use classes. Well... Closures are poor men's objects, or so they say (or is that the other way round ?-). def make_person(name, age): state = dict(name=name, age=age) def set_name(new_name=None): state['name'] = new_name def get_name(): return state['name'] def grow(): state['age'] += 1 def get_age() return state['age'] return set_name, get_name, grow, get_age (toto_set_name, toto_get_name, toto_grow, toto_get_age) = make_person('toto', 42) A bit cumbersome, indeed !-) From nicola.musatti at gmail.com Wed Jun 4 05:26:11 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Wed, 4 Jun 2008 02:26:11 -0700 (PDT) Subject: Help need with subprocess communicate References: <0312b7e9-bffe-4360-bf3a-f5b3b26d243d@l64g2000hse.googlegroups.com> Message-ID: On Jun 3, 11:04 pm, rdab... at gmail.com wrote: > I'm trying to perform following type of operation from inside a python > script. > 1. Open an application shell (basically a tcl ) > 2. Run some commands on that shell and get outputs from each command > 3. Close the shell [...] > Following is my code: > > from subprocess import * > p2 = Popen('qdl_tcl',stdin=PIPE,stdout=PIPE) > o,e = p2.communicate(input='qdl_help \n qdl_read \n > qdl_reg_group_list ') > > Please suggest a way to perform it interactively with killing the > process each time I want to communicate with it. Here's what you need: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 Cheers, Nicola Musatti From morton.thomas at googlemail.com Mon Jun 9 08:02:44 2008 From: morton.thomas at googlemail.com (Thomas Morton) Date: Mon, 9 Jun 2008 13:02:44 +0100 Subject: Getting current screen resolution Message-ID: <8e02cf540806090502q427f22b6h4fb85bbe14736e76@mail.gmail.com> This is a "thing" that has been annoying me all morning: and I can't work out how to do it. I need a way to get the DPI or screen resolution of the monitor that a script is currently runnign on. I have a way in Windows but it doesnt port to Unix (which is important). Any ideas? -- Thomas Morton Lead Developer || Founder TomNRob Web Services www.tomnrob.com From http Mon Jun 2 20:11:16 2008 From: http (Paul Rubin) Date: 02 Jun 2008 17:11:16 -0700 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> Message-ID: <7xhccbe5sr.fsf@ruckus.brouhaha.com> "Russ P." writes: > I also realize, by the way, that Python allows a client of a class to > define a new class member from completely outside the class > definition. Obviously, that cannot be declared private. This is bogus about 95% of the time though. For the cases where it is really desired, I think it's best to require the target class to be enable it specifically somehow, maybe by inheriting from a special superclass. That could let the compiler statically resolve member lookups the rest of the time. From Sengly.Heng at gmail.com Sat Jun 7 15:14:29 2008 From: Sengly.Heng at gmail.com (Sengly) Date: Sat, 7 Jun 2008 12:14:29 -0700 (PDT) Subject: simple question on list manipulation from a newbie Message-ID: <76ccc0a8-90de-4717-9e6f-06836827b1e1@i18g2000prn.googlegroups.com> Dear all, I am working with wordnet and I am a python newbie. I'd like to know how can I transfer a list below In [69]: dog Out[69]: [{noun: dog, domestic_dog, Canis_familiaris}, {noun: frump, dog}, {noun: dog}, {noun: cad, bounder, blackguard, dog, hound, heel}, {noun: frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, weenie}, {noun: pawl, detent, click, dog}, {noun: andiron, firedog, dog, dog-iron}] to a list like this with python: [dog, domestic_dog, Canis_familiaris, frump, dog, dog, cad, bounder, blackguard, dog, hound, heel, frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, weenie}, pawl, detent, click, dog}, andiron, firedog, dog, dog-iron] Thank you. Sengly From tjreedy at udel.edu Sun Jun 29 14:35:57 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 29 Jun 2008 14:35:57 -0400 Subject: Why is recursion so slow? In-Reply-To: <5504f9ac0806290703h1bf44639jbfe5331c4a2d1369@mail.gmail.com> References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> <5504f9ac0806290703h1bf44639jbfe5331c4a2d1369@mail.gmail.com> Message-ID: Dan Upton wrote: > On Sun, Jun 29, 2008 at 1:27 AM, Terry Reedy wrote: >> >> slix wrote: >>> Recursion is awesome for writing some functions, like searching trees >>> etc but wow how can it be THAT much slower for computing fibonacci- >>> numbers? >> The comparison below has nothing to do with recursion versus iteration. (It >> is a common myth.) You (as have others) are comparing an exponential, >> O(1.6**n), algorithm with a linear, O(n), algorithm. >> > > FWIW, though, it's entirely possible for a recursive algorithm with > the same asymptotic runtime to be wall-clock slower, just because of > all the extra work involved in setting up and tearing down stack > frames and executing call/return instructions. Which is exactly why I continued with "In Python, an algorithm written with iteration is faster than the same algorithm written with recursion because of the cost of function calls. But the difference should be a multiplicative factor that is nearly constant for different n. (I plan to do experiments to pin this down better.) Consequently, algorithms that can easily be written iteratively, especially using for loops, usually are in Python programs." People should read posts to the end before replying, in case it actually says what one thinks it should, but just in a different order than one expected. If each call does only a small amount of work, as with fib(), I would guess that time difference might be a factor of 2. As I said, I might do some measurement sometime in order to get a better handle on when rewriting recursion as iteration is worthwhile. tjr From Lie.1296 at gmail.com Sun Jun 15 13:22:02 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 15 Jun 2008 10:22:02 -0700 (PDT) Subject: Creating a TCP/IP connection on already-networked computers References: <4853f269$0$11615$607ed4bc@cv.net> Message-ID: <32dc420e-4a54-4665-95e8-0978a529ede1@v26g2000prm.googlegroups.com> On Jun 14, 11:31?pm, John Salerno wrote: > Let me see if this question even makes sense...I'm reading Core Python > Programming and I jumped ahead to the more specific topics like network > programming. I plan to follow along with the example in that chapter and > create a socket connection between my desktop and laptop. > > However, these two computers are already connected on my home network > (using the Windows Network Setup Wizard), so I was wondering if this > will have any effect on what I might try to do with Python. In other > words, if the program I write actually works and allows the two > computers to speak to each other, will that be a result purely of the > program, or will it have anything to do with the fact that they are > already on a home network together? (i.e. there's another variable in play?) > > Thanks. The Windows Network Wizard is a poor abstraction to set up layer 3 and 4 (the TCP/IP and lower) and layer 5 (the file sharing). You don't need to run this wizard if you've set up your TCP/IP and lower correctly manually (which, according to me, is easier than using the wizard). In a normal situation, you shouldn't need to worry about setting up the layer 3 and 4, you can assume that this two already set up. Some problem lies when connecting two computers through internet, such as you may have to use external IP address or set up port forwarding on the server-side. This is due to the use of 192.168.xxx.xxx as inside-LAN IP address instead of letting each device on the whole world has their own IP address. From spamtrap at dot-app.org Mon Jun 30 13:49:32 2008 From: spamtrap at dot-app.org (Sherman Pendley) Date: Mon, 30 Jun 2008 13:49:32 -0400 Subject: perl + python tutorial available for download References: <86c4090b-ed0b-4249-b3ee-517c94328741@z32g2000prh.googlegroups.com> <31f90$486914df$11268@news.teranews.com> Message-ID: smallpond writes: > "Pyhton" ?? > > typical Both typical, and illustrative of Xah's skill level. :-) sherm-- -- My blog: http://shermspace.blogspot.com Cocoa programming in Perl: http://camelbones.sourceforge.net From pavel.uvarov at gmail.com Mon Jun 2 11:19:05 2008 From: pavel.uvarov at gmail.com (pavel.uvarov at gmail.com) Date: Mon, 2 Jun 2008 08:19:05 -0700 (PDT) Subject: ThreadPoolingMixIn References: <3d9dac72-ce4d-4ce5-9213-4bb17aff2f9e@r66g2000hsg.googlegroups.com> <1c4d113e-b375-471d-9d54-1401c8844352@t12g2000prg.googlegroups.com> Message-ID: <3ac90c85-e4a0-4564-afbc-df8eec131347@d77g2000hsb.googlegroups.com> On Jun 2, 7:09 pm, pavel.uva... at gmail.com wrote: > On May 31, 9:13 pm, Rhamphoryncus wrote: > > > On May 30, 2:40 pm, pavel.uva... at gmail.com wrote: > > > > Hi, everybody! > > > > I wrote a useful class ThreadPoolingMixIn which can be used to create > > > fast thread-based servers. This mix-in works much faster than > > > ThreadingMixIn because it doesn't create a new thread on each request. > > > Do you have any benchmarks demonstrating the performance difference/ > > To benchmark this I used a simple tcp server which writes a small > (16k) > string to the client and closes the connection. > > I started 100 remote clients and got 500 replies/s for ThreadingMixIn > and more than 1500 replies/s for ThreadPoolingMixIn. I tested it on > FreeBSD 6.2 amd64. > > I'm very curious about the exactness of the number 500 for > ThreadingMixIn. It seems to be the same for various packet sizes. > I suspect there is some OS limit on thread creating rate. > > Below I include a bugfixed ThreadPoolingMixIn and the benchmarking > utility. The utility can be used to start clients on localhost, though > the reply rate will be slower (around 1000 replies/s). > > To start benchmarking server with localhost clients use: > python ./TestServer.py --server=threading --n-clients=100 > or > python ./TestServer.py --server=threadpooling --n-clients=100 I've just tested it on a linux box and got a 240 replies/s vs 2000 replies/s, that is 8x performance improvement. From eliben at gmail.com Mon Jun 23 00:44:55 2008 From: eliben at gmail.com (eliben) Date: Sun, 22 Jun 2008 21:44:55 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> Message-ID: <7c81f724-6c4a-4b5f-9e8a-e4cdb01a9293@2g2000hsn.googlegroups.com> Thanks for all the replies in this post. Just to conclude, I want to post a piece of code I wrote to encapsulate function creation in this way: def create_function(code): """ Create and return the function defined in code. """ m = re.match('\s*def\s+([a-zA-Z_]\w*)\s*\(', code) if m: func_name = m.group(1) else: return None d = {} exec code.strip() in globals(), d return d[func_name] Although the 'def' matching in the beginning looks a bit shoddy at first, it should work in all cases. Eli From pataphor at gmail.com Thu Jun 5 05:02:10 2008 From: pataphor at gmail.com (pataphor) Date: Thu, 5 Jun 2008 11:02:10 +0200 Subject: multiprocessing module (PEP 371) References: <877a5774-d3cc-49d3-bb64-5cab8505a419@m3g2000hsc.googlegroups.com> Message-ID: In article <877a5774-d3cc-49d3-bb64-5cab8505a419 @m3g2000hsc.googlegroups.com>, sturlamolden at yahoo.no says... > I don't see pyprocessing as a drop-in replacement for the threading > module. Multi-threading and multi-processing code tend to be > different, unless something like mutable objects in shared memory is > used as well (cf. Python Shared Objects). If this limitation can > educate Python programmers to use queues instead of locks and mutable > objects, even multi-threaded Python programs may actually benefit. > Some API differences between threading and multiprocessing do not > matter. Programmers should not consider processes as a drop-in > replacement for threads. This is probably not very central to the main intention of your post, but I see a terminology problem coming up here. It is possible for python objects to share a reference to some other object. This has nothing to do with threads or processes, although it can be used as a *mechanism* for threads and processes to share data. Another mechanism would be some copying and synchronization scheme, which is what posh seems to do. Or maybe not, I haven't used posh yet, I just read some docs (and I already hate the "if process.fork():" idiom, what are they trying to do, reintroduce c-style assignment and swiching?). By the way I haven't done much thread and process programming, but the things I *have* done often combine threads and processes, like starting a console oriented program in a background process, redirecting the IO and communicate with it using an event loop in a thread. I gets more complicated when a gui thread is also involved, for example when retrofitting a gui interface to an existing terminal based chess or go playing program. P. From taygunkekec at gmail.com Wed Jun 25 02:57:34 2008 From: taygunkekec at gmail.com (Taygun Kekec) Date: Tue, 24 Jun 2008 23:57:34 -0700 (PDT) Subject: Using Python to run SSH commands on a remote server References: <03a078c8$0$3229$c3e8da3@news.astraweb.com> <86adnQ8H4MFYdcLVnZ2dnUVZ_sHinZ2d@cablespeedwa.com> <03a08853$0$3220$c3e8da3@news.astraweb.com> <48601b32$0$7361$607ed4bc@cv.net> Message-ID: <1d136a46-3701-4160-badb-9545ff863a74@m36g2000hse.googlegroups.com> Alson you can take a look at pexpect module if you want to automate logging in and process commands , in this way you will no longer wait for loginname and password prompt. From vdutto at gmail.com Tue Jun 3 06:45:39 2008 From: vdutto at gmail.com (V) Date: Tue, 3 Jun 2008 03:45:39 -0700 (PDT) Subject: Books for programmers References: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> Message-ID: <78ef063d-7219-4ffa-bf8f-88dc24dd90bc@r66g2000hsg.googlegroups.com> Hi Matt, and thank you very much for your answer. > Hm, depends of course, how good your programming skills are in the > languages you knwo already, but I rely on the book "Beginning Python - > From Novice to Professional" by Magnus Lie Hetland, published by Apress. I think that I'm interested in a more advance book, ideally one that talk of the Python gotchas, traps, pitfall, idioms, performance, stile, and so on. I really like the style used from Scott Meyers in his Effective C++ series, or from Herb Sutter's Exceptional C++, but after a quick look I did not find anything similar for Python... Best regards. From sturlamolden at yahoo.no Tue Jun 3 23:18:43 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 3 Jun 2008 20:18:43 -0700 (PDT) Subject: can python do some kernel stuff? References: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> <48366cfa$0$15168$607ed4bc@cv.net> <28c432f0-657c-4272-8cd4-a9081b013279@w5g2000prd.googlegroups.com> <69nigsF3499pqU2@mid.uni-berlin.de> <4836994e$0$11625$607ed4bc@cv.net> <69nls3F344g2cU1@mid.uni-berlin.de> <4836a876$0$11623$607ed4bc@cv.net> Message-ID: On Jun 4, 12:41 am, Ethan Furman wrote: > the kernel itself, *is* kernel coding. And as wonderful as Python is, > it is *not* for kernel coding. Not in its present form, no, it would take some porting. But aside from that, is there any reason one could not embed a python interpreter in the kernel? From george.sakkis at gmail.com Sat Jun 21 11:02:34 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 21 Jun 2008 08:02:34 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <79a1c500-1844-4405-8f52-21e845a85f9b@z66g2000hsc.googlegroups.com> <5678904d-93ee-40f1-97b2-78d49ce29fb7@f24g2000prh.googlegroups.com> <7c2386a3-ffba-4bbb-aeab-3e263710ac60@26g2000hsk.googlegroups.com> Message-ID: On Jun 21, 9:40?am, eliben wrote: > > > I see. In my case I only evaluate function definitions with 'exec', so > > > I only need to de-indent the first line, and the others can be > > > indented because they're in a new scope anyway. What you suggest works > > > for arbitrary code and not only function definitions. It's a nice > > > trick with the "if 1:" :-) > > > Have you actually profiled your code? Or are you just basing this > > assumptions on guesses? > > First of all, I see absolutely no connection between your question and > the text you quote. Is there? Or did you pick one post randomly to > post your question on? > > Second, yes - I have profiled my code. > > Third, this is a very typical torture path one has to go through when > asking about code generation. It is true of almost all communities, > except Lisp, perhaps. You have to convince everyone that you have a > real reason to do what you do. The simple norm of getting a reply to > your question doesn't work when you get to code generation. I wonder > why is it so. How many people have been actually "burned" by bad code > generation techniques, and how many are just parroting "goto is evil" > because it's the accepted thing to say. This is an interesting point > to ponder. It's not as much that many people have been burned but that, like goto, 99% of the time there are better alternatives. Off the top of my head, two recurring threads in c.l.py related to dynamic code generation and evaluation are: - Asking how to dynamically generate variable names ("for i in xrange(10): exec 'x%d = %d' % (i,i)") instead of using a regular dictionary. - Using function names instead of the actual function objects and calling eval(), not knowing that functions are first-class objects (or not even familiar with what that means). So even if your use case belongs to the exceptional 1% where dynamic code generation is justified, you should expect people to question it by default. George From pythonblogs at gmail.com Mon Jun 2 14:49:13 2008 From: pythonblogs at gmail.com (pythonblogs at gmail.com) Date: Mon, 2 Jun 2008 11:49:13 -0700 (PDT) Subject: python blogs Message-ID: <19d5037f-837d-4f6b-9e56-d4e6d84b277d@y22g2000prd.googlegroups.com> Hello! It seems like Python blogs are gaining popularity. It seems to me that they play a crucial role in promoting Python as a language. Do you agree with that? Just a few days ago I've finished setting up a dedicated Python blogging environment at: http://www.pythonblogs.com Do you think it will be useful for Python community? By the way, everyone is welcome to join. Sincerely yours, ~pyblog From dfnsonfsduifb at gmx.de Fri Jun 6 18:03:47 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Sat, 07 Jun 2008 00:03:47 +0200 Subject: Newbie question, list comprehension Message-ID: <3rooh5xmap.ln2@joeserver.homelan.net> Hello group, I'm currently doing something like this: import time localtime = time.localtime(1234567890) fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % (localtime[0], localtime[1], localtime[2], localtime[3], localtime[4], localtime[5]) print fmttime For the third line there is, I suppose, some awesome python magic I could use with list comprehensions. I tried: fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % ([localtime[i] for i in range(0, 5)]) But that didn't work: Traceback (most recent call last): File "./test.py", line 8, in ? fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % ([localtime[i] for i in range(0, 5)]) TypeError: int argument required As it appearently passed the while list [2009, 02, 14, 0, 31, 30] as the first parameter which is supposed to be substituted by "%04d". Is there some other way of doing it? Thanks a lot, Regards, Johannes -- "Wer etwas kritisiert muss es noch lange nicht selber besser k?nnen. Es reicht zu wissen, da? andere es besser k?nnen und andere es auch besser machen um einen Vergleich zu bringen." - Wolfgang Gerber in de.sci.electronics <47fa8447$0$11545$9b622d9e at news.freenet.de> From xpahos at gmail.com Fri Jun 6 09:02:44 2008 From: xpahos at gmail.com (phasma) Date: Fri, 6 Jun 2008 06:02:44 -0700 (PDT) Subject: BZip2 decompression and parsing XML Message-ID: Hi. I'm trying to disassemble bzipped file. If I use minidom.parseString, I'm getting this error: Traceback (most recent call last): File "./replications.py", line 342, in ? File "/usr/lib64/python2.4/xml/dom/minidom.py", line 1925, in parseString return expatbuilder.parseString(string) File "/usr/lib64/python2.4/xml/dom/expatbuilder.py", line 940, in parseString return builder.parseString(string) File "/usr/lib64/python2.4/xml/dom/expatbuilder.py", line 223, in parseString parser.Parse(string, True) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 538676, column 17 If I use minidom.parse, I'm getting this error: Traceback (most recent call last): File "./replications.py", line 341, in ? files.xml = minidom.parse(bz2.decompress(dump)) File "/usr/lib64/python2.4/xml/dom/minidom.py", line 1915, in parse return expatbuilder.parse(file) File "/usr/lib64/python2.4/xml/dom/expatbuilder.py", line 922, in parse fp = open(file, 'rb') IOError But XML parsed normally. Code: try: handler = open(args[0], "r") dump = handler.read() handler.close() except IOError, error: print("Can't open dump: %s" % error) sys.exit(1) files.xml = minidom.parse(bz2.decompress(dump)) From zephyrfalcon!NO_SPAM! at gmail.com Wed Jun 4 18:42:31 2008 From: zephyrfalcon!NO_SPAM! at gmail.com (Hans Nowak) Date: Wed, 04 Jun 2008 18:42:31 -0400 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <207cafc4-ba3a-47cb-95d6-50b2b709b84b@j33g2000pri.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <5ea78616-e955-4ee0-8e60-a22734ec31be@79g2000hsk.googlegroups.com> <207cafc4-ba3a-47cb-95d6-50b2b709b84b@j33g2000pri.googlegroups.com> Message-ID: Lie wrote: > On May 24, 9:14 pm, Fuzzyman wrote: >> For example, at Resolver Systems we expose the spreadsheet object >> model to our users. It hasa public, documented, API - plus a host of >> undocumented internally used methods. >> >> We would really *much* rather hide these, because anything our >> customers start using (whether documented or not) we will probably >> have to continue supporting and maintaining. > Then don't document it, or separate internal documentation (which is > never to pass through the wall) and public documentation (which your > users use). Nobody would (apart from your dev team and anyone told by > your dev team, which means you may fire the person for "lack of > discipline") know that there is such a thing and in consequence > wouldn't use it. > > Don't tell your user not to use something, just don't tell them that > it exists and they won't use it. I am not familiar with the actual software, but judging from "we expose the spreadsheet object model to our users", I assume that users can discover the undocumented attributes, using Python's introspection features, like dir(obj), obj.__dict__, the inspect module, etc. So in this case, not telling them that the attributes exist, will not stop them from finding out. -- Hans Nowak (zephyrfalcon at gmail dot com) http://4.flowsnake.org/ From drakonik at gmail.com Fri Jun 27 20:19:00 2008 From: drakonik at gmail.com (Nick Dumas) Date: Fri, 27 Jun 2008 20:19:00 -0400 Subject: Do I need "self" and "other"? In-Reply-To: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Kurda Yon wrote: > Hi, > > I found one example which defines the addition of two vectors as a > method of a class. It looks like that: > > class Vector: > def __add__(self, other): > data = [] > for j in range(len(self.data)): > data.append(self.data[j] + other.data[j]) > return Vector(data) > > In this example one uses "self" and "other". Does one really need to > use this words? And, if yes, why? I have replaced "self" by "x" and > "other" by "y" and everything looks OK. Is it really OK or I can have > some problem in some cases? > > Thank you! In Python, when defining the methods of a class, you pass self as an argument to these methods so that they can have access to the class's variables and methods. Example: class Foo(): self.x = 5 def bar(self): print self.x def baz(): print self.x #This raises an error. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkhlg3QACgkQLMI5fndAv9gQZgCfRV15fQwGb9+n7Lz6JYmfXdeZ 0fYAn0fK90XfR7in/B9TjflwBRFcsgSS =qyXG -----END PGP SIGNATURE----- From deets at nospam.web.de Wed Jun 4 07:48:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 04 Jun 2008 13:48:09 +0200 Subject: new to python, looking for streams clues References: <58bb3360-daa5-4cf8-a3bf-93044ed189b1@x41g2000hsb.googlegroups.com> Message-ID: <6andovF38trhrU1@mid.uni-berlin.de> Thierry wrote: > Hello peoples, > > As I said, I'm new to python, and particularly to XML generation in > python. > Using the 4suite XML package, I have been able to produce XML, but > only directly to STDOUT. > > Refering to the 4suite markupWriter refrence, the class needs a stream > to output the generated XML, and if none is specified, it's the STDOUT > stream that is used. > > What I would like, would be to store the generated XML into a python > object which implement the stream interface to be able to transform it > via XSLT if needed (it's in a web based project). > > But, I've read the python doc for the last 12 hours without finding > anything about an existing object that implements that interface. > Am I missing something, or should I really create that object myself ? > > I mean, I just need something that I can write into and read > thereafter. > It should already exists, no ? See the modules StringIO and cStringIO - which are mentioned on http://docs.python.org/lib/lib.html with the words: 4.5 StringIO -- Read and write strings as files HTH, Diez From goldnery at gmail.com Wed Jun 4 14:14:02 2008 From: goldnery at gmail.com (Gandalf) Date: Wed, 4 Jun 2008 11:14:02 -0700 (PDT) Subject: how should i use this function? Message-ID: <99ed3c04-bd62-4456-ae12-eca4179005dc@r66g2000hsg.googlegroups.com> http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/PyCRichEditCtrl__GetSelText_meth.html GetSelText() I tried to import win32ui.PyCRichEditCtrl, But the shell told me their's no such module. If anyone can show me an example it would be great Thanks! From google at mrabarnett.plus.com Sat Jun 14 17:15:10 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 14 Jun 2008 14:15:10 -0700 (PDT) Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <0213909a-7888-4474-bd88-fc5f148f0abe@y38g2000hsy.googlegroups.com> Message-ID: <9a2940dc-a99e-4077-978b-8c9a400398d7@r66g2000hsg.googlegroups.com> On Jun 14, 4:05 pm, sturlamolden wrote: > On Jun 12, 3:48 pm, Mark wrote: > > > Is this possible? > > def foobar(user,score): > sums = {} > for u,s in zip(user,score): > try: > sums[u] += s > except KeyError: > sums[u] = s > return [(u, sums[u]) for u in sums].sort() > sort() sorts the list in-place and returns None. Try this instead: return sorted([(u, sums[u]) for u in sums]) or, better yet: return sorted(sums.items()) > usersum = foobar(user,score) > for u,s in usersum: > print "%d %d" % (u,s) From pavlovevidence at gmail.com Sun Jun 8 18:46:12 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 8 Jun 2008 15:46:12 -0700 (PDT) Subject: Q re documentation Python style References: Message-ID: <540d2d1d-d274-4614-a46c-4e372190791b@x41g2000hsb.googlegroups.com> On Jun 8, 5:17 pm, kj wrote: > I'm a Perlhead trying to learn the Way of Python. Welcome to the light, my son. > I guess this is a rambling way to ask: are docstrings *it* as far > Python documentation goes? Or is there a second, more flexible > system? You can define a decorator to inject the docstring; at least the docstring will not come between the function line and the body. Define the decorator like this: def doc(docstring): def inject_doc(function): function.func_doc = docstring return function return inject_doc And then you could do this: @doc("This is the docstring.") def some_function(): do_whatever() I think most tools that use docstrings actually execute the module, which means by the time the tool sees it the docstring will have been assigned, though I'm not sure they all do. Carl Banks From gh at ghaering.de Mon Jun 16 17:15:10 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 16 Jun 2008 23:15:10 +0200 Subject: sqlite3 and Python 2.5.1 In-Reply-To: <612ed26a-c6cf-4133-af6c-f256484e3928@x41g2000hsb.googlegroups.com> References: <612ed26a-c6cf-4133-af6c-f256484e3928@x41g2000hsb.googlegroups.com> Message-ID: <6bo3euF3c8etnU1@mid.uni-berlin.de> milan_sanremo wrote: > I have sqlite installed, but when I try to import sqlite3 I receive: > > Python 2.5.1 (r251:54863, Nov 3 2007, 02:54:36) [C] on sunos5 > Type "help", "copyright", "credits" or "license" for more information. >>>> import sqlite3 > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named sqlite3 > > Yet: > > # find /usr/local/python -name "sqlite*" -print > /usr/local/python/lib/python2.5/sqlite3 > > # /opt/csw/bin/sqlite3 > SQLite version 3.2.2 > Enter ".help" for instructions > sqlite> > > What is missing? You compiled Python yourself. During that, the SQLite3 header files could not be found, so the sqlite3 module was not compiled/installed. -- Gerhard From jason.scheirer at gmail.com Sat Jun 14 13:32:50 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Sat, 14 Jun 2008 10:32:50 -0700 (PDT) Subject: Was the move to Python 2.0 as big a deal? References: <4853f365$0$11601$607ed4bc@cv.net> Message-ID: <6bc70020-12ac-4474-9889-d18fee76ae5d@a9g2000prl.googlegroups.com> On Jun 14, 9:35?am, John Salerno wrote: > Just curious if people put up any resistance to 2.0 like some people do > for 3.0. Was it as big of a change in the language, or was the > transition smoother? It seems silly for anyone to say they would prefer > to stick with 1.x versions at this point, so perhaps we'll get there > with 3.0 eventually too. > > Anyway, I'm just trying to figure out if the whole "I don't like 3.0" > mentality (of some people, not all of course) is merely a result of it > still being new and not even released yet, and will completely go away > after a year or two; or if there really are such drastic changes that > people won't want to adopt it at all. A lot of the bigger changes and warts that have emerged in the past decade or so of the 2.0 series (text encoding madness anyone?) have been tabled until the 3.0 transition, so any compatibility breaks for the sake of fixing inconsistencies and ugliness in Python have been accruing and are finally being applied in 3.0. The 1.5->2.0 transition was a little strange, but I think a large reason that it was less painful was because the language was younger, less established and had far fewer people programming in it (and correspondingly smaller codebases) to transition over. From cdcasey at gmail.com Fri Jun 20 11:57:12 2008 From: cdcasey at gmail.com (chris) Date: Fri, 20 Jun 2008 08:57:12 -0700 (PDT) Subject: images on the web References: <2e72bd7d-9d33-43ba-8c08-ba3b39368466@z72g2000hsb.googlegroups.com> <485B4F31.6000104@mattnordhoff.com> <7n0si5-6u3.ln1@nb2.stroeder.com> Message-ID: <354be5d7-e86a-40e3-9cd0-b8a5ceead962@r66g2000hsg.googlegroups.com> On Jun 20, 1:52 am, Michael Str?der wrote: > Matt Nordhoff wrote: > > Matt Nordhoff wrote: > >> You could use data: URIs [1]. > > >> For example, a 43-byte single pixel GIF becomes this URI: > > >> > > >> They don't have universal browser support, but that might not be a > >> problem in this case. > > >> As for generating them with Python, I'm not sure... I just used Hixie's > >> data: URI kitchen [2] for the above example. > > >> [1] > >> [2] > > > Oh.. As > > shows, the reason I couldn't find a data: URI Python library is because > > they're utterly trivial to generate: > > > import base64 > > import urllib > > > raw_data = create_gif() > > uri = 'data:image/gif;base64,' + urllib.quote(base64.b64encode(raw_data)) > > > (And it's even simpler if you leave out the base64-encoding.) > > The caveat with URL schema data: is that the amount of data to be > transferred is significantly higher than including HTML tag > in your HTML source and let the browser fetch the raw binary image data > in a separate HTTP request (you also have to serve from your web > application). > > Ciao, Michael. This sounds like the way I want to go, it's just a matter of figuring it out. Is it just a matter of putting a function call in an img tag? I'll give the URI thing a try, too, From andymac at bullseye.apana.org.au Fri Jun 27 21:11:18 2008 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 28 Jun 2008 12:11:18 +1100 Subject: ImportError: DLL load failed In-Reply-To: <418cd5740806271120n5a43f5cfmd78a5c749b9e1eea@mail.gmail.com> References: <418cd5740806271120n5a43f5cfmd78a5c749b9e1eea@mail.gmail.com> Message-ID: <48658FB6.9040702@bullseye.andymac.org> Tony May wrote: > I'm having trouble importing when I run in Python. The hello world program > passes the test during the bjam build but gives an error about loading > the dll > when I import from a python script. > > first the test from running bjam. > ...patience... > ...found 1915 targets... > ...using 1 temp target... > ...updating 2 targets... > ...using \threading-multi>hello_ext.pyd... > > capture-output bin\hello.test\msvc-8.0express\debug\threading-multi\hello > 1 file(s) copied. > **passed** bin\hello.test\msvc-8.0express\debug\threading-multi\hello.test > ...updated 2 targets... > > then trying to run the script from python > I copied the pyd file and the rest of the output dir to c:\python25\dlls > > C:\Program Files\boost\boost_1_35_0\libs\python\example\tutorial>python > hello.py > > > Traceback (most recent call last): > File "hello.py", line 6, in > import hello_ext > ImportError: DLL load failed: This application has failed to start > because the a > pplication configuration is incorrect. Reinstalling the application may > fix this > problem. The DLL that's actually being imported by your script is not a Python extension module, as the modules initialisation function can't be found. Use the -v option on the Python command line to identify which DLL is actually being imported. You can then decide to move/rename.delete it or your own module as best fits your circumstances. -- ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From timothy.grant at gmail.com Sat Jun 14 15:10:10 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Sat, 14 Jun 2008 12:10:10 -0700 Subject: Creating a TCP/IP connection on already-networked computers In-Reply-To: <485413d0$0$4997$607ed4bc@cv.net> References: <4853f269$0$11615$607ed4bc@cv.net> <4854123f$0$5017$607ed4bc@cv.net> <485413d0$0$4997$607ed4bc@cv.net> Message-ID: On Sat, Jun 14, 2008 at 11:54 AM, John Salerno wrote: > John Salerno wrote: > > ----- >> #!/usr/bin/env python >> >> from socket import * >> from time import ctime >> >> HOST = '192.168.1.100' >> > > > ----- >> #!/usr/bin/env python >> >> from socket import * >> >> HOST = '192.168.1.100' >> > > A question about this. Is the "HOST" referring to the IP address of the > server computer in both of these cases? Because when I ran the program and > got to the part where it says "connected from:" on the server side, it shows > this same IP address. Shouldn't it be something different, since the > requests are coming from a different computer than the server computer? > > -- > http://mail.python.org/mailman/listinfo/python-list > John, It looks to me as if you're running both client and server on the same box, and in effect conecting to yourself. You asked in an earlier message if a friend on a different network could connect to you using your client programme and that depends on a LOT of things. Your friend certainly wouldn't be able to using the 192.168.x.x address as that is an unroutable address. But you would likely have a bit of work to do to get it to work through you and your friend's firewalls (that is likely a conversation for a later time though. -- Stand Fast, tjg. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Tue Jun 10 13:22:10 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 10 Jun 2008 10:22:10 -0700 (PDT) Subject: Python doesn't understand %userprofile% References: Message-ID: <16da3ad6-b51e-4552-99b4-93c31a8e9e27@59g2000hsb.googlegroups.com> On Jun 10, 11:11?am, Tim Golden wrote: > bsag... at gmail.com wrote: > > In xp when I try os.path.getmtime("%userprofile/dir/file%") Python > > bites back with "cannot find the path specified" Since my script has > > to run on machines where the username is unspecified I need a fix. > > Well I can see a few problems here. > > First is that putting percent signs around the whole path is > never going to work anyway. You want something like: > > "%USERPROFILE%/dir/file". > > Secondly, the expansion of environment variables like > USERPROFILE is done for you by the shell or the command > prompt. You have to do it for yourself if you're opening your > own files. You want something like: > > import os > print os.path.getmtime (os.path.join (os.environ['USERPROFILE'], "ntuser.ini")) > > But finally, what do you mean "run on machines where the username is > unspecified"? If you mean: where no user is logged in, then you won't > have a (meaningful) userprofile in any case: it might be the Default User > profile; I'm not sure. But is that what you want? > > You *can* use the functions in the win32profile module of the pywin32 > packages to find out various things about profiles directories, but things > can get quite complicated if users have roaming profiles and the like. > > TJG Tim, I'm surprised you didn't mention your excellent winshell utility. I use it for this sort of issue all the time where I need to update files on login and I don't know the user's name beforehand. The winshell.Desktop() one has been a life saver and I think the OP could probably use winshell for their problem. Or I may be completely off my rocker. Either way, here's the link: http://timgolden.me.uk/python/winshell.html Mike From thijs.triemstra at gmail.com Sun Jun 29 12:34:14 2008 From: thijs.triemstra at gmail.com (Thijs Triemstra | Collab) Date: Sun, 29 Jun 2008 09:34:14 -0700 (PDT) Subject: Docutils rst2html.py gives Unknown Directive type "toctree" References: Message-ID: Getting the same error in the apache logs here, no idea where it's coming from: [Sun Jun 29 18:25:50 2008] [error] :10: (ERROR/3) Unknown directive type "toctree". [Sun Jun 29 18:25:50 2008] [error] [Sun Jun 29 18:25:50 2008] [error] .. toctree:: [Sun Jun 29 18:25:50 2008] [error] :maxdepth: 2 [Sun Jun 29 18:25:50 2008] [error] [Sun Jun 29 18:25:50 2008] [error] :16: (ERROR/3) Unknown interpreted text role "ref". [Sun Jun 29 18:25:50 2008] [error] :17: (ERROR/3) Unknown interpreted text role "ref". [Sun Jun 29 18:25:50 2008] [error] :18: (ERROR/3) Unknown interpreted text role "ref". On Jun 19, 11:19?pm, "Calvin Cheng" wrote: > Hi, > > I am attempting to convert a bunch of .txt files into html using the > docutils package. > > It works for most of the txt files except for the index.txt file which > gives 2 errors: > (1) Unknown Directive type "toctree" > (2) (ERROR/3) Unknown interpreted text role "ref". > > Any idea how I can fix this? > > Would be glad if someone who is familiar with docutils could point me > in the right direction. > > Thank you, > Calvin From t_spens at yahoo.com Fri Jun 27 12:57:06 2008 From: t_spens at yahoo.com (Tim Spens) Date: Fri, 27 Jun 2008 09:57:06 -0700 (PDT) Subject: embedding and extending python C API registering callback handler objects In-Reply-To: <24081.19905.qm@web45113.mail.sp1.yahoo.com> Message-ID: <393211.31628.qm@web45115.mail.sp1.yahoo.com> --- On Fri, 6/27/08, Tim Spens wrote: > From: Tim Spens > Subject: Re: embedding and extending python C API registering callback handler objects > To: python-list at python.org, "Matimus" > Date: Friday, June 27, 2008, 9:16 AM > thanks, but didn't fix the problem. > > > --- On Fri, 6/27/08, Matimus > wrote: > > > From: Matimus > > Subject: Re: embedding and extending python C API > registering callback handler objects > > To: python-list at python.org > > Date: Friday, June 27, 2008, 9:03 AM > > On Jun 27, 8:22 am, Tim Spens > > > wrote: > > > Hello all, > > > > > > I've been trying to get an example found > > > herehttp://codeidol.com/python/python3/Embedding-Python/Registering-Callb... > > > to work. Every thing works fine except when I > try to > > trigger an event from c that will call a python > function. > > Here is my test code: > > > > > > //-----------------------python > > code--------------------------// > > > #! /usr/bin/env python > > > import time > > > import callback > > > > > > def callback1(label,count): > > > print 'callback1 successfully > > triggered from python via callback.so' > > > return 'callback1 => %s number > > %i' % (label, count) > > > > > > def callback2(label,count): > > > return 'callback2 => ' + > > label * count > > > > > > print '\nTest1:' > > > callback.setHandler(callback1) > > > callback.triggerEvent() # simulate events > > caught by C layer > > > > > > print '\nTest2:' > > > callback.setHandler(callback2) > > > > > > print 'Waiting for callback2 to be called > from > > c:' > > > while 1: > > > time.sleep(.001) > > > > > > //-----------------------c > > code-------------------------------// > > > #include > > > #include > > > > > > /* keep Python object in C */ > > > static PyObject *Handler = NULL; > > > > > > void Route_Event(char *label, int count){ > > > char *cres; > > > PyObject *args, *pres; > > > /* call Python handler */ > > > args = Py_BuildValue("(si)", label, > > count); > > > pres = PyEval_CallObject(Handler, args); > > > Py_DECREF(args); > > > if (pres != NULL){ > > > /* use and decref handler result */ > > > PyArg_Parse(pres, "s", > > &cres); > > > printf("%s\n", cres); > > > Py_DECREF(pres); > > > > > > }} > > > > > > // the actual python callback call > > > static PyObject * > > > make_call(PyObject *function, PyObject *args){ > > > if (function == NULL) return NULL; > > > PyObject * val = > PyObject_CallObject(function, > > args); > > > Py_XDECREF(args); > > > return val; > > > > > > } > > > > > > static PyObject * > > > Register_Handler(PyObject *self, PyObject *args){ > > > /* save Python callable object */ > > > Py_XDECREF(Handler); > > > PyArg_Parse(args, "O", > &Handler); > > > Py_XINCREF(Handler); > > > Py_INCREF(Py_None); > > > return Py_None; > > > > > > } > > > > > > static PyObject * > > > Trigger_Event(PyObject *self, PyObject *args){ > > > /* let Python simulate event caught by C */ > > > static int count = 0; > > > Route_Event("spam", count++); > > > Py_INCREF(Py_None); > > > return Py_None; > > > > > > } > > > > > > static struct PyMethodDef callback_methods[] = { > > > {"setHandler", > Register_Handler}, > > /* name, address */ > > > {"triggerEvent", Trigger_Event}, > > > {NULL, NULL}}; > > > > > > > > /* on first "import callback" */ > > > void initcallback(){ /* this > > is called by Python */ > > > (void) Py_InitModule("callback", > > callback_methods); > > > > > > } > > > > > > int main(){ > > > while (1){ > > > printf("1\n"); > > > //attempting to call callback2 > > which is registered to Handler > > > //i've also tried args = > > Py_BuildValue("(si)", label, count); here > but I > > get a segfault. > > > PyObject *args = > > Py_BuildValue("s","c code"); > > > printf("2\n"); > > > PyObject* val = > > make_call(Handler,args); > > > printf("3\n"); > > > Py_XDECREF (val); > > > printf("4\n"); > > > sleep(1); > > > > > > }} > > > > > > //------------------------compiler > > stuff----------------------// > > > gcc callback.c -c -g -Wall -fpic -I > > /usr/include/python2.5 -o callback.o > > > gcc callback.c -g -Wall -I /usr/include/python2.5 > -L > > /usr/local/lib -lpython2.5 -o callback > > > gcc -shared -Wall callback.o -o callback.so > > > > > > //------------------------test code > > results-------------------// > > > ../callback.py > > > Test1: > > > callback1 successfully triggered from python via > > callback.so > > > callback1 => spam number 0 > > > > > > Test2: > > > Waiting for callback2 to be called from c: > > > #NOTHING EVER GETS PRINTED HERE CALLBACK NEVER > GETS > > CALLED? > > > > > > ../callback > > > 1 > > > 2 > > > 3 > > > 4 > > > .... > > > > > > Thanks, > > > Tim > > > > Maybe you just need to flush the stdout buffer in > python. > > `sys.stdout.flush()` > > > > Matt > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > http://mail.python.org/mailman/listinfo/python-list I think I know where the problem is but I'm unsure how to fix it. When I call Register_Handler(...) from python via callback.setHandler1(callback1) this only seems to affect pythons ability to trigger an "event" in c. PyObject *Handler is always NULL even after I call Register_Handler(...). I thought there was some magic here that was assigning the pointer *Handler to my python callback1 handler so it could be triggered from c? -Tim From gnewsg at gmail.com Fri Jun 6 10:23:31 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Fri, 6 Jun 2008 07:23:31 -0700 (PDT) Subject: Partial download with ftplib and retrbinary References: <9dd32f80-ce21-4c2c-8eba-1afd3b80379f@x41g2000hsb.googlegroups.com> Message-ID: <905eff9f-bc91-4f99-83df-7a89fd936b27@f63g2000hsf.googlegroups.com> On 24 Mag, 12:53, fepeac... at googlemail.com wrote: > I am breaking/interrupting my connection with theftpserver at > present when doing a partial download of a file. I have a callback > with retrbinary that raises an exception and ends the download. The > problem is that the server is not notified and hangs. I cannot send > any further commands and need to relogin to download further. Is there > a way to still continue downloading without having to login again. > > My retrbinary function is: > > ftp.retrbinary('RETR '+file, handleDownload,1,bound[0]) > > where bound[0] is an integer specifying the start byte of the > download. > > My callback is: > > def handleDownload(block): > ? ? global count,localfile,number > ? ? localfile.write(block) > ? ? if count==number: > ? ? ? ? ? ? raise(Exception) > ? ? count=count+1 > > where number specifies the number of bytes to download. > > Help would be gratefully received. The server hangs on because the data connection is left open. Unfortunately you have no easy way to close the data connection by using retrbinary. You have to trick a little bit and keep a reference of the data socket and manually close it. The example below starts to retrieve a file and stops when 524288 bytes have been received. Hope this could help you. import ftplib ftp = ftplib.FTP('127.0.0.1', 'user', 'password') ftp.voidcmd('TYPE I') conn = ftp.transfercmd('RETR filename') # the data socket bytes_recv = 0 while 1: chunk = conn.recv(8192) # stop transfer while it isn't finished yet if bytes_recv >= 524288: # 2^19 break elif not chunk: break file.write(chunk) bytes_recv += len(chunk) conn.close() --- Giampaolo http://code.google.com/p/pyftpdlib From kyosohma at gmail.com Thu Jun 19 14:50:19 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 19 Jun 2008 11:50:19 -0700 (PDT) Subject: python/ruby question.. References: <3b017f08-2d42-4c65-9003-19ffc606234d@l64g2000hse.googlegroups.com> Message-ID: <5ea57226-c622-46b5-b792-d95604b1aebe@q24g2000prf.googlegroups.com> On Jun 19, 11:49?am, a... at pythoncraft.com (Aahz) wrote: > In article , > Matt Nordhoff ? wrote: > > > > >You're supposed to use the subprocess module. > > Really? ?Sez who? > > $ python > Python 2.3.4 (#1, Feb ?2 2005, 12:11:53) > [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> import subprocess > > Traceback (most recent call last): > ? File "", line 1, in ? > ImportError: No module named subprocess > -- > Aahz (a... at pythoncraft.com) ? ? ? ? ? <*> ? ? ? ?http://www.pythoncraft.com/ > > "as long as we like the same operating system, things are cool." --piranha The subprocess module supercedes os.popen*, os.system, commands and a few others in Python 2.4+. Thus, those others are deprecated. See the docs here: http://docs.python.org/lib/module-subprocess.html Mike From bjourne at gmail.com Tue Jun 3 06:07:43 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 3 Jun 2008 12:07:43 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> Message-ID: <740c3aec0806030307ld7078bfv15ba2a920d2590e2@mail.gmail.com> On Mon, Jun 2, 2008 at 10:50 PM, Russ P. wrote: > On Jun 2, 6:41 am, Carl Banks wrote: > >> You are not realizing that only useful(**) thing about data hiding is >> that some code has access to the data, other code does not. If you >> "hide" data equally from everyone it's just a useless spelling change. > > I think you're missing the point. > > As I see it, the primary value of data hiding is that it provides > useful information on which data and methods are intended for the > client and which are intended for internal use. It's like putting a > front panel on a TV set with the main controls intended for the > viewer. Here's my two cents. First of all, a TV is a bad analogy compared to reusable software libraries. Really bad analogy. A TV is a horribly complicated device which has to be dumbed down because otherwise it would be to hard to use for ordinary people. A software developers relation to a third party library is more similar to a TV repair man trying to repair a TV than to a random person watching TV. For a repair man, the front panel is just useless and in the way. Oh, and to continue on the TV analogy, one of the reason why a TV is complicated is because its interface is totally different from its implementation. Channels are just a bad abstraction for tuning the receiver to different frequencies and for switching inputs. Merely using a TV doesn't teach you anything about how it actually works. KISS: Keep It Simple Stupid. And it is always simpler to not implement the gunk needed for data hiding than to do it. By keeping things simple you keep your code easy to implement, easy to understand and easy to reuse. Data hiding sacrifices implementation simplicity supposedly to make the interface simpler and to keep backwards compatibility. It allows you to change implementation details without affecting the interface. But do you really want to do that? Consider this silly Java example: class Foo { private int bar; public int getBar() { return bar; } }; Then for some reason you decide that hm, "bar" is not a good attribute name so you change it to "babar". And you can do that without changing the public interface! Woho! So now you have a public getter named "getBar" that returns an attribute named "babar". That's in reality just bad and whoever is maintaining the implementation is going to be annoyed that the getters name doesn't match the attribute name. What would have happened without data hiding? Renaming the public attribute "bar" to "babar" probably cause some grief for someone reusing your library, but you would keep your implementation pure. What about semantic changes? Data hiding doesn't protect you against that, so you'll have to change your interface anyway. The interface for a car hasn't changed much in the last 100 years, but the implementation has. How easy is it to repair a car nowadays compared to 30 years ago? And data hiding as a documentation aid is just a sham. "These methods are public so you can call them, these aren't so hands off!" A reuser of your library *will* want to know what happens on the inside, by trying to make stuff impossible to reach you are just making that kind of information much harder to come by. The better method is to just write proper docstrings that tell the user what the methods do and when they can be called. Another good way to see how useless data hiding is, is to try and unit test a very encapsulated library. You'll see that it is almost impossible to write good unit tests unless you publicly export almost everything in the code. At which point you come to realize that all the data hiding was for naught. -- mvh Bj?rn From circularfunc at yahoo.se Mon Jun 23 13:54:21 2008 From: circularfunc at yahoo.se (cirfu) Date: Mon, 23 Jun 2008 10:54:21 -0700 (PDT) Subject: IDE on the level of Eclipse or DEVc++? References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> Message-ID: i downloaded the extension for eclipse, nice. any opinions of netbeans vs eclipse for python? From mario at ruggier.org Sat Jun 28 06:34:14 2008 From: mario at ruggier.org (mario) Date: Sat, 28 Jun 2008 03:34:14 -0700 (PDT) Subject: Mako vs. Cheetah? References: <4862f57c$0$11621$607ed4bc@cv.net> <4863bf9c$0$14081$c3e8da3@news.astraweb.com> Message-ID: <11fd5899-1c13-4feb-966d-69bbc43317c2@m3g2000hsc.googlegroups.com> A small and ultra-lightweight system, with all the power of any fully featured text-based templating system (such as mako or cheetah) and then some (no constraints on template file names or formats, restricted execution, automatic XSS protection, ...) that can be used in a web context or standalone, while being also incredibly fast, is Evoque Templating: http://evoque.gizmojo.org/ And the simplicity of the system means you can assimilate the entire thing in a single sitting, and thereafter easily remember the few key things to continue using it without constant re-consulting of the docs (that, actually, are also pretty good ;-) So yes, agree with you entirely, that shameless personal preference is important for choosing your templating system... ;) mario From john.gerald.mason at gmail.com Sun Jun 1 15:55:45 2008 From: john.gerald.mason at gmail.com (Mason) Date: Sun, 1 Jun 2008 12:55:45 -0700 (PDT) Subject: convert binary to float Message-ID: <0c15e8e1-948b-4bd6-a312-b1e055da859e@t54g2000hsg.googlegroups.com> I have tried and tried... I'd like to read in a binary file, convert it's 4 byte values into floats, and then save as a .txt file. This works from the command line (import struct); In [1]: f = open("test2.pc0", "rb") In [2]: tagData = f.read(4) In [3]: tagData Out[3]: '\x00\x00\xc0@' I can then do the following in order to convert it to a float: In [4]: struct.unpack("f", "\x00\x00\xc0@") Out[4]: (6.0,) But when I run the same code from my .py file: f = open("test2.pc0", "rb") tagData = f.read(4) print tagData I get this (ASCII??): ?@ I only know how to work with '\x00\x00\xc0@'. I don't understand why the output isn't the same. I need a solution that will allow me to convert my binary file into floats. Am I close? Can anyone point me in the right direction? Thanks, Mason From grante at visi.com Wed Jun 11 14:34:59 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 11 Jun 2008 13:34:59 -0500 Subject: problems with opening files due to file's path References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> <77acc29a-fffa-44d6-b07b-6bcf8b5bdd74@h1g2000prh.googlegroups.com> Message-ID: On 2008-06-11, Alexnb wrote: > Okay, so as a response to all of you, I will be using the Entry() widget in > Tkinter to get this path. OK. > and the repr() function just makes all my backslashes 4 > instead of just 1, and it still screwes it up with the numbers > and parenthesis is has been since the first post. I've absolutely no clue why you would be using the repr() function. > Oh and I know all about escape characters, (\n,\b,\a,etc.) Apparently not. > I can program C, not a lot, but enough to know that I like > python better. Anyway, so far I tried all of your stuff, and > it didn't work. To what does "it" refer? > infact, it puts backslashes in front of the > "'" in some of the words, such as "I'm" goes to "I\'m." Again, "it" doesn't seem to have a concrete referant. > So I posted the code I will be using if you want to see the > Tkinter code I can post it, but I don't see how it will help. If you know what would help and what wouldn't, then you must know enough to fix your problems. So please do so and quit bothering the newgroup. -- Grant Edwards grante Yow! I want another at RE-WRITE on my CEASAR visi.com SALAD!! From eckhardt at satorlaser.com Thu Jun 19 11:49:13 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 19 Jun 2008 17:49:13 +0200 Subject: Simple Python class questions References: <8549940b-e909-4bc6-b9a1-ea7d14284785@z16g2000prn.googlegroups.com> Message-ID: Lie wrote: > I think it's not that hard to see that it's just a pseudo code "...in comms.py I have: ..." actually explicitly says that it is actual code from a file. *shrug* Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From franck110 at gmail.com Sun Jun 1 22:42:55 2008 From: franck110 at gmail.com (Franck Y) Date: Sun, 1 Jun 2008 19:42:55 -0700 (PDT) Subject: Better performance Message-ID: <5ef6911e-c7ec-4eb5-8a53-ee59d5a36817@l64g2000hse.googlegroups.com> Hello Folks, I am facing a problem where i need to parse around 200 files, i have a bit of knowledge in PHP/Perl/Python (the magic P :-P) Which one would you suggest me since i have to generate a web interface ? And each one has his area of 'work' Thanks for your help ! From mensanator at aol.com Fri Jun 13 17:13:06 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 13 Jun 2008 14:13:06 -0700 (PDT) Subject: Python 3000 vs. Python 2.x References: <2c299cdc-adcd-4540-b09f-43b4147e10ca@y21g2000hsf.googlegroups.com> Message-ID: <5087e578-ef11-48c5-97ec-68c4d9d95024@a1g2000hsb.googlegroups.com> On Jun 13, 4:04?pm, mr.opus.peng... at gmail.com wrote: > As a new comer to Python I was wondering which is the best to start > learning. ?I've read that a number of significant features have > changed between the two versions. ?Yet, the majority of Python > programs out in the world are 2.x and it would be nice to understand > those as well. ?Thanks for all the help. > > Creosote, What 3rd party modules are you planning to use? You won't be able to use them until their developers release Python 3000 versions. In my research, I heavily depend on the gmpy module for fast, number theoretic functions. Last time I checked, it was only available for v2.5. So, I could install v2.6 or v3.0, but I wouldn't be able to run any of my programs, so what would be the point? From deets at nospam.web.de Mon Jun 9 17:46:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 09 Jun 2008 23:46:31 +0200 Subject: Does the python library of Google Data API is truly free? In-Reply-To: <3a296d00-d4e0-4f03-b6b3-bef4c5d628dd@x35g2000hsb.googlegroups.com> References: <3ac654b2-61b4-44ce-8e03-75f2344d5869@s50g2000hsb.googlegroups.com> <6fb57ab1-b0d2-4b7d-93c1-b919ca0e51a0@i36g2000prf.googlegroups.com> <3a296d00-d4e0-4f03-b6b3-bef4c5d628dd@x35g2000hsb.googlegroups.com> Message-ID: <6b5mloF3aeui4U1@mid.uni-berlin.de> Kless schrieb: > On 9 jun, 21:40, Lie wrote: >> Do you notice that the terms are for the SERVICE not for the SOFTWARE. >> The terms for the service is quite reasonable, as I see it. >> The software itself is governed by the Apache License 2.0, detailed >> here:http://www.apache.org/licenses/LICENSE-2.0 > > Well, it's used a free license to access to a service that is not free > -it's owner and too restrictive-. And it isn't nothing reasonable that > Google get many rights about your content, and that you have not any > right about the rest of the content. > > This goes against the free software, considering that a service is > software. This is nonsense. If a hosting provider offers you free hosting based on linux - and then goes out of business or is forced to charge money - do you say "that's against free software?" Or if they prohibit you to host malicious, offending or otherwise problematic content served by the free apache - is that "against free software?" A service is a service. It is offered as is, under whatever conditions the provider likes it. Offering a convenient way to access the service using a FOSS license is good style. But you aren't forced to use that, you can write your own. But that doesn't change the terms and conditions of the service itself. Diez From deets at nospam.web.de Thu Jun 12 04:58:28 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 12 Jun 2008 10:58:28 +0200 Subject: Please recommend a blog program written using python-cgi References: <4f16f948-1082-4d3a-9276-cac97945c96b@x1g2000prh.googlegroups.com> Message-ID: <6bc6qrF3asvdfU2@mid.uni-berlin.de> Royt wrote: > Hi, I'm a newbie to Python, but I think it won't be too hard to learn. > A few days ago I registered Google App Engine, it only support Python > 2.5. I want to set my blog on it soon. But it's not easy for me to > finish it in a short time since I'm not very familiar with Python, so > I want find some codes available, throught reading the code, I can > learn something from it. I know there are many frameworks for web > development, but I just want the code using traditional CGI method, > it's easy to use and it doesn't require any additional knowledge about > framework. I need a simple example (support basic function of a > weblog, easy to revise) but not a complicated huge monster (I don't > think such a thing now exists). I guess you are out of luck. Usually people use frameworks because it *does* make work easier. AFAIK google engine supports Django. So try & aquaint you with that - and I bet there are Django-based blogs out there. Diez From dev at projekt01.ch Thu Jun 19 17:15:43 2008 From: dev at projekt01.ch (Roger Ineichen) Date: Thu, 19 Jun 2008 23:15:43 +0200 Subject: AW: [Zope3-Users] Python Package Construction In-Reply-To: <1213901807.2875.95.camel@localhost.localdomain> References: <1213901807.2875.95.camel@localhost.localdomain> Message-ID: Hi Tim > Betreff: [Zope3-Users] Python Package Construction > > Hi All, > > I would like feedback on the proper/best 'Pythonic' approach. > > This is a rather subjective question. Where is the trade-off > between package name lengths and faithfulness to the specifications? > > [Discussion follows] > > I am implementing a set of specifications for healthcare IT > for Python programmers to be able to develop interoperable > healthcare applications. > I am using ZCA (aka.Zope3) extensively. > > My desire is to implement the specs as faithfully as possible for two > reasons: > 1) teachability - how easy/difficult is it to teach the > framework and specifications to new developers? > 2) maintainability - which approach, if either, will make it > easier to maintain the framework if/when the specifications change? > > My first pass was to develop a skeleton of the specs using > Interfaces from the ZCA approach and then the implementations > following the document structure of the specs. > > The specs are available via SVN at: > http://www.openehr.org/svn/specification/TRUNK/publishing/arch > itecture/ > > It is best to probably use real examples. Following the > document structure for packaging AND using the ZCA convention > of having a sub-directory for interfaces caused massive > circular import issues due to some classes being used in the > interface definition of classes inside the same interface > file being imported into the implementation file. If that > sounds confusing; it is. It was confusing to write too. :-) > If anyone has questions I'll try to expand. > > It is best to probably use specific, real examples. > http://www.openehr.org/svn/specification/TRUNK/publishing/arch > itecture/rm/data_types_im.pdf > > (note class names are converted from the upper case, > underscore separated style to CamelCase) > > The package openehr.rm.datatypes.text defines the > implementation class CodePhrase. The associated interface > file openehr.rm.datatypes.interfaces.text needed CodePhrase > as an attribute type in DvCodedText and TermMapping needs > both CodePhrase and DvCodedText. This quickly got out of control. > > So my solution to solving the circular imports is to take > each interface and implementation and put them into one file. > Research tells me that this is probably the second mostly > popular ZCA approach. So, ICodePhrase and CodePhrase are now > in openehr/rm/datatypes/codephrase.py, DvCodeText and > IDvCodedText in openehr/rm/datatypes/dvcodedtext.py, etc. > > But wait, now I don't have a 'text package'. So if > codephrase.py and dvcodedtext.py were in > openehr/rm/datatypes/text/ that would solve the problem. > BUT! Throughout the specs many of the names are VERY long > already. Adding another package name that is from 4 - 15 (or > more) characters long adds to the length of already long > import statements, i.e. > > (sorry for the email line wraps) > > from openehr.am.archetype.creferenceobject import > ICReferenceObject,CReferenceObject > > should really be > > from openehr.am.archetype.constraintmodel.creferenceobject > import ICReferenceObject,CReferenceObject > > Thoughts, opinions and jeers all gratefully accepted. :-) For a usecase like this, I personaly recommend to defina all interfaces in one module which probably is a namespace if you need alot of interfaces to define. e.g. openehr.interfaces.foobar.IFooBar the reason why: - spearate interface from implementation. That's an important aspect in a component architecture. If you define your implementation and interfaces in one file, then you don't need a component architecture. - interfaces are separated in a well know place. This means if you define a module and you like to import an interface you can import just one line: from openehr import interfaces Which makes it very simple. Regards Roger Ineichen > --Tim > > > > > > > > > > -- > Timothy Cook, MSc > Health Informatics Research & Development Services LinkedIn > Profile:http://www.linkedin.com/in/timothywaynecook > Skype ID == timothy.cook > ************************************************************** > *You may get my Public GPG key from popular keyservers or * > *from this link http://timothywayne.cook.googlepages.com/home* > ************************************************************** > From eric.talevich at gmail.com Mon Jun 2 18:02:49 2008 From: eric.talevich at gmail.com (etal) Date: Mon, 2 Jun 2008 15:02:49 -0700 (PDT) Subject: Merging ordered lists References: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> Message-ID: <8140b81b-bfa1-463b-a92a-19c0f6453444@k30g2000hse.googlegroups.com> On Jun 1, 1:49?am, Peter Otten <__pete... at web.de> wrote: > Peter Otten wrote: > > #untested > > Already found two major blunders :( > > # still untested > import difflib > > def _merge(a, b): > ? ? sm = difflib.SequenceMatcher(None, a, b) > ? ? for op, a1, a2, b1, b2 in sm.get_opcodes(): > ? ? ? ? if op == "insert": > ? ? ? ? ? ? yield b[b1:b2] > ? ? ? ? elif op == "replace": > ? ? ? ? ? ? yield a[a1:a2] > ? ? ? ? ? ? yield b[b1:b2] > ? ? ? ? else: # delete, equal > ? ? ? ? ? ? yield a[a1:a2] > > def merge(a, b): > ? ? return sum(_merge(a, b), []) > > def merge_to_unique(sources): > ? ? return unique(reduce(merge, sorted(sources, key=len, reverse=True))) > difflib.SequenceMatcher looks promising; I'll try it. Thanks! > def unique(items): > ? ? u = set(items) > ? ? if len(u) == len(items): > ? ? ? ? return items > ? ? result = [] > ? ? for item in items: > ? ? ? ? if item in u: > ? ? ? ? ? ? result.append(item) > ? ? ? ? ? ? u.remove(item) > ? ? return result You did right by preserving the original (non-alphabetical) ordering, but I'm less enthusiastic about the shape of this function. My original function used 7 lines of code, and only 1 for the unique() step. This uses up to three container objects. Is it really an improvement? (Secret: the reference list (or, any of the sources) is unlikely to be more than a few dozen elements long. The data set that puts merge_to_unique through a workout will be a giant list of comparatively short lists, so the unique() part just needs to be short and conceptually clean, while merge() should attempt sane behavior for large len(sources).) From mnordhoff at mattnordhoff.com Fri Jun 13 18:38:04 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 13 Jun 2008 22:38:04 +0000 Subject: Python 3000 vs. Python 2.x In-Reply-To: <2c299cdc-adcd-4540-b09f-43b4147e10ca@y21g2000hsf.googlegroups.com> References: <2c299cdc-adcd-4540-b09f-43b4147e10ca@y21g2000hsf.googlegroups.com> Message-ID: <4852F6CC.5040303@mattnordhoff.com> mr.opus.penguin at gmail.com wrote: > As a new comer to Python I was wondering which is the best to start > learning. I've read that a number of significant features have > changed between the two versions. Yet, the majority of Python > programs out in the world are 2.x and it would be nice to understand > those as well. Thanks for all the help. > > Creosote, You should learn Python 2. Python 3 is only in alpha/beta, and it won't be very relevant for several years. Python 3 isn't a whole new language; it just breaks backwards compatibility to clean up old warts and make other improvements. It won't be too hard to transition to it when you decide to. -- From M8R-yfto6h at mailinator.com Mon Jun 23 23:38:51 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Mon, 23 Jun 2008 20:38:51 -0700 Subject: String question References: <695fec18-8a3a-48e1-b467-d4957f9065fa@26g2000hsk.googlegroups.com> Message-ID: "Andreu" wrote in message news:g3p72i$432$1 at aioe.org... > Yes, ... don't ask me why, but in fact v1,v2,v3 = str1.split() > does not seem to work. My original problem was I forgot about > the parenthesis as Tim point out. So I ended up converting to a > list as in: v = str1.split() and accessing the elements using > v[0] v[1] ect...it is working now. Thanks. > > Andreu. v1,v2,v3 = str1.split() will only work if there are exactly three things in str1. >>> s = 'this is a test' >>> v1,v2,v3 = s.split() Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack >>> v1,v2,v3 = s.split(' ',2) # limit to two splits maximum >>> v1 'this' >>> v2 'is' >>> v3 'a test' -Mark From tjreedy at udel.edu Fri Jun 13 17:51:14 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 13 Jun 2008 17:51:14 -0400 Subject: Point Of intersection between two plotted functions References: <2fd19881-27f8-48f3-bfa9-2d8a26f31920@26g2000hsk.googlegroups.com> Message-ID: wrote in message news:2fd19881-27f8-48f3-bfa9-2d8a26f31920 at 26g2000hsk.googlegroups.com... | Is there anyway one could find ot the point of intersection between | any two plotted functions Assume you have sequence xi, yi, zi, where yi and zi are function values corresponding to xi. In general, you will never have exact intersection with yi==zi. So in addition, look for successive triples xi,yi,zi and x(i+1), y(i+1), z(i+1) such that yiz(i+1) or the other way around. In other words, zi-yi and z(i+1)-y(i+1) have opposite signs. You might want to also consider abs(zi-yi) < some very small number as possibly indicating touching without crossing (as with tangents). From george.sakkis at gmail.com Wed Jun 18 17:34:39 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 18 Jun 2008 14:34:39 -0700 (PDT) Subject: extra positional arguments before optional parameters syntax References: Message-ID: <4450093c-874f-420f-8d0b-09fbf6f07574@p25g2000hsf.googlegroups.com> On Jun 18, 5:25 pm, MisterWilliam wrote: > I noticed that in PEP 3105, the PEP about turning print to print(), > the syntax for print() is defined as follows: > def print(*args, sep=' ', end='\n', file=None) > > Ignoring the fact that print is a reserved keyword in python, this is > not valid python because extra positional arguments (*args), cannot > come before optional parameters (sep=' ', end='\n', file=None). > > >>> def f(*args, sep=' ', end='\n', file=None): > > File "", line 1 > def f(*args, sep=' ', end='\n', file=None): > ^ > SyntaxError: invalid syntax > > Am I misunderstanding something? Is this type of syntax suppose to be > allowed in a future version of Python? (I can't find anything about > this through my searching.) You didn't search hard enough; it's three PEPs earlier: http://www.python.org/dev/peps/pep-3102/ George From steven.p.clark at gmail.com Wed Jun 25 22:38:54 2008 From: steven.p.clark at gmail.com (Steven Clark) Date: Wed, 25 Jun 2008 22:38:54 -0400 Subject: struct.pack behavior In-Reply-To: References: Message-ID: <663744510806251938x7de7e56dg1e2f1ade0892da50@mail.gmail.com> On Wed, Jun 25, 2008 at 7:03 PM, John Machin wrote: > On Jun 26, 9:00 am, "Steven Clark" wrote: >> Can anyone explain to me why >> struct.pack('HB',1,2) gives 3 bytes, whereas struct.pack('BH',1,2) >> gives 4 bytes? >> > Alignment -- read the manual. > -- > http://mail.python.org/mailman/listinfo/python-list > If "the manual" is the help files for the struct module, I've read it several times over. I understand endianness; I don't understand alignment. Could anyone give a less cryptic / terse answer? From phillip.oldham at gmail.com Fri Jun 13 03:38:09 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Fri, 13 Jun 2008 00:38:09 -0700 (PDT) Subject: Comments on my first script? References: <7e3a7c92-6204-46dd-8df8-90218f2fb314@26g2000hsk.googlegroups.com> <4016716e-0ff7-41aa-951a-ed9562ff2ac8@m44g2000hsc.googlegroups.com> Message-ID: <7bb26acf-8b58-4d29-8e64-05a75eb5e584@d45g2000hsc.googlegroups.com> Thanks guys. Those comments are really helpful. The odd semi-colon is my PHP background. Will probably be a hard habbit to break, that one! ;) If I do accidentally drop a semi-colon at the end of the line, will that cause any weird errors? Also, Chris, can you explain this: a, b = line.split(': ')[:2] I understand the first section, but I've not seen [:2] before. From mcashcash at gmail.com Wed Jun 4 08:03:51 2008 From: mcashcash at gmail.com (mcashcash at gmail.com) Date: Wed, 4 Jun 2008 05:03:51 -0700 (PDT) Subject: Earn = 10,000 US Dollars per month without Investment. Message-ID: <704df407-1108-430c-a2e5-c4860062b52d@i18g2000prn.googlegroups.com> You Have Finally Found It Earn!! = 10,000 US Dollars per month without Investment Genuine Lifetime Income!! http://seniorfriendfinder.com/go/g970599-pmem http://seniorfriendfinder.com/go/g970599-pct http://seniorfriendfinder.com/go/g970599-brk http://alt.com/go/g900909-ppc http://govindswamy-govindaswamy.blogspot.com http://govindaswamy-amman.blogspot.com From francis.girardpython at gmail.com Wed Jun 18 08:27:07 2008 From: francis.girardpython at gmail.com (Francis Girard) Date: Wed, 18 Jun 2008 08:27:07 -0400 Subject: Interpreting string containing \u000a In-Reply-To: References: Message-ID: Thank you very much ! I didn't know about this 'unicode-escape'. That's great! Francis 2008/6/18 Duncan Booth : > "Francis Girard" wrote: > > > I have an ISO-8859-1 file containing things like > > "Hello\u000d\u000aWorld", i.e. the character '\', followed by the > > character 'u' and then '0', etc. > > > > What is the easiest way to automatically translate these codes into > > unicode characters ? > > > > >>> s = r"Hello\u000d\u000aWorld" > >>> print s > Hello\u000d\u000aWorld > >>> s.decode('iso-8859-1').decode('unicode-escape') > u'Hello\r\nWorld' > >>> > > -- > Duncan Booth http://kupuguy.blogspot.com > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hat at se-162.se.wtb.tue.nl Wed Jun 25 02:57:38 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 25 Jun 2008 08:57:38 +0200 Subject: Problem found in tutorial References: Message-ID: On 2008-06-25, John W. Hamill wrote: > 20JUN2008 > By John W. Hamill > > > Errata found in Python tutorial > http://www.python.org Bugs and other problems should be reported in bugs.python.org Otherwise they will probably get lost. > Error Found by John W. Hamill > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > - - > C:\__jh\ftp\python\2_5_2\doc\tutorial\node11.html Next time, please also add a URL that is usable for a larger group of people than those that have access to your C: drive. (Generator expression examples, Section 9.11, see http://docs.python.org/tut/node11.html#SECTION00111100000000000000000) >>>> unique_words = set(word for line in page for word in line.split()) > >>>> valedictorian = max((student.gpa, student.name) for student in > graduates) > > NOTE: page and graduates are not defined and this won't run without them. > I defined them like so to make this work: Correctly seen. Report at bugs.python.org ! > page = ("The quick brown","fox jumped over","the lazy dog's","back 123 > times." ) > > class Graduate: Always derive new classes from object as in class Graduate(object): > def __init__(self, name, gpa): > self.name = name > self.gpa = gpa and indentation is normally 4 spaces, at least in public Python documentation. > gpa = 0 > name = "" Why do you introduce two class variables with the same name? (not useful, you can delete them) > > graduates = (Graduate("Charlie Brown",8.09), Graduate("Snoopy",3.7), > Graduate("Lucy Brown",3.5)) > Albert From dfnsonfsduifb at gmx.de Fri Jun 13 10:32:37 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Fri, 13 Jun 2008 16:32:37 +0200 Subject: pgdb connection string Message-ID: <51dai5xjnc.ln2@joeserver.homelan.net> Hello group, I've run into a small problem with pgdb which is actually not PostgreSQL specific - I just do not understand the Python syntax at one point. I'm trying to initialize a connection to a PG database. So help(pgdb) says: pgdb.connect(connect_string) -> connection connect_string = 'host:database:user:password:opt:tty' All parts are optional. You may also pass host through password as keyword arguments. To pass a port, pass it in the host keyword parameter: pgdb.connect(host='localhost:5432') Now from what I understand is that it accepts a string in the form: "%s:%s:%s:%s" % (conf["db"]["hostname"], conf["db"]["database"], conf["db"]["username"], conf["db"]["password"]) Which actually works. But if I want to pass the port, there's one more colon and it parses garbage. So what exactly is this host="foobar" syntax all about? What exactly is passed to pgdb.connect (because it does not seem to be a string) - is it a dictionary or something? I'm puzzled. Regards, Johannes -- "Wer etwas kritisiert muss es noch lange nicht selber besser k?nnen. Es reicht zu wissen, da? andere es besser k?nnen und andere es auch besser machen um einen Vergleich zu bringen." - Wolfgang Gerber in de.sci.electronics <47fa8447$0$11545$9b622d9e at news.freenet.de> From ivan.illarionov at gmail.com Wed Jun 4 12:35:50 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 4 Jun 2008 16:35:50 +0000 (UTC) Subject: Extending Python with C: Can I specify another C compiler? References: <625c63a6-8f71-48db-9f6a-e3f43b487472@56g2000hsm.googlegroups.com> Message-ID: On Wed, 04 Jun 2008 09:12:18 -0700, spectrumdt wrote: > Hello. > > I am trying to extend my Python program with some C code. > > This thread is sort of a follow-up to another thread of mine, linked > below. I don't know what the conventions are in this newsgroup about > creating new threads vs. staying in existing ones, but I figured I'd > rather make a new one with a title pertaining to my current problem. > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/ d60449f4db19f731# > > Anyway, my question is this: When compiling my C code to include in > Python, using a Python script with the function distutils.core.setup... > can I choose which C compiler to use? On my system it defaults to gcc, > but I would like to use mpicc instead (C compiler for MPI, Message > Passing Interface). > > Can I do this? > > My system, in case it matters, is Fedora Linux. > > Thanks in advance. There is -c option for setup.py build and setup.py build_ext. If it doesn't work for your compiler you probably have to build your extensions manually. Ivan From sylvain.vivien at gmail.com Sat Jun 7 03:49:41 2008 From: sylvain.vivien at gmail.com (Sylvain) Date: Sat, 7 Jun 2008 00:49:41 -0700 (PDT) Subject: cgi, parse_header and semi-colon References: Message-ID: <99af23e4-4a64-48dd-8537-a123db8147b5@b1g2000hsg.googlegroups.com> On Jun 6, 5:33 pm, "Richard Brodie" wrote: > "Sylvain" wrote in message > > news:b80af57f-897d-4fd1-bebc-df0782143314 at 25g2000hsx.googlegroups.com... > > > If we upload a file with a semi-colon (i.e : "C:/my;file.jpg") : > > cgi.FieldStorage.filename returns only "my" everything after the semi- > > colon is missing > > > Is it a bug or i'm missing something ? > > I doubt it's bug inparse_header, since it's meant to split on > semicolons. Whether it's a bug in one of its callers, or the client > not escaping sufficiently, I couldn't say offhand. I've printed the filename in the content-disposition header : filename="my;file.jpg" If you look at the http://www.ietf.org/rfc/rfc2183.txt about "content- disposition" : "A short parameter value containing only ASCII characters, but including `tspecials' characters, SHOULD be represented as `quoted- string'." So my header is correct but i think there is clearly a bug in the parse_header and "content-disposition" should not be "splitted" only with the split(';') method but should look at quoted-string too. Regards From bearophileHUGS at lycos.com Mon Jun 9 10:04:31 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 9 Jun 2008 07:04:31 -0700 (PDT) Subject: Q re documentation Python style References: Message-ID: kj: > I have some functions > that require a very long docstring to document, and somehow I find > it a bit disconcerting to stick a few screenfuls of text between > the top line of a function definition and its body. You may put the main function(s) documentation in the docstring of the module, and a much shorter version in the docstring of the function. Bye, bearophile From gagsl-py2 at yahoo.com.ar Tue Jun 3 22:45:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 03 Jun 2008 23:45:16 -0300 Subject: Different execution time in python code between embedded or standalone References: <207312b70806031258n68b9dfl942e098e5119c1dc@mail.gmail.com> Message-ID: En Tue, 03 Jun 2008 16:58:12 -0300, Pau Freixes escribi?: > Hi list, > > First Hello to all, this is my and hope not end message to the list :P > > This last months I have been writting a program in c like to mod_python > for > embedding python language, it's a middleware for dispatch and execute > python > batch programs into several nodes. Now I'm writing some python program > for > test how scale this into several nodes and comparing with "standalone" > performance. > > I found a very strange problem with one application named md5challenge, > this > aplication try to calculate the max number md5 digest in several seconds, > md5challenge use a simple signal alarm for stop program when time has > passed. This is the code of python script > > def handler_alrm(signum, frame): > global _signal > global _nrdigest > global _f > > > _signal = True > > def try_me(): > global _nrdigest > global _f > global _signal > > _f = open("/dev/urandom","r") > while _signal is not True: > buff = _f.read(_const_b) > md5.md5(buff).hexdigest() > _nrdigest = _nrdigest + 1 > > if _f is not None : > _f.close() > > def main( req ): > global _nrdigest > > > signal.signal(signal.SIGALRM, handler_alrm) > signal.alarm(req.input['time']) > > > try_me() > > req.output['count'] = _nrdigest > > return req.OK > > > if __name__ == "__main__": > > # test code > class test_req: > pass > > req = test_req() > req.input = { 'time' : 10 } > req.output = { 'ret' : 0, 'count' : 0 } > req.OK = 1 > > main(req) > > print "Reached %d digests" % req.output['count'] > > > When I try to run this program in standalone into my Pentium Dual Core > md4challenge reached 1.000.000 milion keys in 10 seconds but when i try > to > run this in embedded mode md5challenge reached about 200.000 more keys > !!! I > repeat this test many times and always wins embedded mode !!! What's > happen ? > > Also I tested to erase read dependencies from /dev/random, and calculate > all > keys from same buffer. In this case embedded mode win always also, and > the > difference are more bigger !!! > > Thks to all, can anybody help to me ? So the above code corresponds to the standalone version - what about the embedded version? Are you sure it is exactly the *same* code? All those global statements are suspicious, and you don't even need most of them. Note that looking up a name in the global namespace is much slower than using a local name. Also, you're including the time it takes the OS to *generate* several megabytes of random data from /dev/urandom (how big is _const_b?). Usually it's easier (and more accurate) to measure the time it takes to compute a long task (let's say, how much time it takes to compute 1000000 md5 values). You're doing it backwards instead. I'd rewrite the test as: def try_me(): from md5 import md5 buff = os.urandom(_const_b) for i in xrange(1000000): md5(buff).hexdigest() def main(req): t0 = time.clock() try_me() t1 = time.clock() # elapsed time = t1-t0 PS: Recuerdo que respond? esto en la lista de Python en castellano, pero ahora veo que mi mensaje nunca lleg? :( -- Gabriel Genellina From ram.rachum at gmail.com Sun Jun 15 15:08:08 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Sun, 15 Jun 2008 12:08:08 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com><3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> Message-ID: <6fb5a49a-d50a-4dac-942d-ab98a369bb25@r66g2000hsg.googlegroups.com> On Jun 15, 10:01?pm, "Terry Reedy" wrote: > wrote in message > > news:1257aa24-14fa-426e-8019-262984c70633 at 2g2000hsn.googlegroups.com... > |> How did you determine that standard python floats are not good enough? > > | I have a physical system set up in which a body is supposed to > | accelerate and to get very close to lightspeed, while never really > |attaining it. > > Just a thought. ?You might do better if you can rearrange your equations in > terms of c-v instead of v. ?Letting c=1, you cannot accutrately express > v = .99999999999999999999 > in Python, but can easily express > 1-v = .00000000000000000001. > And so on. > > tjr Good idea Terry, I'll think about it. From praveen.sunsetpoint at gmail.com Thu Jun 19 01:08:38 2008 From: praveen.sunsetpoint at gmail.com (Sallu) Date: Wed, 18 Jun 2008 22:08:38 -0700 (PDT) Subject: =?ISO-8859-1?Q?Regular_expressions_for_accents_like_=F3_character_in?= =?ISO-8859-1?Q?_python?= Message-ID: i want to restrict to user to not enter accents character. si i need to make an Regular expressions for accents like ? character From __peter__ at web.de Mon Jun 2 17:06:29 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 Jun 2008 23:06:29 +0200 Subject: [Re] Checking each item in m.group()? References: Message-ID: nospam at nospam.com wrote: > I need to go through each line of a CSV file, and extract some fields > using a regex. Then, I need to check each retrieved field, and if it > looks like "", turn this into NULL so that it's correct SQL. You are taking the wrong approach here. Don't build SQL statements as strings; you are enabling the next SQL injection attack. Pass parameters using the DB API instead. Don't use regular expressions to parse a CSV file. Python's csv module is more likely to deal correctly with the quirks of that standard. A self-contained example: import csv import sqlite3 as sqlite from cStringIO import StringIO def records(infile): for row in csv.reader(infile): # replace empty strings in the second column with None # which translates to NULL in the database yield row[0], row[1] or None def main(): # create sample data; you may use a real file infile = StringIO("""\ alpha,beta,gamma zeta,,theta """) # create the database db = sqlite.connect(":memory:") cursor = db.cursor() cursor.execute("create table demo (first, second);") # safely insert data cursor.executemany("insert into demo values (?, ?);", records(infile)) # show contents for row in cursor.execute("select first, second, second is NULL " "from demo order by first, second;"): print row if __name__ == "__main__": main() Peter From musiccomposition at gmail.com Sat Jun 7 23:09:45 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sat, 7 Jun 2008 20:09:45 -0700 (PDT) Subject: ABC question: what is the purpose of the register() method? References: <22c53e8d-1f95-465f-932e-b0b0bbf148ba@x41g2000hsb.googlegroups.com> Message-ID: On Jun 7, 1:37 pm, Kay Schluehr wrote: > I was reading PEP 3119 (http://www.python.org/dev/peps/pep-3119/) and > have done some experiments using Python 3.0a5. Now I'm somewhat > puzzled about the purpose of the ABCMeta.register() method. > > One can use the register() method to register any class as a virtual > subclass of any ABC. For example one can register `int` on `Iterable` > and therefore it is a subclass which is confirmed in the issubclass > check. What is that good for? It's mostly good for types created in C, where it's hard to inherit a class. For example, builtin types register them selves under some ABCs in collections. From ppearson at nowhere.invalid Fri Jun 20 12:11:17 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: Fri, 20 Jun 2008 11:11:17 -0500 Subject: Tkinter canvas drag/drop obstacle Message-ID: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> Tkinter makes it very easy to drag jpeg images around on a canvas, but I would like to have a "target" change color when the cursor dragging an image passes over it. I seem to be blocked by the fact that the callbacks that might tell the target that the mouse has entered it (, , even ) aren't called if the mouse's button is down. What am I missing? Have I failed to find the right Tkinter document? Is Tkinter the wrong tool for this job? Thanks. -- To email me, substitute nowhere->spamcop, invalid->net. From georgeoliverGO at gmail.com Sat Jun 28 03:49:42 2008 From: georgeoliverGO at gmail.com (George Oliver) Date: Sat, 28 Jun 2008 00:49:42 -0700 (PDT) Subject: 2D online multiplayer framework? Message-ID: <6dc6195b-b8a0-42a9-a982-3a4b70943c24@r37g2000prm.googlegroups.com> I'm looking for a framework to support a 2D online real-time multiplayer game (rugby league football with a lo-fi pixel look). The GameProgramming page at the Python wiki had some suggestions but so far nothing looks that promising, does anyone have some recommendations? It would be ideal to play this through a web browser but I don't know if that's practical. This aspect of programming is pretty new to me so I'm not sure if I should start with something general like Twisted or if there's a different path I should take. thanks, George From weheh at yahoo.com Sun Jun 22 16:00:01 2008 From: weheh at yahoo.com (weheh) Date: Sun, 22 Jun 2008 20:00:01 GMT Subject: pyTTS says, '"SAPI" not supported' Message-ID: <5by7k.2739$gE.1491@trnddc07> I'm running Python 2.3 and calling pyTTS. I've had it working forever. Today, I ran out of disk space. After deleting some of my personal files, for no apparent reason, pyTTS no longer runs. For the statement tts = pyTTS.Create() I get the error message: ValueError: "SAPI" not supported Can anybody help me? What's going on? From sjmachin at lexicon.net Thu Jun 26 04:56:08 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 26 Jun 2008 01:56:08 -0700 (PDT) Subject: Freeze problem with Regular Expression References: <6cf614F3f8ocoU1@mid.individual.net> <0e1a9726-cc1d-4bd2-b0ba-b2bcc1c27ee8@f24g2000prh.googlegroups.com> Message-ID: <2969ef42-c4a6-4950-8522-df58a4138776@q24g2000prf.googlegroups.com> On Jun 26, 8:29?am, John Machin wrote: > (2) ALWAYS use a raw string for regexes; your \s* will match on lower- > case 's', not on spaces and should have written: (2) ALWAYS use a raw string for regexes. <<<=== Big fat full stop aka period. but he was at the time only half-way through the first cup of coffee for the day :-) From stef.mientki at gmail.com Mon Jun 30 15:04:12 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 30 Jun 2008 21:04:12 +0200 Subject: list extension ? In-Reply-To: <4868b0ba$0$17063$426a34cc@news.free.fr> References: <4868b0ba$0$17063$426a34cc@news.free.fr> Message-ID: <48692E2C.1090406@gmail.com> thanks guys, > >> def __init__ ( self, value = [] ) : > > Gotcha : default argument values are eval'd only once. Also, it would > make more sense IMHO to follow the parent's class initializer's > behaviour: > > def __init__(self, *args) > >> list.__init__ ( self, value ) > > list.__init__(self, *args) > that's even better, except the call must be list.__init__ ( self, args ) cheers, Stef From hamish at valvesoftware.com Fri Jun 20 17:19:37 2008 From: hamish at valvesoftware.com (Hamish McKenzie) Date: Fri, 20 Jun 2008 14:19:37 -0700 Subject: inheritance question... In-Reply-To: References: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> <09ec833f-7751-4991-8d09-45c200fb4c18@z72g2000hsb.googlegroups.com> Message-ID: <587C2C9324493D4B96BD6BBCDEAC321AA95911@exchange3.valvesoftware.com> I have this class: class Vector(object): TOL = 1e-5 def __eq__( self, other, tolerance=TOL ): print tolerance shortened for clarity obviously. so I want to subclass this class like so: class BigVector(Vector) TOL = 100 for example if I was working with large vectors which I knew would never be very close hence the large tolerance. this doesn't work however - the TOL class variable, while overridden in BigVector, is still using the Vector.TOL variable in the __eq__ method. which kinda makes sense to a certain degree, but how do I get the behaviour where doing: BigVector().__eq__( otherVec ) prints 100 instead of 1e-5? does this question make sense? not sure how clearly I'm phrasing my question... any of you guys python experts? I *could* do this, but its ugly: class Vector(object): TOL = 1e-5 def __eq__( self, other, tolerance=None ): if tolerance is None: tolerance = self.TOL print tolerance From jonhune at yahoo.com Thu Jun 5 18:53:52 2008 From: jonhune at yahoo.com (Jon Hune) Date: Thu, 5 Jun 2008 15:53:52 -0700 (PDT) Subject: soaplib newbie question Message-ID: <729667.58494.qm@web46312.mail.sp1.yahoo.com> hi everyone, I'm totally new to SOAP. Can anyone help with this soap question. I'm trying to use soaplib. I can't find many examples on using soaplib and what I have below if the standard hello world example I find online. Say I want to call the zzz service at yyy. I know that the service inputs are two integers and a string (say a,b,c), and the output is three strings (say d,e,f). URL = "http://www.yyy.com/yyy.wsdl" a = 1 b = 2 c = "3" from soaplib.wsgi_soap import SimpleWSGISoapApp from soaplib.service import soapmethod from soaplib.serializers.primitive import String, Integer, Array class YYY(SimpleWSGISoapApp): @soapmethod(Integer, Integer, String, _returns = Array(String)) def zzz(self, a, b, c): pass from soaplib.client import make_service_client client = make_service_client(URL, YYY()) print client.zzz(a, b, c) I get this error: $ python x.py Traceback (most recent call last): File "x.py", line 32, in orderNumber) File "/usr/lib/python2.5/site-packages/soaplib-0.7.1dev_r17-py2.5.egg/soaplib/ client.py", line 157, in __call__ payload, headers = from_soap(data) File "/usr/lib/python2.5/site-packages/soaplib-0.7.1dev_r17-py2.5.egg/soaplib/ soap.py", line 96, in from_soap if len(body.getchildren()): AttributeError: 'NoneType' object has no attribute 'getchildren' Another question I have is what happens when the output is say an integer and a string? I can't find an example for soaplib. In the above case, the output is 3 strings. I used Array(String). I'm not even sure if that's correct. How should I for instance specify output of an integer and a string? thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From squareswallower at 1ya2hoo3.net Sun Jun 1 17:14:44 2008 From: squareswallower at 1ya2hoo3.net (dave) Date: Sun, 1 Jun 2008 15:14:44 -0600 Subject: Bring object 'out of' Class? References: Message-ID: > Then you can write: > >>>> hands = deck.deal_cards(4, 5) # On fait une belotte? > > And I don't see the need of defining 'Hand' inside 'Deck'. > > HTH Thanks for the input. I believe using 'class Hand(Deck):' is to illustrate (in the book) inheritance and how it can be used. By using 'Hand(Deck)' I can then use the methods (pop_card, add_cards, etc..) defined in the 'Deck' class. From maric at aristote.info Fri Jun 27 06:27:16 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 27 Jun 2008 12:27:16 +0200 Subject: using urllib2 In-Reply-To: <18150669.post@talk.nabble.com> References: <18150669.post@talk.nabble.com> Message-ID: <200806271227.17081.maric@aristote.info> Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit?: > I have never used the urllib or the urllib2. I really have looked online > for help on this issue, and mailing lists, but I can't figure out my > problem because people haven't been helping me, which is why I am here! :]. > Okay, so basically I want to be able to submit a word to dictionary.com and > then get the definitions. However, to start off learning urllib2, I just > want to do a simple google search. Before you get mad, what I have found on > urllib2 hasn't helped me. Anyway, How would you go about doing this. No, I > did not post the html, but I mean if you want, right click on your browser > and hit view source of the google homepage. Basically what I want to know > is how to submit the values(the search term) and then search for that > value. Heres what I know: > > import urllib2 > response = urllib2.urlopen("http://www.google.com/") > html = response.read() > print html > > Now I know that all this does is print the source, but thats about all I > know. I know it may be a lot to ask to have someone show/help me, but I > really would appreciate it. This example is for google, of course using pygoogle is easier in this case, but this is a valid example for the general case : >>>[207]: import urllib, urllib2 You need to trick the server with an imaginary User-Agent. >>>[208]: def google_search(terms) : return urllib2.urlopen(urllib2.Request("http://www.google.com/search?" + urllib.urlencode({'hl':'fr', 'q':terms}), headers={'User-Agent':'MyNav 1.0 (compatible; MSIE 6.0; Linux'}) ).read() .....: >>>[212]: res = google_search("python & co") Now you got the whole html response, you'll have to parse it to recover datas, a quick & dirty try on google response page : >>>[213]: import re >>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

    .*?

    ', res) ] ...[229]: ['Python Gallery', 'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des Monty ...', 'Re: os x, panther, python & co: msg#00041', 'Re: os x, panther, python & co: msg#00040', 'Cardiff Web Site Design, Professional web site design services ...', 'Python Properties', 'Frees < Programs < Python < Bin-Co', 'Torb: an interface between Tcl and CORBA', 'Royal Python Morphs', 'Python & Co'] -- _____________ Maric Michaud From bruno.42.desthuilliers at websiteburo.invalid Tue Jun 10 04:04:10 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 10 Jun 2008 10:04:10 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <4847d39d$0$7614$426a74cc@news.free.fr> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> <484cf5f6$0$15495$426a74cc@news.free.fr> <127975a3-b3d9-4799-9673-b292ec8d37e3@x19g2000prg.googlegroups.com> <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> Message-ID: <484e3526$0$30894$426a74cc@news.free.fr> Russ P. a ?crit : > On Jun 9, 2:10 pm, "bruno.desthuilli... at gmail.com" > wrote: > >> But if it takes 6 month to get the mentioned developer to release >> something I can use, I'm screwed up. Fine. > > I've lost track of how many times I've said this now, but my > suggestion for a "priv" keyword allowed for "indirect" access to > private data through some name-mangling scheme. And I've lost track of how many times I've said this now, but we already have this. While we're at it, why not a 'prot' keyword that would restrict name-mangling to the addition of a single leading underscore ? > That could be your > temporary fix while you are waiting for the developer to release a > corrected version. And even if that option were not available, you > could simply open up the relevant source file in the editor of your > choice and remove the offending "priv" declaration. Yes. And I can always edit the source code and add the methods I need etc. You probably never used monkeypatching, so I guess you just can't understand the difference between maintaining a monkeypatch and maintaining a fork. > I completely fail > to see how you are "screwed." > Sorry, but when I have to keep repeating the same basic points over > and over, I can't help but think I might be wasting my time. If you hope to get a general agreement here in favor of a useless keyword that don't bring anything to the language, then yes, I'm afraid you're wasting your time. From michael at stroeder.com Mon Jun 16 09:47:49 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Mon, 16 Jun 2008 15:47:49 +0200 Subject: Who is using python-ldap with Python 1.5.x and 2.0-2.2? Message-ID: <6h7ii5-l9m.ln1@nb2.stroeder.com> HI! I'd like to hear from the Python community whether support for Python version prior to 2.3 is still needed in python-ldap. Please tell me which Python version you're using and why it'd be important for you to have python-ldap updates still supporting it. BTW: Actually older Python versions are not tested with recent python-ldap since at least two years. But I'd like to clearly decide on that. Ciao, Michael. From cwitts at gmail.com Fri Jun 6 04:31:56 2008 From: cwitts at gmail.com (Chris) Date: Fri, 6 Jun 2008 01:31:56 -0700 (PDT) Subject: import cherrypy2 References: Message-ID: On Jun 6, 10:22?am, luca72 wrote: > Hello i can't import cherrypy2 but i don't know why this is the sys > path: > > '', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > setuptools-0.6c7-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg', '/home/pirataja/ > opo.net/python/lib/python2.5/site-packages/TurboKid-1.0.4-py2.5.egg', > '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > TurboJson-1.1.2-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > python2.5/site-packages/TurboCheetah-1.0-py2.5.egg', '/home/pirataja/ > opo.net/python/lib/python2.5/site-packages/simplejson-1.9.1-py2.5- > linux-i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site- > packages/RuleDispatch-0.5a0.dev_r2306-py2.5-linux-i686.egg', '/home/ > pirataja/opo.net/python/lib/python2.5/site-packages/PasteScript-1.6.2- > py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > FormEncode-1.0.1-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > python2.5/site-packages/DecoratorTools-1.7-py2.5.egg', '/home/pirataja/ > opo.net/python/lib/python2.5/site-packages/configobj-4.5.2-py2.5.egg', > '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > CherryPy-2.3.0-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > python2.5/site-packages/kid-0.9.6-py2.5.egg', '/home/pirataja/opo.net/ > python/lib/python2.5/site-packages/Cheetah-2.0.1-py2.5-linux- > i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > PyProtocols-1.0a0dev_r2302-py2.5-linux-i686.egg', '/home/pirataja/ > opo.net/python/lib/python2.5/site-packages/PasteDeploy-1.3.1- > py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/ > Paste-1.7-py2.5.egg', '/home/pirataja/opo.net/python/lib/ > python25.zip', '/home/pirataja/pirata-jacopo.net/python/lib/ > python2.5', '/home/pirataja/opo.net/python/lib/python2.5/plat- > linux2', > '/home/pirataja/opo.net/python/lib/python2.5/lib-tk', > '/home/pirataja/opo.net/python/lib/python2.5/lib-dynload', '/home/ > pirataja/opo.net/python/lib/python2.5/site-packages'] > > For my is all ok but whe i do import cherrypy2 i get no mudule name > cherrypy2 > > Regards > > Luca because it's "import cherrypy" and not "import cherrypy2" From omer at no-log.org Sat Jun 21 11:46:33 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Sat, 21 Jun 2008 17:46:33 +0200 Subject: Way to unblock sys.stdin.readline() call In-Reply-To: <56b21108-45b4-4b9e-bda5-171c9ddc21ce@i76g2000hsf.googlegroups.com> References: <56b21108-45b4-4b9e-bda5-171c9ddc21ce@i76g2000hsf.googlegroups.com> Message-ID: <200806211746.33397.omer@no-log.org> Le Saturday 21 June 2008 15:26:53 joamag, vous avez ?crit?: > HI, > > Is there any possible way to unblock the sys.stdin.readline() call > from a different thread. > Something like sys.stdin.write() but that would actually work ... > something to put characters in the stdin... > Do you mean setting stdin in non-blocking mode ? On unix you can do it with the fcntl module (you'll find more infos in the libc docs) : fcntl.fcntl(sys.stdin, fcntl.F_SETFL, os.O_NONBLOCK) and catch IOErrors with errno = EAGAIN. But I don't know how to do it in a portable way, suggestions welcome :) -- C?dric Lucantis From termim at gmail.com Mon Jun 30 15:34:53 2008 From: termim at gmail.com (Mike) Date: Mon, 30 Jun 2008 12:34:53 -0700 (PDT) Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> Message-ID: On Jun 30, 1:49?pm, "bruno.desthuilli... at gmail.com" wrote: > > > Then what is so *good* about it, why embedding HTML into Python is not > > good? > > Who said embedding HTML in Python was bad ? Did you _carefully_ read > John's question ?-) > I should have say "why embedding HTML into Python is not good enough?" ;=) > wrt/ what's so good about it: web designers are usually better at > working with this approach (whatever scripting language embedded in > html) than they are writing Python code - either as plain strings or > using a more declarative syntax like the one provided by Stan or I keep reading this argument that some mythical 'web designers' are usually better at working with this abracadabra (TAL etc.). BTW, most of the times it is used by programmers :). Sorry, I can't believe it. Sure there are some people that enjoy reading Perl or JCL, but all of them? IMHO if 'web designer' is able to separate HTML syntax from 'embedded language' syntax, then he is perfectly able to understand clear and simple Python code. > equivalent html generators. ?But nothing prevents you from using > Mako's internals directly if you find it easier and more > maintainable !-) Yea, that is a perfect and universal advise - use whatever fits you best!;:=} From fc14301589 at icqmail.com Wed Jun 11 10:16:56 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Wed, 11 Jun 2008 22:16:56 +0800 Subject: My fight with classes :) Message-ID: <484fde63_1@news.tm.net.my> Hi, I'm very new with classes. I still reading something around ;) I got started to try a concatenation of 2 type of string, which have a particular property to start with A or D. My class here: """ Small class to join some strings according to the leading first letter""" def __init__(self): self.valueA= '' self.valueD= '' def __add__(self, value): if not isinstance(value, str): return if value.lower().startswith('a'): self.valueA += value if value.lower().startswith('d'): self.valueD += value return self.valueA ,self.valueD __call__= __add__ __iadd__= __add__ my test on the shell: >>> from utilities import StrJoin as zx >>> k= zx() >>> k >>> k +'aks' ('aks', '') >>> k +'daks' ('aks', 'daks') >>> k +'hdaks' ('aks', 'daks') >>> k +'dhks' ('aks', 'daksdhks') >>> j('boi') Traceback (most recent call last): File "", line 1, in NameError: name 'j' is not defined >>> k('boi') ('aks', 'daksdhks') >>> k('aboi') ('aksaboi', 'daksdhks') >>> k('duboi') ('aksaboi', 'daksdhksduboi') >>> k += 'liu' >>> k += 'aliu' Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate tuple (not "str") to tuple >>> k ('aksaboi', 'daksdhksduboi') Do I miss something? I'd rather like to avoid class, but a function won't allow me to store so easily data between several call. Mostly I'd expect to pass to the built instance in a more elaborated function. Then I mean call will be the primer goal. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From gh at ghaering.de Mon Jun 30 09:52:56 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 30 Jun 2008 15:52:56 +0200 Subject: List Performance In-Reply-To: <2eydnaP-saOZQfXVnZ2dnUVZ_qvinZ2d@comcast.com> References: <42358e0b-a351-4862-8f6a-1938eedeff6c@s21g2000prm.googlegroups.com> <2eydnaP-saOZQfXVnZ2dnUVZ_qvinZ2d@comcast.com> Message-ID: Larry Bates wrote: > [...] > So its actually faster to append to a long list than an empty one? That > certainly would not have been intuitively obvious now would it? Maybe not intuitively, but if you know how dynamically growing data structures are implemented, it's plausible. They overallocate, and the amount of overallocation is dependent on the current size. Relevant source snippet from Python 2.6: /* This over-allocates proportional to the list size, making room * for additional growth. The over-allocation is mild, but is * enough to give linear-time amortized behavior over a long * sequence of appends() in the presence of a poorly-performing * system realloc(). * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... */ new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6); If, on the other hand, we knew beforehand how big the list will get approximately, we could avoid all these reallocations. No problem with Python's C API: PyAPI_FUNC(PyObject *) PyList_New(Py_ssize_t size); But you can't do it directly from Python, unless you (ab)use ctypes. -- Gerhard From jarausch at igpm.rwth-aachen.de Fri Jun 13 03:39:22 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Fri, 13 Jun 2008 09:39:22 +0200 Subject: ANN: eGenix pyOpenSSL Distribution 0.7.0-0.9.8h-1 In-Reply-To: References: Message-ID: <4852242A.5000507@igpm.rwth-aachen.de> eGenix Team: M.-A. Lemburg wrote: > ________________________________________________________________________ > > ANNOUNCING > > eGenix.com pyOpenSSL Distribution > > Version 0.7.0-0.9.8h-1 > > > An easy to install and use repackaged distribution > of the pyOpenSSL Python interface for OpenSSL - > available on Windows and Unix platforms > > > This announcement is also available on our web-site for online reading: > http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.7.0-0.9.8h-1-GA.html Just to mention downloading the source doesn't work. Under requirements (to compile the source) there is mxbase version >= 3.0.1 which I couldn't find on your web server. Many thanks, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From M8R-yfto6h at mailinator.com Sat Jun 7 10:19:42 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Sat, 7 Jun 2008 07:19:42 -0700 Subject: Parsing a path to components References: <7d7dd66c-b2bb-4a9a-a2e4-589079cda97b@e39g2000hsf.googlegroups.com> <14bf5448-4677-4ced-9d79-b4eb0c048218@56g2000hsm.googlegroups.com> <6auuc5F38s3s9U1@mid.uni-berlin.de> Message-ID: <_rydnW6Tc6hjBdfVnZ2dnUVZ_oadnZ2d@comcast.com> "eliben" wrote in message news:e5fd542f-56d2-4ec0-a3a7-aa1ee106c624 at a70g2000hsh.googlegroups.com... > On Jun 7, 10:15 am, Marc 'BlackJack' Rintsch wrote: >> On Fri, 06 Jun 2008 23:57:03 -0700, s0suk3 wrote: >> > You can just split the path on `os.sep', which contains the path >> > separator of the platform on which Python is running: >> >> > components = pathString.split(os.sep) >> >> Won't work for platforms with more than one path separator and if a >> separator is repeated. For example r'\foo\\bar/baz//spam.py' or: >> >> In [140]: os.path.split('foo//bar') >> Out[140]: ('foo', 'bar') >> >> In [141]: 'foo//bar'.split(os.sep) >> Out[141]: ['foo', '', 'bar'] >> >> Ciao, >> Marc 'BlackJack' Rintsch > > Can you recommend a generic way to achieve this ? > Eli >>> import os >>> from os.path import normpath,abspath >>> x=r'\foo\\bar/baz//spam.py' >>> normpath(x) '\\foo\\bar\\baz\\spam.py' >>> normpath(abspath(x)) 'C:\\foo\\bar\\baz\\spam.py' >>> normpath(abspath(x)).split(os.sep) ['C:', 'foo', 'bar', 'baz', 'spam.py'] -Mark From shiningsandy at gmail.com Thu Jun 19 09:14:08 2008 From: shiningsandy at gmail.com (sandeep) Date: Thu, 19 Jun 2008 06:14:08 -0700 (PDT) Subject: python script for tortoise cvs Message-ID: hi we are using tortoise cvs and putty. i want to write a python script to whom i can provide a tag and module.now what this script will do is look for this specific tag and checks for whether its a individual tag or its inside a branch.if its inside a branch then find out what is the branch tag and then check out that branch for me else it checks out that module with that tag. Actually the thing is i am not able to find the way how i will do it and for where i have to look for the info.so any help will be appreciated. thanks and regards sandeep kumar sharma From lac at openend.se Thu Jun 5 14:26:58 2008 From: lac at openend.se (Laura Creighton) Date: Thu, 05 Jun 2008 20:26:58 +0200 Subject: ANN: Resolver One 1.1 released In-Reply-To: Your message of "Wed, 04 Jun 2008 11:01:44 PDT." References: Message-ID: <200806051826.m55IQwG6021897@theraft.openend.se> Hey, Congratulations! Laura Creighton From jacksingleton1 at gmail.com Sat Jun 28 21:12:35 2008 From: jacksingleton1 at gmail.com (c0mrade) Date: Sat, 28 Jun 2008 18:12:35 -0700 (PDT) Subject: Testing for Null? In-Reply-To: <268ac2770806281605n663670e9n29620f344ed66e4d@mail.gmail.com> References: <268ac2770806281605n663670e9n29620f344ed66e4d@mail.gmail.com> Message-ID: <18176481.post@talk.nabble.com> Try something like this... list = ['lkdfjsldk', None, '', '0', 'slfkjsdlfj', 'lsdgjdlfg', False, True] for n, it in enumerate(list): if not it: print 'Error on this definition' else: print '%d. %s' % (n+1, it) Results: 1. lkdfjsldk Error on this definition Error on this definition 4. 0 5. slfkjsdlfj 6. lsdgjdlfg Error on this definition 8. True Alexnb wrote: > > I am having a problem with a list value that is empty. I have a list of > definitions called mainList. the 5th value in the list doesn't have > anything > in it. In this case, the values are definitions; also, in this case just > the > word cheese is defined. Here is my output to the console: > > > 5. a sprawling,weedy plant having small lavender or white flowers and > round, flat, segmented fruits thought to resemble little wheels of cheese. > 6. > 7. an ingot or billet made into a convex, circular form by blows at the > ends. > > > I've made it so where the numbers, the period, and two spaces follow that, > then the definition. However, as you can see in 6, there is nothing. Here > is > the code to print all this: > > n=0 > > for x in mainList: > if mainList[n] == "": > print "Error on this definition" > else: > print str(n+1)+". "+str(mainList[n]) > n=n+1 > > Now the two "" is where I need to figure out if it is empty. What is up > right now doesn't work; or at least doesn't give the desired result. So I > need to know how to write the if statement to make it work. This should be > simple, but I just don't know how to do it, never had this problem before. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- View this message in context: http://www.nabble.com/Testing-for-Null--tp18175738p18176481.html Sent from the Python - python-list mailing list archive at Nabble.com. From hniksic at xemacs.org Thu Jun 5 17:59:58 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 05 Jun 2008 23:59:58 +0200 Subject: ClassName.attribute vs self.__class__.attribute References: <25e0de62-4c63-4545-8684-69a410639807@i76g2000hsf.googlegroups.com> Message-ID: <87hcc7zgo1.fsf@mulj.homelinux.net> "bruno.desthuilliers at gmail.com" writes: > On 5 juin, 17:40, Gabriel Rossetti > wrote: >> Hello everyone, >> >> I had read somewhere that it is preferred to use >> self.__class__.attribute over ClassName.attribute to access class (aka >> static) attributes. > > It's even prefered to use self.attribute, I was going to write exactly that, but it occurred to me that he might want to be *assigning* to self.__class__.attribute (or HisClass.attribute) from his methods, in which case self.attribute would be quite different. From mail at timgolden.me.uk Fri Jun 6 12:05:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 06 Jun 2008 17:05:03 +0100 Subject: How to remove read-only from a file In-Reply-To: <496954360806060846p4f96a00buc408720dcf9d95da@mail.gmail.com> References: <496954360806060846p4f96a00buc408720dcf9d95da@mail.gmail.com> Message-ID: <4849602F.6040403@timgolden.me.uk> Robert Dailey wrote: > Hi, > > Using Python 3.0, how can I remove a read-only property from a file in > Windows XP? Thanks. import os import stat os.chmod ("c:/temp/temp.txt", stat.S_IWRITE) (Haven't actually checked that on Python 3.0 but I don't believe it's changed...) TJG From bronger at physik.rwth-aachen.de Fri Jun 27 02:02:39 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 27 Jun 2008 08:02:39 +0200 Subject: Cyclic imports References: <1a5a1eb9-b4d1-4905-b60c-48fc93056e4d@k13g2000hse.googlegroups.com> <2588f7e0-ccbb-40cb-84da-d133349f5b72@u36g2000prf.googlegroups.com> Message-ID: <87fxqzo1og.fsf@physik.rwth-aachen.de> Hall?chen! James writes: >> # a.py >> import b >> # refer to b.b >> >> # b.py >> import a >> # refer to a.a > > Thanks Dan, but that still doesn't work for me I'm afraid... > > I renamed the modules avoid name overloading -- a.py is now: > import b > > class A(): > print('b.b_mod:', b.b_mod) Dan's hint is the way to go nevertheless. However, it is still not possible to actually use the module object on the top-level (i.e., while module a.py is read). So, you must delay any access to module b until everything is fully loaded -- for example, by wrapping the access in a function which is called from the main program. On the other hand, the above code was for debugging purposes I assume. So maybe there's no real problem anyway because all your uses of module b are wrapped in functions/methods anyway. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From eckhardt at satorlaser.com Thu Jun 5 05:16:43 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 05 Jun 2008 11:16:43 +0200 Subject: Image Processing (batch) References: <6akqd5F37rofnU1@mid.individual.net> Message-ID: Tim Roberts wrote: > Thomas Guettler wrote: >> >>I tried PIL for image batch processing. But somehow I don't like it >> - Font-Selection: You need to give the name of the font file. >> - Drawing on an image needs a different object that pasting and saving. >> - The handbook is from Dec. 2006. > > I have repeatedly seen the attitude in your last point, and I simply do > not understand it. What on Earth is wrong with having a product that > actually becomes stable? Nothing, and it is correct pointing that out. OTOH, there are billions of open source projects out there that started with an idea but never entered that finished state where they are useful, so-called abandonware. If the documentation is old, it is either stable or abandoned. Only a closer look can tell which of both, but statistically it is more likely that it is abandoned, sad as it is. Peace! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From bruno.42.desthuilliers at websiteburo.invalid Wed Jun 25 05:49:35 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 25 Jun 2008 11:49:35 +0200 Subject: IDE on the level of Eclipse or DEVc++? In-Reply-To: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> Message-ID: <486214ae$0$9742$426a34cc@news.free.fr> cirfu a ?crit : > is there an IDE for python of the same quality as Eclipse or DEVC++? > > I am currently using the editor that coems iwth python and it is all > fine but for bigger projects it would be nice to have some way to > easier browse the projectfiles for example. If you're into clickodroms, you may want to have a look at Eric too. As far as i'm concerned, I still wait for something that would be worth dropping emacs + python-mode + ecb. From jason.scheirer at gmail.com Thu Jun 26 17:56:56 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Thu, 26 Jun 2008 14:56:56 -0700 (PDT) Subject: Help me optimize my feed script. References: <184ee312-e54f-48bd-ac9f-1eb7e1737fc7@v26g2000prm.googlegroups.com> Message-ID: <5626bd7c-7386-494d-a24c-b46966bb2041@r37g2000prm.googlegroups.com> On Jun 26, 12:30?pm, bsag... at gmail.com wrote: > I wrote my own feed reader using feedparser.py but it takes about 14 > seconds to process 7 feeds (on a windows box), which seems slow on my > DSL line. Does anyone see how I can optimize the script below? Thanks > in advance, Bill > > # UTF-8 > import feedparser > > rss = [ > 'http://feeds.feedburner.com/typepad/alleyinsider/ > silicon_alley_insider', > 'http://www.techmeme.com/index.xml', > 'http://feeds.feedburner.com/slate-97504', > 'http://rss.cnn.com/rss/money_mostpopular.rss', > 'http://rss.news.yahoo.com/rss/tech', > 'http://www.aldaily.com/rss/rss.xml', > 'http://ezralevant.com/atom.xml' > ] > s = '\n\nC:/x/test.htm\n' > > s += '\n' > > s += '\n\n
    \n' > > for url in rss: > ? ? ? ? d = feedparser.parse(url) > ? ? ? ? title = d.feed.title > ? ? ? ? link = d.feed.link > ? ? ? ? s += '\n

    '+ title +'

    \n' > ? ? ? ? # aldaily.com has weird feed > ? ? ? ? if link.find('aldaily.com') != -1: > ? ? ? ? ? ? ? ? description = d.entries[0].description > ? ? ? ? ? ? ? ? s += description + '\n' > ? ? ? ? for x in range(0,3): > ? ? ? ? ? ? ? ? if link.find('aldaily.com') != -1: > ? ? ? ? ? ? ? ? ? ? ? ? continue > ? ? ? ? ? ? ? ? title = d.entries[x].title > ? ? ? ? ? ? ? ? link = d.entries[x].link > ? ? ? ? ? ? ? ? s += ''+ title +'
    \n' > > s += '

    \n\n' > > f = open('c:/scripts/myFeeds.htm', 'w') > f.write(s) > f.close > > print > print 'myFeeds.htm written' I can 100% guarantee you that the extended run time is network I/O bound. Investigate using a thread pool to load the feeds in parallel. Some code you might be able to shim in: # Extra imports import threading import Queue # Function that fetches and pushes def parse_and_put(url, queue_): parsed_feed = feedparser.parse(url) queue_.put(parsed_feed) # Set up some variables my_queue = Queue.Queue() threads = [] # Set up a thread for fetching each URL for url in rss: url_thread = threading.Thread(target=parse_and_put, name=url, args=(url, my_queue)) threads.append(url_thread) url_thread.setDaemonic(False) url_thread.start() # Wait for threads to finish for thread in threads: thread.join() # Push the results into a list feeds_list = [] while not my_queue.empty(): feeds_list.append(my_queue.get()) # Do what you were doing before, replacing the for url in rss with for d in feedS_list for d in feeds_list: title = d.feed.title link = d.feed.link From basti.wiesner at gmx.net Sun Jun 22 05:40:12 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Sun, 22 Jun 2008 11:40:12 +0200 Subject: Fast and easy GUI prototyping with Python References: <9c349bf0-ef63-4463-bd4e-cdbe331b58c3@z66g2000hsc.googlegroups.com> Message-ID: Michael Torrie : > erokar at gmail.com wrote: >> 2) The Qt vs. .NET API. I have no experience with Qt's API and a >> rudimentary experience with the .NET API (seems powerfull but also big >> and complex). > > Qt's API is very very good. Easy to use and extremely powerful. Note > that in Python a number of Qt's APIs are not used in favor of Python > native apis for things like file and socket I/O, IPC, Threads, and so > forth. The support for signals and slots is imho a strong reason to prefer Qt apis over standard python apis, especially when it comes down to asynchronous programming (for instance, large network transfers like file downloads). > I've not used VS 2008's SWF gui designer, but of all the designers I've > seen so far, Qt's Designer is the best I've ever used. full ack. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From timr at probo.com Sat Jun 28 02:13:04 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 28 Jun 2008 06:13:04 GMT Subject: Working with the Windows Registry References: <49beca2a-9d6c-40a2-a7c3-bf1cf376df0a@l28g2000prd.googlegroups.com> Message-ID: <8alb6459djthkord5terdv6unfe4tscgjd@4ax.com> teh_sAbEr wrote: >Hi everybody. I'm trying to write a script that'll change desktop >wallpaper every time its run. Heres what I've gotten so far: > >#random wallpaper changer! >import _winreg >from os import walk >from os.path import exists >from random import randint > >#first grab a registry handle. >handle = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,'Control Panel >\Desktop',_winreg.KEY_SET_VALUE) > >def GenerateListOfWallpapers(): > targetDir = 'C:\Documents and Settings\Enrico Jr\My Documents\Jr >\'s Wallpapers' You are fortunate that your name is not "Tim" or "Ian" or "Nathan", because this would not have worked as you have written it. You either need to double the backslashes: ... 'C:\\Documents and Settings\\Enrico...' or use forward slashes: ... 'C:/Documents and Settings/Enrico...' or use the "r" modifier: ... r'C:\Documents and Settings\Enrico...' However, as a general practice, it's probably better to get the special directories from the environment: targetDir = os.environ['USERPROFILE'] + '\\My Documents\\Jr\'s Wallpapers' Remember that it's not called "Documents and Settings" on Vista... -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From zowtar at gmail.com Thu Jun 26 11:53:51 2008 From: zowtar at gmail.com (zowtar) Date: Thu, 26 Jun 2008 08:53:51 -0700 (PDT) Subject: url.encore/quote Message-ID: <889c0e25-c1e0-415b-b6db-f9e633a7eabb@d45g2000hsc.googlegroups.com> urlencode({'page': i, 'order': 'desc', 'style': 'flex power'}) return: page=1&order=desc&style=flex+power but I want: page=1&order=desc&style=flex%20power and url.quote don't put the &'s and ='s any idea guys? From dfh at forestfield.co.uk Sat Jun 14 05:23:18 2008 From: dfh at forestfield.co.uk (David Hughes) Date: Sat, 14 Jun 2008 02:23:18 -0700 (PDT) Subject: We are all consenting adults here Message-ID: <2cca4335-1162-4d61-b115-1f17d368721d@d1g2000hsg.googlegroups.com> Who coined this originally? I was reminded of it having just received a text message from mobile phone company Orange, in response to my request for them to review their policy of blocking access to this group (and, I suspect, all of Usenet). I quote: "Your request has been actioned and the content is confirmed as only suitable for customers over the age of 18. URL: http://groups/google.com/group/comp.lang.python" David From grante at visi.com Sat Jun 14 18:15:22 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 14 Jun 2008 17:15:22 -0500 Subject: Making wxPython a standard module? References: <6bidd7F3bg8usU1@mid.uni-berlin.de> <87fxrfx0h0.fsf@physik.rwth-aachen.de> <87wskrvhwd.fsf@physik.rwth-aachen.de> Message-ID: On 2008-06-14, Torsten Bronger wrote: >> [...] >> >> IMO, a few of the "un-Pythonic" things about wxPython are: >> >> 1) Window ID numbers. > > When I started to use wxPython, there was a newly-introduced > wx.ID_ANY that you could give instead of -1. My eyes filtered > it out after a couple of hours, just as they do with "self". Defining a new name for -1 is just painting the wart a different color. >> [...] >> >> 2) the "flags" parameter. > > Well, I like flags, and I don't see that they are unpythonic. I > find the code they produce very legible. You're saying that having the user or-together a bunch of bitmasks and pass the result as an integer is a common way for Python functions/object allow the user to turn optional features on and off? You must be using a different Python than I am. What I see used for that in the standard library modules are either named parameters with useful default values or individual object attributes. The only exceptions I can think are low level routines in the "os" and "socket" modules that allow direct access to things like Unix libc calls like open(), creat(), read(), write() and to the BSD sockets API. >> [...] >> >> 3) the parent/child tree > > See wx.ID_ANY. I don't see what the two have to do with each other, but maybe that's the root of all my problems. >> [...] >> >> 4) sizers > > Maybe because I come from TeX/LaTeX, i liked sizers > immediately. They worked well for me. I came from TeX/LaTeX also, and before wx, I spent a little time using Trestle GUI widgets which follow the TeX box-and-glue paradigm almost exactly. I guess I don't find wx sizers work much like TeX/LaTeX boxes. >> [...] >> >> 5) binding >> >> "What? you wanted a button that _did_ something when you >> clicked it?" > > You're right, this can be better. There's too much explicitness. > However, if you really hate the construct, you can define a > shortcut. I do. I sub-class wx.Button. Users should have to do that to get basic functionality that's required in 99.999% of the widget's use cases. Explicit is fine if it serves a purpose. I don't see the purpose of requiring a second line of code to bind a button to a callable. >> [...] >> >> 6) Thousands of wx.UPPER_CASE_INTEGER_HEX_CONSTANTS > > Thank you for the thorough explanations but in my opinion your > points are minor. They're minor in that they don't prevent you from writing programs that work, but they're not minor in that they unnecessarily increase the workload of the user without providing any benefit. They are sources of bugs. > Additionally, most of them are a matter of taste. I don't > think that because you didn't find sizers convenient, or some > parts too explicit, you can say that wxWidgets is un-Pythonic. Maybe a couple are just bad design decisions that weren't well thought out rather than being "un-Pythonic". OTOH, I consider that being well thoght out and well designed is one of the characteristics of Python, so things that aren't are un-Pythonic. > I rather have the impression that you like terseness, which is > totally okay but a different thing. I think that the most common use cases should be handled with a minimum of "extra" stuff having to be done by the user. It's just not Pythonic to require a user to specify default values for x,y,z when non-default valus for x,y,z are only used in 1 case out of 10000. In Python you use named parameters with default values. You don't use positional parameters and then tell the user "yes, I know this is useless almost all the time, so just pass a -1 if you want the default behavior. You shouldn't have to specifically ask for default behavior. You should only have to ask for non-default behavior. > I agree that changing the naming conventions and making use of > properties would increase pythonicness, but on an already high > level. I guess my views on what is "pythonic" are a lot different. I also don't think it's at all surprising that a C++ library like wxWidgets has an API that isn't very Pythonic. -- Grant Edwards grante Yow! I'm gliding over a at NUCLEAR WASTE DUMP near visi.com ATLANTA, Georgia!! From tjreedy at udel.edu Mon Jun 23 21:33:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Jun 2008 21:33:09 -0400 Subject: insertion sorts... In-Reply-To: <5f0111a3-c1b9-4864-bae3-32fa324c4e5e@j22g2000hsf.googlegroups.com> References: <06adb999-c7e2-4475-a49f-dbfbe042f4fd@r66g2000hsg.googlegroups.com> <5f0111a3-c1b9-4864-bae3-32fa324c4e5e@j22g2000hsf.googlegroups.com> Message-ID: Matimus wrote: > May I suggest you look into using `enumerate`: > >>>> for i, val in enumerate([4,5,6]): > ... print i, val > ... > 0 4 > 1 5 > 2 6 > > It allows you to get the index and the value at the same time, which > should eliminate the need for `aList.index`. I thought of suggesting that, but indirectly iterating over a list that is being modified with enumerate has the same problem as directly interating over the same changing list. From Lie.1296 at gmail.com Wed Jun 18 15:14:02 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 18 Jun 2008 12:14:02 -0700 (PDT) Subject: Does '!=' equivelent to 'is not' References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> <20080617120941.GE7349@dragontoe.org> Message-ID: <76aa0e1a-9242-4976-a1a2-9e7b258784c7@w4g2000prd.googlegroups.com> On Jun 18, 7:26?am, "Gabriel Genellina" wrote: > En Tue, 17 Jun 2008 09:09:41 -0300, Derek Martin ? > escribi?: > > > On Tue, Jun 17, 2008 at 04:33:03AM -0300, Gabriel Genellina wrote: > >> > Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)' > >> > and 'not(id(a) == id(b))' > > >> No. > > > Sure it is... he said "similar"... not identical. ?They are not the > > same, but they are similar. > > 'equality' and 'identity' are similar too, so the whole answer would make ? > no sense in that case. You can't explain identity based on things that ? > aren't identical. A fine grained question for a fine grained difference ? > requires a fine grained answer. In my defense, I admit I have the tendency to forget (purposefully) fine-grained differences if I thought that the difference was not significant enough in the context of speaking. The OP asked about != and 'is not', so I explained in terms of those being equality and identity testing respectively. To give a more concise and easy to understand example, I said that 'is not' is like using testing the 'id()' of the objects. Since (I think) the difference between != and 'is not' is much larger compared to the difference between 'is not' and 'id() test', I thought I could consider 'is not' and 'id() test' as "equivalent" in the context of this thread: 'Does != is equivalent to "is not"'. Either way, I'm sorry that I failed to put explicit notice that 'is not' and 'id() testing' isn't exactly the same either. > > Saying a flat "no" alone, without qualifying your statement is > > generally interpreted as rude in English... ?It's kind of like how you > > talk to children when they're too young to understand the explanation. > > Yucky. > > I didn't meant to be rude at all - and I apologize to Mr. Lie. I don't deserve the apology because the mistake is on me and I didn't feel offended, in fact I'm delighted someone could point out my mistake. > The ? > explanation for such strong "No" was in the paragraph below it (the idea ? > was to say: "No to this, yes to that") From duncan.booth at invalid.invalid Mon Jun 9 04:12:31 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jun 2008 08:12:31 GMT Subject: Parsing a path to components References: <7d7dd66c-b2bb-4a9a-a2e4-589079cda97b@e39g2000hsf.googlegroups.com> <14bf5448-4677-4ced-9d79-b4eb0c048218@56g2000hsm.googlegroups.com> <6auuc5F38s3s9U1@mid.uni-berlin.de> <_rydnW6Tc6hjBdfVnZ2dnUVZ_oadnZ2d@comcast.com> Message-ID: "Mark Tolonen" wrote: >> Can you recommend a generic way to achieve this ? >> Eli > >>>> import os >>>> from os.path import normpath,abspath >>>> x=r'\foo\\bar/baz//spam.py' >>>> normpath(x) > '\\foo\\bar\\baz\\spam.py' >>>> normpath(abspath(x)) > 'C:\\foo\\bar\\baz\\spam.py' >>>> normpath(abspath(x)).split(os.sep) > ['C:', 'foo', 'bar', 'baz', 'spam.py'] That gets a bit messy with UNC pathnames. With the OP's code the double backslah leadin is preserved (although arguably it has split one time too many, '\\\\frodo' would make more sense as the first element: >>> parse_path(r'\\frodo\foo\bar') ['\\\\', 'frodo', 'foo', 'bar'] With your code you just get two empty strings as the leadin: >>> normpath(abspath(r'\\frodo\foo\bar')).split(os.sep) ['', '', 'frodo', 'foo', 'bar'] -- Duncan Booth http://kupuguy.blogspot.com From piyush.subscription at gmail.com Tue Jun 24 15:29:33 2008 From: piyush.subscription at gmail.com (Piyush Anonymous) Date: Wed, 25 Jun 2008 00:59:33 +0530 Subject: sending executable data over network.. In-Reply-To: References: <19ac19520806232359r31f74c7bk9f5d47eb3540e457@mail.gmail.com> <200806241245.35047.omer@no-log.org> <19ac19520806240547m172941b2k52777e47b9a84711@mail.gmail.com> Message-ID: <19ac19520806241229i6bbc3f1dh21f1c4f9103b5f2e@mail.gmail.com> assuming security is not of concern at the moment, how can i add in update capability? please help me out or show some pointers to look into. i wish to change the way the method definition of a class at run time in a running server (actually i m planning to support many changes at run time). new code which is to be executed is provided by a client at different location. i am receiving the code as a string and compile it on server-side with the 'compile' builtin function or get compiled code using marshal. however i cannot link it to the running code in server? for example, i get a new method definition for a method in class and i wish to change it. client sent new definition, i compile it in server, getting a code object. how can i link it to old code? if it will running in same environment, i could simply write A.getdata=getdatanew # A is a class how should i do it here? should i change the way i am receiving the code? thanks for help -piyush On Wed, Jun 25, 2008 at 12:22 AM, Terry Reedy wrote: > > > Piyush Anonymous wrote: > >> any idea or pointer how i could link it to running code in server? >> for example, i get a new method definition for a method and i wish to >> change it. >> client sent new definition, i compile it in server. how can i link it to >> old code? >> > > Code to be hot-updated (while running) must have update capability builtin. > But please consider security. If a remote system can log in and *push* > code, an attacker can potentially do the same. Notice that self-updating > programs and systems generally log out to a hardwired location, ask if there > are updates, and *pull* the new code. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bob.martin at excite.com Fri Jun 6 02:58:45 2008 From: bob.martin at excite.com (Bob Martin) Date: Fri, 06 Jun 2008 06:58:45 GMT Subject: Books for learning how to write "big" programs References: <219c77ef-dd0c-464b-bb6a-e4f3bee89eae@x41g2000hsb.googlegroups.com> <304580c2-bdfb-4564-8507-d742d9eaf5a8@79g2000hsk.googlegroups.com> Message-ID: in 69148 20080605 140635 s0suk3 at gmail.com wrote: >On May 22, 12:49=A0pm, "Kurt Smith" wrote: >> On Thu, May 22, 2008 at 10:55 AM, duli wrote: >> > Hi: >> > I would like recommendations forbooks(in any language, not >> > necessarily C++, C, python) which have walkthroughs for developing >> > a big software project ? So starting from inception, problem >> > definition, design, coding and final delivery on a single theme >> > or application. >> >> The bigger the project, the more likely it is that you'll have >> documentation on how to use it (for a language or library, how to use >> the features in your program) but to take the time to write up a >> dead-tree book on the project's "inception, problem definition, >> design, coding and final delivery" is not likely well spent. =A0Anyone >> who has the expertise to write such a book would probably be spending >> his time working on the next phase of the project itself. >> >> Someone will probably respond with an amazon link to a book that does >> exactly what you're asking, in which case, I will stand corrected. >> But I'll be surprised. >> >> >> >> > Most of the code I have written andbooksthat I have read deal with >> > toy programs and I am looking for something a bit more >> > comprehensive. =A0For example, maybe a complete compiler written in C++ >> > for some language, or a complete web server or implementing >> > .net libraries in some language (just a few examples of the scale of >> > things I am interested in learning). >> >> It seems to me the reason toy programs are so prevalent is because >> they illustrate a (few) well defined ideas in a short amount of code. >> A big project, necessarily, brings together all kinds of stuff, much >> of which may not interest the author at all, and so doesn't motivate >> him to write a book about it. >> >> Compilers, web servers & .NET libraries are *widely* varying areas. >> You may have interest in them all, but to significantly contribute to >> any requires a fair amount of expertise and specialization. >> >> The best route I've found to learn how to organize & program large >> scale applications is this: find a cutting edge program that interests >> you and that is open source. =A0Download its source, and read the code. >> Diagram it. =A0Map it out. =A0Read the comments. =A0Join the mailing list >> (probably the developer's list), lurk for a while, and ask questions >> about why they organized things the way they did. =A0Get the overall big >> picture and learn from it. =A0Better yet, find out what pitfalls they >> found and avoided (or fell into). =A0Compare their approach & >> organization with another competing project. =A0This is the wonder of >> open source software -- you have access to everything, and can learn >> from all the expertise the developers put into their opus. >> >> You can learn the basics frombooks, but nothing beats analyzing a >> species in the wild. > >I think I have lately understood what you mean, thanks to Programming >Python 3rd Ed by Lutz. It doesn't teach Python itself -- the book aims >to teach Python programming at an application level, but I'm starting >to wonder whether that knowledge can be obtained from any book. The >book goes through over 1500 pages (!) giving small- and medium-sized >example programs and describing their details. Roughly after a couple >of hundred pages I started to feel like all that was trivial (isn't >looking at code and figuring their details what we do in our every-day >programmer lifes?), and then started to feel like it was really >useless. Maybe large-scale programming can only be self-thought in >every day life, am I right?. Of course. From dbpokorny at gmail.com Mon Jun 30 14:18:07 2008 From: dbpokorny at gmail.com (dbpokorny at gmail.com) Date: Mon, 30 Jun 2008 11:18:07 -0700 (PDT) Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> Message-ID: On Jun 27, 9:09 am, "John Salerno" wrote: > Of course, I suppose whether or not any of this matters depends on if you > are a web designer or a programmer, but am I missing something about > templates, or is it really the case that they, more or less by definition, > combine content and logic? This is a little anecdote about "separation of presentation, content, and logic." I used to work in a web application development environment that resembled Visual basic. The application presented its data through a java applet, and the server was written in lisp. If you were able to avoid the bugs (a bit like the fire swamps from The Princess Bride) then you could be fairly productive. The server took 45 seconds to start, took up a gigabyte of memory, and the applet took up 50 megabytes of memory in the browser and had sluggish performance. When I got a job as a LAMP, P = python developer, I first created a little program that would sift content in an "xhjp" file (which stood for "cross between html, javascript, and python.") The big idea was: you could write "dynamic elements" like so: {{{
    Python code to render a chunk of XML ||| Javascript code to use the XML to do something interesting }}} There was a makefile that turned a single xhjp into a javascript file, and html file, and a python file. The hope was that you could think about the logic of elements in a single place. I thought this was a great idea and that it would be a big help in development, but it turned out to be a drag. Eventually I realized that I had to get my hands dirty and write a decent javascript framework to manage the page layout. This was somewhat painful, since among other things firefox doesn't report javascript exceptions that occur in response to an async http (commonly known as AJAX) request, but now swapping components in and out of the page is relatively easy. Currently the app gets its information with JSON (highly recommended), and tells the server what it wants with a "why" dict entry in the async http post (the information sent to the server is bundled in a dict). The server runs Django. To give you an idea of the current design, an async post scrapes a piece of information off of every dom element whose class is "context", bundles it with a "why", and provides a custom callback (this is far from ideal, something of a compromise). The vast majority of the dom elements are constructed with dhtml using information supplied by the server; this is possible because it is a intranet app. A public web app would do this with a template, before it hits the browser. BTW there is a good document design_philosophies.txt in the Django documentation. They have a section on why you *don't* want to put python code in your html. Cheers, David From cooperq at gmail.com Wed Jun 18 01:47:49 2008 From: cooperq at gmail.com (cooperq at gmail.com) Date: Tue, 17 Jun 2008 22:47:49 -0700 (PDT) Subject: Hrounding error Message-ID: Hi, I am new to python. I was messing around in the interperator checking out the floating point handling and I believe I may have found a rounding bug: >>> 234 - 23234.2345 -23000.234499999999 This is not correct by my calculations. I am using python 2.5.2 in ubuntu 8.04. I am wondering if this is a known bug, or if I am just not understanding some feature of python. Thanks for the help! -Cooper Quintin http://www.bitsamurai.net From cokofreedom at gmail.com Tue Jun 24 03:52:07 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 24 Jun 2008 00:52:07 -0700 (PDT) Subject: Python 3000 vs Perl 6 References: Message-ID: On Jun 24, 8:20 am, "Corey G." wrote: > If Perl 6 ever does get on its feet and get released, how does it > compare to Python 3000? Is Perl 6 more like Java now with Parrot? I > just want to make sure that Python is staying competitive. > > If this is the wrong mailing list, just let me know. Thanks! Do you mean in terms of speed (parrot is a JIT?). I believe Python 3k will (when out of beta) will have a speed similar to what it has currently in 2.5, possibly with speed ups in some locations. But competitive-wise I think the point is Python 3k tries to remove warts from the Python Language to make it even more friendly to readers and writers alike. In that way it should/will stay competitive. However towards overall usage, the general advice is to stay with the 2.x series for now, trying to ensure your code style is moving towards the Py3k style, and then make the jump to the 3.x series when it is finialised. Another point, is Perl 6 ever going to get released :P From mrmakent at cox.net Fri Jun 13 14:38:15 2008 From: mrmakent at cox.net (Mike Kent) Date: Fri, 13 Jun 2008 11:38:15 -0700 (PDT) Subject: Subclassing list, what special methods do this? Message-ID: <7ba7e964-2d34-4594-8cfc-79dbf904df18@f63g2000hsf.googlegroups.com> For Python 2.5 and new-style classes, what special method is called for mylist[2:4] = seq and for del mylist[2:4] (given that mylist is a list, and seq is some sequence)? I'm trying to subclass list, and I'm having trouble determining what special methods I have to override in my class for the above two operations. From my testing, it seems to be __setslice__ for both, but the docs say __setslice__ and brethren are deprecated. I would have thought that __setitem__ and __delitem__ would be what was called, but again, my testing says otherwise. From __peter__ at web.de Sun Jun 1 04:34:49 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 01 Jun 2008 10:34:49 +0200 Subject: Merging ordered lists References: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> Message-ID: etal wrote: > Here's an algorithm question: How should I efficiently merge a > collection of mostly similar lists, with different lengths and > arbitrary contents, while eliminating duplicates and preserving order > as much as possible? > > My code: > > def merge_to_unique(sources): > """Merge the unique elements from each list in sources into new > list. > > Using the longest input list as a reference, merges in the > elements from > each of the smaller or equal-length lists, and removes duplicates. > > @return: Combined list of elements. > """ > sources.sort(None, len, True) # Descending length > ref = sources[0] > for src in sources[1:]: > for i, s in enumerate(src): > if s and (ref[i] != s) and s not in ref: > ref.insert(ref.index(src[i-1])+1, s) > # Remove duplicates > return [r for i, r in enumerate(ref) if r and r not in ref[i+1:]] > > > This comes up with using the CSV module's DictWriter class to merge a > set (list, here) of not-quite-perfect CSV sources. The DictWriter > constructor needs a list of field names so that it can convert > dictionaries into rows of the CSV file it writes. Some of the input > CSV files are missing columns, some might have extras -- all of this > should be accepted, and the order of the columns in the merged file > should match the order of the input files as much as possible (not > alphabetical). All of the list elements are strings, in this case, but > it would be nice if the function didn't require it. > > Speed actually isn't a problem yet; it might matter some day, but for > now it's just an issue of conceptual aesthetics. Any suggestions? #untested import difflib def _merge(a, b): sm = difflib.SequenceMatcher(None, a, b) for op, a1, a2, b1, b2 in sm.get_opcodes(): if op == "insert": yield b[b1:b2] else: yield a[a1:a2] def merge(a, b): return sum(_merge(a, b), []) def merge_to_unique(sources): return reduce(merge, sorted(sources, key=len, reverse=True)) Peter From ralphzajac at sbcglobal.net Sun Jun 8 20:51:53 2008 From: ralphzajac at sbcglobal.net (ralphz) Date: Sun, 08 Jun 2008 17:51:53 -0700 Subject: How to close app after x seconds. Message-ID: Hi I have small app that I want to close tself after x seconds. Basically start show some message and close. I come up with something like this but it does not work. Can anyone help me with it? #!/usr/bin/env python import wx import time class MyFrame(wx.Frame): def __init__(self, title, pos, size): wx.Frame.__init__(self, None, -1, title, pos, size) self.CreateStatusBar() self.SetStatusText("Some message here") class MyApp(wx.App): def OnInit(self): self.frame = MyFrame('TITLE', (100, 100), (400,100)) self.frame.Show() self.SetTopWindow(self.frame) self.ID_Timer = wx.NewEventType() self.timer = wx.Timer(self, self.ID_Timer) self.timer.Start(5000, False) self.Bind(wx.EVT_TIMER, self.appclose, self.timer) # wx.EVT_TIMER(self, self.ID_Timer, self.appclose) return True def appclose(self, evt): self.frame.Destroy() if __name__ == '__main__': app = MyApp(0) app.MainLoop() Ralph http://TheOrangeIT.org From spectrumdt at gmail.com Wed Jun 4 12:01:52 2008 From: spectrumdt at gmail.com (spectrumdt at gmail.com) Date: Wed, 4 Jun 2008 09:01:52 -0700 (PDT) Subject: Trying to extend Python with C: undefined reference to `Py_BuildValue' References: <045458d3-771b-459d-b5ef-21d8f3c08659@2g2000hsn.googlegroups.com> Message-ID: On Jun 4, 4:13?pm, Ivan Illarionov wrote: > Hi! Your C code contains too many errors. I'm lazy to comment them all. > > 2. create 'buildme.py' file with this content: > Thanks for the replies. Maybe I should have read the rest of the guide to extending Python with C before whining here. I hadn't noticed the part where I was supposed to create a script to compile my C code rather than just call gcc. I fixed that, and now it works. Thanks. Yeah, my C code is probably full of bugs, too. I am a sucky C programmer. :P From deets at nospam.web.de Thu Jun 12 08:25:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 12 Jun 2008 14:25:08 +0200 Subject: Strange bug doesn't occur in Pydb References: <6bb01lF38u72tU1@mid.uni-berlin.de> Message-ID: <6bciubF3asvq1U1@mid.uni-berlin.de> kj wrote: > In <6bb01lF38u72tU1 at mid.uni-berlin.de> "Diez B. Roggisch" > writes: > >>kj schrieb: >>> I'm running into a strange seg fault with the module cjson. The >>> strange part is that it does not occur when I run the code under >>> Emacs' Pydb. >>> >>> Here's an example: >>> >>> >>> import sys, cjson >>> >>> d1 = {'a': 1, 'b': 2, 'c': 3} >>> print sys.version >>> j1 = cjson.encode(d1) >>> print j1 # should print the string '{"a": 1, "c": 3, "b": 2}' >>> >>> The code above runs fine under Pydb, but segfaults at the call to >>> cjson.encode when I run it from the command line in a standard >>> Linux shell interaction. In the printed version strings are >>> identical. >>> >>> I figure this must be a bug in cjson. I'd love to find a workaround >>> for it, and hope that this strange difference between Pydb and the >>> shell command line may be a clue to that. >>> >>> Any thoughts? > >>Are you sure you actually run the same interpreter in emacs as you do on >>the commandline? > > No, I'm not. All I know is that both Emacs and the commandline > are running on the same machine, and that the version string that > the program prints is the same in both conditions. How can I verify > that that the same interpreter is running in both cases? By e.g. import sys print sys.prefix Additionally, you should compare what sys.path contains and if it's the same - otherwise it might be that cjson is picked up from somewhere else. If all that's the case, I'd invoke python through gdb and see where the segfault happens. BTW: I've been using (and even patching) cjson - without any troubles whatsoever. Diez From gh at ghaering.de Mon Jun 9 09:36:53 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 09 Jun 2008 15:36:53 +0200 Subject: lists to save in a tuple In-Reply-To: <130e261e-1e1a-4657-b8db-8a7704fb083d@z66g2000hsc.googlegroups.com> References: <130e261e-1e1a-4657-b8db-8a7704fb083d@z66g2000hsc.googlegroups.com> Message-ID: Nader wrote: > Hello, > > I have two lists and would save them in a tuple. > > a = [1,2,3] > b = ['a','b','c'] > > with the next statement I can do that: > > t = [(x,y), for x in a for y in b] > > This gives the next list: > > [(1,'a'),(1,'b'),(1,'c'), (2,'a'),(2,'b'),(2,'c'), (3,'a'),(3,'b'), > (3,'c')] > > But I want the next list: > > [(1,'a'),(2,'b'),(3,'c')] > > Would somebody tell me how I can solve this problem? Use the zip() builtin. zip(a, b) -- Gerhard From Russ.Paielli at gmail.com Mon Jun 9 14:17:37 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 9 Jun 2008 11:17:37 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <484cf660$0$15495$426a74cc@news.free.fr> Message-ID: <6efd1deb-5e53-46d1-803a-f855a1f409be@a9g2000prl.googlegroups.com> On Jun 9, 2:23 am, Bruno Desthuilliers wrote: > Mark Wooding a ?crit : > > > > > Fuzzyman wrote: > > >> So, you are stating that no API programmer using Python *ever* has a > >> valid or genuine reason for wanting (even if he can't have it) genuine > >> 'hiding' of internal state or members from consumers of his (or > >> her...) API? > > > I don't want to speak for whoever you were responding to, but from my > > point of view... > > > Yes. > > > I understand the difference between the documented interface of a system > > and the details of its implementation. But sometimes it can be useful > > to take advantage of implementation details, particularly if the > > published interface is inadequate in some way. Whether or not I choose > > to make use of implementation details is a trade-off between immediate > > convenience and maintainability, but that's something I can make a > > rational decision about. > > > By enforcing your `data hiding', you're effectively telling me that I'm > > too stupid to make rational decisions of this sort. And that's actually > > extremely insulting. > > I couldn't state it better. +1QOTW btw. Please see my previous reply to that post. Being "insulted" by data hiding is the "QOTW"? I'd call that an insult to everyone else who has posted on this forum in the past week. Unless of course you mean "silliest QOTW." From larry at portcommodore.com Sun Jun 29 00:18:30 2008 From: larry at portcommodore.com (larry at portcommodore.com) Date: Sat, 28 Jun 2008 21:18:30 -0700 (PDT) Subject: help debugging noob code - converting binary data to images... Message-ID: <56955a42-155c-4c37-9bf6-5a99cadb5c79@l42g2000hsc.googlegroups.com> Ok I'm a Python noob, been doing OK so far, working on a data conversion program and want to create some character image files from an 8-bit ROM file. Creating the image I've got down, I open the file and use TK to draw the images... but 1) It does not seem to end (running in IDLE), I have to kill the process to retry it seems tkinter does not close(?) 2) Once I added the Image module open won't open my binary file (complains its not an image file, which is isnt.) I am sure I need to prefix open with something but I can't seem to find an example of how to word it, Below is the code (if it is lousy its because I've mainly been borrowing by examples as I go...) Any suggestions are gretly appreciated. #!/usr/local/bin/python from Tkinter import * from string import * from Image import * root = Tk() root.title('Canvas') #open commodore Cset rom cset = open("chargen","r") canvas = Canvas(width=16, height=16, bg='white') canvas.pack(expand=YES, fill=BOTH) # character size factor size = 2 # read all 512 characters from ROM for cchar in range(0, 511, 1): #draw line while charline < 8: position = 0 x = cset.read(1) ch = ord(x) # draw pixels while position < 8: if ch & ( 2 ** position ): xp = 1+(7-position)*size yp = 1+charline*size canvas.create_rectangle(xp,yp,xp+size,yp+size, fill='black', width=0) position += 1 charline += 1 #save character image outfile = "/home/mydir/work/char"+zfill(cchar,3)+".png" canvas.save(outfile,"png") #clear canvas for next char... canvas.create_rectangle(1,1,size*8,size*8, fill='white', width=0) root.mainloop() From beema.shafreen at gmail.com Fri Jun 13 02:45:15 2008 From: beema.shafreen at gmail.com (Beema shafreen) Date: Fri, 13 Jun 2008 12:15:15 +0530 Subject: e-value Message-ID: Hi all, I have file which includes the e_value i want to fetch the lines if the line with the e_value which is less than 0.01 so I have script but it doesn't work. can you please tell me is this the right way. The script does not end up with any error. It work if is give the condition evalue > 0.01 my script: >>> for line in fh: ... gi, seq, e_value = line.strip().split('\t') ... if e_value < 0.01: ... print e_value ... >>> sample data file: gi|7290649| IWHHTFYNELR 4.6e-02 gi|108883867| TITLEVEPSDTIENVK 7.8e-02 gi|157018218| LFEGGFDTLNK 2.2e-03 gi|34420406| YMVGPIEEVVEK 7.5e-04 gi|118791575| ATIKDEITHTGQFYEANDYR 9.4e-03 gi|78706974| LLSGVTIAQGGVLPNIQAVLLPK 5.2e-02 gi|157015257| VDDDVAVTDEK 1.0e-02 gi|28571691| QAGEVTYADAHK 2.2e-02 gi|89954247| VETGVLKPGTVVVFAPVNLTTEVK 4.4e-03 gi|78101790| LFEGGFDTLNK 2.2e-03 gi|157021047| LLSGVTIAQGGVLPNIQAVLLPK 7.3e-05 gi|157138410| LLSGVTIAQGGVLPNIQAVLLPK 5.2e-02 gi|27820013| LTDEEVDEMIR 2.6e-03 gi|56417572| TITLEVEPSDTIENVK 7.8e-02 gi|157020596| HPGSFEIVHVK 5.8e-02 can anybody help me reagrding this. -- Beema Shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From raoyitao at gmail.com Thu Jun 12 04:10:23 2008 From: raoyitao at gmail.com (Royt) Date: Thu, 12 Jun 2008 01:10:23 -0700 (PDT) Subject: Please recommend a blog program written using python-cgi Message-ID: <4f16f948-1082-4d3a-9276-cac97945c96b@x1g2000prh.googlegroups.com> Hi, I'm a newbie to Python, but I think it won't be too hard to learn. A few days ago I registered Google App Engine, it only support Python 2.5. I want to set my blog on it soon. But it's not easy for me to finish it in a short time since I'm not very familiar with Python, so I want find some codes available, throught reading the code, I can learn something from it. I know there are many frameworks for web development, but I just want the code using traditional CGI method, it's easy to use and it doesn't require any additional knowledge about framework. I need a simple example (support basic function of a weblog, easy to revise) but not a complicated huge monster (I don't think such a thing now exists). I find some online course, i.e. http://www.upriss.org.uk/python/PythonCourse.html & http://www.python.org/doc/essays/ppt/sd99east/index.htm but I didn't find the code needed, could anyone recommend it to me? thanks. From cokofreedom at gmail.com Fri Jun 6 02:53:22 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 5 Jun 2008 23:53:22 -0700 (PDT) Subject: Newb question: underscore References: <873anrl8p5.fsf@benfinney.id.au> <87y75jjeqo.fsf@benfinney.id.au> Message-ID: <601115a1-c788-4be7-b6b4-92cf159559bd@f36g2000hsa.googlegroups.com> > > My question is: Why would anyone decide to obfuscate something as easy > > to read as Python??? > > They didn't decide to obfuscate; they decided to follow a > strongly-expected convention for the name of that function by existing > users of the 'gettext' functionality, in contexts that predate the > appearance of that functionality in Python. > Well _ can also mean the previous output statement that wasn't null, so it has OTHER uses... From mccredie at gmail.com Thu Jun 19 19:23:57 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 19 Jun 2008 16:23:57 -0700 (PDT) Subject: python/ruby question.. References: <39801514-d2b8-4926-b56b-39856d79b0dd@d1g2000hsg.googlegroups.com> Message-ID: <1c699ba8-8a33-41e3-b1e7-82d28633f25a@z66g2000hsc.googlegroups.com> On Jun 19, 4:00?pm, Matimus wrote: > On Jun 18, 8:33?pm, "bruce" wrote: > > > > > hi... > > > can someone point me to where/how i would go about calling a ruby app from a > > python app, and having the python app being able to get a returned value > > from the ruby script. > > > something like > > > test.py > > ?a = os.exec(testruby.rb) > > > testruby.py > > ?foo = 9 > > ?return foo > > > i know this doesn't work... but i've been searching for hours on this with > > no luck.... (and yeah, i'm relatively new to both ruby/python!!) > > > thanks > > Both Ruby and Python appear to support XMLRPC. I haven't used XMLRPC > in Ruby, but in general you create a server and expose some functions. > On the client end (Python) you would do something like this (assuming > you are serving on port 8050): > > import xmlrpclib > > rubyserver = xmlrpclib.Server("http://localhost:8050") > x = rubyserver.foo(1,2,3) > > where 'foo' is a function served by the ruby server and x is its > return value. > > some links: > > http://www.ruby-doc.org/stdlib/libdoc/xmlrpc/rdoc/index.html > > Good python server and client examples on this page: > > http://docs.python.org/lib/simple-xmlrpc-servers.html > > I can't be of much help for ruby, and that link doesn't seem to help > much other than to say 1. it exists and 2. its easy. > > Matt Here is a more complete example. The ruby server code: require "xmlrpc/server" s = XMLRPC::Server.new(8080) s.add_handler("add") do |a,b| a + b end s.add_handler("div") do |a,b| if b == 0 raise XMLRPC::FaultException.new(1, "division by zero") else a / b end end s.set_default_handler do |name, *args| raise XMLRPC::FaultException.new(-99, "Method #{name} missing" + " or wrong number of parameters!") end s.serve I put the above code into a file xmlrpctest.rb and ran it at the command line. Then I opened the python interpreter in a separate window and did this: >>> s = xmlrpclib.Server("http://localhost:8080") >>> s.div(100,2.0) 50.0 >>> s.add(100000, 2) 100002 >>> In the long run you may still want to use the subprocess module to launch the ruby xmlrpc server, but once you do that communicating between the two processes should be pretty simple. Matt From Scott.Daniels at Acm.Org Tue Jun 10 08:55:12 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 10 Jun 2008 05:55:12 -0700 Subject: Parsing a path to components In-Reply-To: <7d7dd66c-b2bb-4a9a-a2e4-589079cda97b@e39g2000hsf.googlegroups.com> References: <7d7dd66c-b2bb-4a9a-a2e4-589079cda97b@e39g2000hsf.googlegroups.com> Message-ID: eliben wrote: ... a prety good try ... > def parse_path(path): > """...""" By the way, the comment is fine. I am going for brevity here. > lst = [] > while 1: > head, tail = os.path.split(path) > if tail == '': > if head != '': lst.insert(0, head) > break > else: > lst.insert(0, tail) > path = head > return lst > ---------------------------------- > > Did I miss something and there is a way to do this standardly ? Nope, the requirement is rare. > Is this function valid, or will there be cases that will confuse it ? parse_path('/a/b/c//d/') Try something like: def parse_path(path): '''...same comment...''' head, tail = os.path.split(path) result = [] if not tail: if head == path: return [head] # Perhaps result = [''] here to an indicate ends-in-sep head, tail = os.path.split(head) while head and tail: result.append(tail) head, tail = os.path.split(head) result.append(head or tail) result.reverse() return result --Scott David Daniels Scott.Daniels at Acm.Org From danb_83 at yahoo.com Sat Jun 14 00:03:09 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Fri, 13 Jun 2008 21:03:09 -0700 (PDT) Subject: numpy: handling float('NaN') different in XP vs. Linux References: Message-ID: <369beb8f-986e-4112-b232-eeed01d7ddb7@w34g2000prm.googlegroups.com> On Jun 13, 10:45?pm, "John [H2O]" wrote: > I have a script: > > from numpy import float > OutD=[] > v=['3','43','23.4','NaN','43'] > OutD.append([float(i) for i in v[1]]) > > On linux: > Python 2.5.1 (r251:54863, Mar ?7 2008, 04:10:12) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > [john at andLinux analysis]$ python jnk.py > [[3.0, 43.0, 23.399999999999999, nan, 43.0]] > > On XP: > Python 2.5 (r25:51908, Mar ?9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > C:\analysis>C:\Python25\python.exe jnk.py > Traceback (most recent call last): > ? File "jnk.py", line 4, in > ? ? OutD.append([float(i) for i in v]) > ValueError: invalid literal for float(): NaN Python just uses the atof() function from the underlying C library. Some of them handle NaN's, and some of them don't. If you want to get NaN on a platform where float('NaN') doesn't work, try 1e1000 / 1e1000. Or failing that, struct.unpack('d', struct.pack('Q', 0xfff8000000000000))[0] From leoncamel at gmail.com Sun Jun 1 10:32:39 2008 From: leoncamel at gmail.com (Leon zhang) Date: Sun, 1 Jun 2008 07:32:39 -0700 (PDT) Subject: the pipe reading in Thread dose not work. Message-ID: <80750570-0a03-4006-99f4-23943aa56177@u6g2000prc.googlegroups.com> #!/usr/bin/env python # -*- coding: utf-8 -*- import string, sys from threading import Thread import os import time class test_pipe(Thread): def __init__(self, fd): Thread.__init__(self) self.testfd = fd def run(self): print "started thread begin -----" while True: buf = self.testfd.read() print "receive %s" % (buf) time.sleep(1) #print "hoho" if __name__ == "__main__": stdin_r, stdin_w = os.pipe() #stdout_r, stdout_w = pipe() f_w = os.fdopen(stdin_w, "w", 0) thrd = test_pipe(os.fdopen(stdin_r, "r", 0)) thrd.start() time.sleep(1) while True: f_w.write("help\r\n") time.sleep(1) thrd.join() -------------------------------------------- well, I want the following small test about pipe() in thread(). OK, I write to the pipe in the main thread, and I created a new thread for reading from the pipe, then it will print what it received from the pipe(). But, it seems it block at the "self.testfd.read()". So, is there and suggestion and explaination about it? Thanks in advance. From news at prodata.co.uk Tue Jun 17 13:23:20 2008 From: news at prodata.co.uk (John Dann) Date: Tue, 17 Jun 2008 18:23:20 +0100 Subject: Numeric type conversions References: Message-ID: On Tue, 17 Jun 2008 08:58:11 -0700 (PDT), MRAB wrote: >[snip] >Please note that in slicing the start position is included and the end >position is excluded, so that should be ByteStream[12:14]. Yes, I just tripped over that, in fact, hence the error in my original post. I suppose there must be some logic in including the start position but excluding the end position, though it does escape me for now. I can understand making a range inclusive or exclusive but not a mixture of the two. Suppose it's just something you have to get used to with Python and, no doubt, much commented on in the past. JGD From barry at python.org Thu Jun 19 07:53:10 2008 From: barry at python.org (Barry Warsaw) Date: Thu, 19 Jun 2008 07:53:10 -0400 Subject: [Python-3000] RELEASED Python 2.6b1 and 3.0b1 In-Reply-To: <79990c6b0806190143n58e51a22ubafd3fe343291dfb@mail.gmail.com> References: <1972109D-735D-4485-82F4-9BC8F2984967@python.org> <79990c6b0806190143n58e51a22ubafd3fe343291dfb@mail.gmail.com> Message-ID: <5A74EFE6-0915-4EF9-9096-3CE75F32F00E@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Jun 19, 2008, at 4:43 AM, Paul Moore wrote: > On 19/06/2008, Barry Warsaw wrote: >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> On behalf of the Python development team and the Python community, >> I am >> happy to announce the first beta releases of Python 2.6 and Python >> 3.0. > > Any ETA for Windows builds? The web pages still point to the alphas. > (I'd like to see the Windows builds more closely integrated with the > releases now we're in beta stage...) Martin usually fills these in pretty quickly. I think the current situation works fine for the betas but we'll make sure the final release (and candidates) are better coordinated. - -Barry -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQCVAwUBSFpIpnEjvBPtnXfVAQJyWQP9FSH8Ipg93UDM3nmH3UtN+i61YGsQPd0O ypHlnz4yHpxeRkJm1zkppHHI0hKMou6JOeUf05QCnPzrAdsG/mkuv5aoBrBt3dDd UncHLoQOvXEhGrrPzexmHKv3ehxUXPQOzkiWBWVv9e69GYH4e4HcqV6s2Ya2733T zC/EyOgkyMg= =5wM5 -----END PGP SIGNATURE----- From sri_annauni at yahoo.co.in Fri Jun 13 12:29:06 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Fri, 13 Jun 2008 21:59:06 +0530 (IST) Subject: Python Socket programming Message-ID: <655455.29695.qm@web7907.mail.in.yahoo.com> Hi, I am going to do some socket related programming in Python. Before that, I wish to know the Gotchas of Python Scoket Programming. Can anyone send me any link that satisfies my needs?? Thanks, Srini Explore your hobbies and interests. Go to http://in.promos.yahoo.com/groups/ From chradcliffe at gmail.com Thu Jun 26 17:58:26 2008 From: chradcliffe at gmail.com (Craig Radcliffe) Date: Thu, 26 Jun 2008 17:58:26 -0400 Subject: Help me on Backspace please In-Reply-To: <6fe75aa0-721e-42a1-83e4-ceee24853000@w7g2000hsa.googlegroups.com> References: <6fe75aa0-721e-42a1-83e4-ceee24853000@w7g2000hsa.googlegroups.com> Message-ID: Something like this might do the trick: import re f = open("file.txt") old_text = f.readlines() f.close() new_text = [re.sub(r'.\b', '', i) for i in old_text] f = open("file_modified.txt", "w") f.writelines(new_text) I don't know how necessary the separate read and writes are, but it'll be good for a start. At any rate, you'll want to look at the remodule. On Thu, Jun 26, 2008 at 16:32, wrote: > Hi > I am a beginner on Python and have a problem.. > > I have text file and reading it line by line and there are backspace > characters in it like '\b' or anything you want like "#". I want to > replace these chars. with Backspace action. I mean deleting the > previous char. and the \b char also. and writing all cleaned text to a > file again. > > How can I do that. > > Thanks.. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gerard.blais at gmail.com Thu Jun 12 07:33:28 2008 From: gerard.blais at gmail.com (Gerry) Date: Thu, 12 Jun 2008 04:33:28 -0700 (PDT) Subject: Converting a simple python script to a simple windows executable References: Message-ID: On Jun 12, 4:04?am, William McBrine wrote: > On Wed, 11 Jun 2008 12:25:29 -0700, geoffbache wrote: > > (1) py2exe. This is really for when python isn't installed on the remote > > user's machine, so it requires you to distribute a large amount of DLLs > > etc which are part of the python installation. A bit silly when I know > > that the remote user has python anyway. > > If you know the target user has Python installed, why don't you just > distribute the .pyw file? (Use ".pyw" instead of ".py" to avoid the extra > console window.) > > -- > 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on I really like cx_freeze: http://python.net/crew/atuining/cx_Freeze/ From george.sakkis at gmail.com Tue Jun 10 22:15:16 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 10 Jun 2008 19:15:16 -0700 (PDT) Subject: Confusion with weakref, __del__ and threading Message-ID: I'm baffled with a situation that involves: 1) an instance of some class that defines __del__, 2) a thread which is created, started and referenced by that instance, and 3) a weakref proxy to the instance that is passed to the thread instead of 'self', to prevent a cyclic reference. This probably sounds like gibberish so here's a simplified example: ========================================== import time import weakref import threading num_main = num_other = 0 main_thread = threading.currentThread() class Mystery(object): def __init__(self): proxy = weakref.proxy(self) self._thread = threading.Thread(target=target, args=(proxy,)) self._thread.start() def __del__(self): global num_main, num_other if threading.currentThread() is main_thread: num_main += 1 else: num_other += 1 def sleep(self, t): time.sleep(t) def target(proxy): try: proxy.sleep(0.01) except weakref.ReferenceError: pass if __name__ == '__main__': for i in xrange(1000): Mystery() time.sleep(0.1) print '%d __del__ from main thread' % num_main print '%d __del__ from other threads' % num_other ========================================== When I run it, I get around 950 __del__ from the main thread and the rest from non-main threads. I discovered this accidentally when I noticed some ignored AssertionErrors caused by a __del__ that was doing "self._thread.join()", assuming that the current thread is not self._thread, but as it turns out that's not always the case. So what is happening here for these ~50 minority cases ? Is __del__ invoked through the proxy ? George From iainking at gmail.com Thu Jun 5 10:30:21 2008 From: iainking at gmail.com (Iain King) Date: Thu, 5 Jun 2008 07:30:21 -0700 (PDT) Subject: Creating A Tuple From A List, Adding To Tuple As You Do References: Message-ID: <63b264bd-20a3-4ab0-9298-dca338cdf2b4@25g2000hsx.googlegroups.com> On Jun 5, 1:41 pm, Jeff Nyman wrote: > Greetings all. > > The subject line of this thread is probably one of the worst ever. I > was trying to encapsulate what I am doing. Based on my new-found > knowledge from another thread, I'm able to get a list of directories > and they come to me in the form of a list. Here is an example: > > from glob import glob > DC_List = glob('\\\\vcdcflx006\\Flex\\Sites\\*\\') > DC_List = ['Baltimore', 'Birmingham', 'Cincinnati', 'Cleveland', > LosAngeles'] > > (Each element in the DC_List is actually a full directory path, but I > shortened that in the interest of clarity.) > > The problem is that I need to pass this list to a list control in a > wxWidgets application. In order to do that, I need to pass in a list > like this: > > [ ('Baltimore', ''), ('Birmingham', ''), ('Cincinnati', ''), > ('Cleveland', ''), ('LosAngeles', '') ] > > In other words, each element in the list is a tuple that has an empty > second string. The problem I'm having is in converting my list above > to be of this type. I can't do append because that (logically) puts > everything at the end. I did try this: > > for count in range(0, len(DC_List)): > DC_List.insert(count, '') > > Here I was thinking I could insert a '' into the right place after > each entry in the list. That doesn't quite work. Does anyone have an > idea of a good approach here? (I did search on tuples and lists and > while I found a lot of information about both, I couldn't find a > solution that did what I'm discussing above.) > > - Jeff I know a ton of people have already replied with list comprehensions, but I figured I'd chime in with one that also strips out the path of your folders for you (since I'm not sure how you are managing that just now) cities = [(os.path.basename(x), '') for x in glob('\\\\vcdcflx006\\Flex \\Sites\\*\\')] I tend to use / instead of \\ as a folder seperator, it should work for you (I think): cities = [(os.path.basename(x), '') for x in glob('//vcdcflx006/Flex/ Sites/*')] Iain From gagsl-py2 at yahoo.com.ar Thu Jun 19 01:52:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 19 Jun 2008 02:52:19 -0300 Subject: =?iso-8859-15?Q?Regular_expressions_for_accents_like_=F3?= =?iso-8859-15?Q?_character_in_python?= References: Message-ID: En Thu, 19 Jun 2008 02:08:38 -0300, Sallu escribi?: > i want to restrict to user to not enter accents character. si i need > to make an Regular expressions for accents like ? character You may enumerate all the allowed characters: py> allowed_re = re.compile(r"^[A-Za-z0-9 ]*$") py> input = "hello world" py> allowed_re.match(input) <_sre.SRE_Match object at 0x00A3C1E0> py> input = "c?digo inv?lido" py> allowed_re.match(input) py> print allowed_re.match(input) None -- Gabriel Genellina From seandavi at gmail.com Wed Jun 11 09:17:33 2008 From: seandavi at gmail.com (Sean Davis) Date: Wed, 11 Jun 2008 06:17:33 -0700 (PDT) Subject: Numpy array to gzip file Message-ID: I have a set of numpy arrays which I would like to save to a gzip file. Here is an example without gzip: b=numpy.ones(1000000,dtype=numpy.uint8) a=numpy.zeros(1000000,dtype=numpy.uint8) fd = file('test.dat','wb') a.tofile(fd) b.tofile(fd) fd.close() This works fine. However, this does not: fd = gzip.open('test.dat','wb') a.tofile(fd) Traceback (most recent call last): File "", line 1, in IOError: first argument must be a string or open file In the bigger picture, I want to be able to write multiple numpy arrays with some metadata to a binary file for very fast reading, and these arrays are pretty compressible (strings of small integers), so I can probably benefit in speed and file size by gzipping. Thanks, Sean From exarkun at divmod.com Sun Jun 15 12:16:16 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 15 Jun 2008 12:16:16 -0400 Subject: The best way to package a Python module? In-Reply-To: Message-ID: <20080615161616.4714.1519820848.divmod.quotient.9372@ohm> On Mon, 16 Jun 2008 01:01:47 +0900, js wrote: >Hi list, > >I'm trying to build a package for python modules. >When I just wanted to have a package for Python2.5, this is an easy task, >but in most cases, it's not enough. >Sometimes I need python2.4, 2.5, 2.6 or 3.0 etc. > >The problem is coming from the fact that python installs its modules >into version-independent place as follow. > >$prefix/lib/python2.4/site-package/ >$prefix/lib/python2.5/site-package/ > >For this, I have to create a package for each version. >Let's say if I need a module called "spam" and installed spam with python2.5. >The files would be installed in $prefix/lib/python2.5/site-package/. >It only usable from python2.5. > >When I need it for python2.4, I have to prepare the same package for python2.4, >the only difference is the place it installed. > >This is the problem I'm having now. >How can I avoid this redundant work? >Any advice, suggestions would be greatly appreciated. > >Thanks! What do you mean, "package"? If you use distutils, then none of the questions you asked make very much sense. >-- >http://mail.python.org/mailman/listinfo/python-list > From matthieu.brucher at gmail.com Thu Jun 26 06:16:11 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Thu, 26 Jun 2008 12:16:11 +0200 Subject: Threads, GIL and re.match() performance In-Reply-To: <207312b70806260020j6a4c5d4dt3af0625c27ec3cc2@mail.gmail.com> References: <25be11e7-157c-4af0-be3a-fa7a6c9c3acc@m3g2000hsc.googlegroups.com> <207312b70806260020j6a4c5d4dt3af0625c27ec3cc2@mail.gmail.com> Message-ID: Hi, The C-API uses references counts as well, so it is not threadsafe. Matthieu 2008/6/26 Pau Freixes : > But Python C-API[1] it's the main base for extent python with C/c++, and > this is not not threadsafe.? I dont understand > > [1] http://docs.python.org/api/api.html > > On Thu, Jun 26, 2008 at 4:49 AM, Benjamin > wrote: >> >> On Jun 25, 9:05 am, Mirko Dziadzka wrote: >> > >> > 1) Is there a reason for this? >> >> I think it is because the Python re library uses the Python C-API >> which is not threadsafe. >> > 2) Is the regex library not thread-safe? >> > 3) Is it possible, to release the GIL in re.match() to >> > get more performance? >> >> -- >> http://mail.python.org/mailman/listinfo/python-list > > > > -- > Pau Freixes > Linux GNU/User > -- > http://mail.python.org/mailman/listinfo/python-list > -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher From exarkun at divmod.com Sun Jun 1 13:19:13 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 1 Jun 2008 13:19:13 -0400 Subject: the pipe reading in Thread dose not work. In-Reply-To: <80750570-0a03-4006-99f4-23943aa56177@u6g2000prc.googlegroups.com> Message-ID: <20080601171913.4714.1079010110.divmod.quotient.4409@ohm> On Sun, 1 Jun 2008 07:32:39 -0700 (PDT), Leon zhang wrote: > >#!/usr/bin/env python ># -*- coding: utf-8 -*- > >import string, sys >from threading import Thread >import os >import time > >class test_pipe(Thread): > def __init__(self, fd): > Thread.__init__(self) > self.testfd = fd > > def run(self): > print "started thread begin -----" > while True: > buf = self.testfd.read() > print "receive %s" % (buf) > time.sleep(1) > #print "hoho" > >if __name__ == "__main__": > > stdin_r, stdin_w = os.pipe() > #stdout_r, stdout_w = pipe() > > f_w = os.fdopen(stdin_w, "w", 0) > > thrd = test_pipe(os.fdopen(stdin_r, "r", 0)) > thrd.start() > > time.sleep(1) > > while True: > f_w.write("help\r\n") > time.sleep(1) > > thrd.join() >-------------------------------------------- >well, I want the following small test about pipe() in thread(). >OK, I write to the pipe in the main thread, and I created a new thread >for reading from the pipe, then it will print what it received from >the pipe(). > >But, it seems it block at the "self.testfd.read()". > >So, is there and suggestion and explaination about it? file.read() reads the entire contents of the file. Your code never closes the write end of the pipe, so the read can never succeed - there is always more for it to read. Jean-Paul From tdelaney at avaya.com Wed Jun 4 19:10:55 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 5 Jun 2008 07:10:55 +0800 Subject: multiprocessing module (PEP 371) In-Reply-To: <48471D42.20808@cheimes.de> Message-ID: Christian Heimes wrote: > Can you provide a C implementation that compiles under VS 2008? Python > 2.6 and 3.0 are using my new VS 2008 build system and we have dropped > support for 9x, ME and NT4. If you can provide us with an > implementation we *might* consider using it. You'd have to at least consider whether to consider using it ;) BTW, something like adding a windows fork() that is not publically exposed might be considered a bug/performance fix only (and thus suitable for 3.0.1) if you don't get it into 3.0 (to be exposed to Python code in 3.1) - but check first whether it would be accepted as such. Definitely best to try to get it into 3.0. Tim Delaney From celoserpa at gmail.com Tue Jun 24 12:31:27 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Tue, 24 Jun 2008 13:31:27 -0300 Subject: Accounting and financial system In-Reply-To: <1e5bcefd0806240924t74c7b4ax48d1267e508e516b@mail.gmail.com> References: <1e5bcefd0806240924t74c7b4ax48d1267e508e516b@mail.gmail.com> Message-ID: <1e5bcefd0806240931g38f11c47se1670c0238f9f2d2@mail.gmail.com> Btw, sorry it is [OT], I forgot to add the prefix, it is really not a post tied to the language itself. On Tue, Jun 24, 2008 at 1:24 PM, Marcelo de Moraes Serpa < celoserpa at gmail.com> wrote: > Hello list, > > In a next project of mine, I will need to implement some accounting and > financial control. It is not a full ERP, only the basic functions for > finances and accounting control. However, I have little to no experience in > this business domain (accounting and finances) but I really do need to > understand the basic machinery behind it, even if it will take a significant > amount of time. What I would like to know is where I could look (besides > getting a degree :P) for sample code and documentation for these subjects? > Do you think I would need to read some books before I get into code? If so, > which ones? For sample code, I was thinking about OpenERP, since I've heard > it is a complete ERP solution and it is written in python ;) > > Really, I'm committed to understand the basiscs of the said business > domains, I really need this project to succeed :) > > Thanks in advance! > > Marceo. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sspatz at kcnet.com Thu Jun 26 21:56:30 2008 From: sspatz at kcnet.com (Saul Spatz) Date: Thu, 26 Jun 2008 20:56:30 -0500 Subject: recursion in Class-methods? In-Reply-To: References: <975b0368-10fe-419c-82ef-50277d4ecd54@l42g2000hsc.googlegroups.com> <48635bfb$0$6862$426a74cc@news.free.fr> Message-ID: <562dnYb_KN1J1fnVnZ2dnUVZ_vninZ2d@posted.kcnet> defn noob wrote: >>> if start == end: >>> return path >>> if not self.dictionary.has_key(start): >> if start not in self.dictionnary: >> >>> return None >>> for node in self.dictionary[start]: >>> if node not in path: >>> newpath = find_path(self.dictionary, node, end, path) >> newpath = self.find_path(...) >> >> (snip remaining code - same problems, same solutions...) > > it is to incoherent fo follow what you mean here(not meaning to sound > rude i appreciate the help). I modified your code as shown below, and it seems to work fine. (I didn't test the shortest path part, just the example you gave.) class Graph(object): def __init__(self, dictionary): self.dictionary = dictionary def find_path(self, start, end, path=None): if not path: path = [] path = path + [start] if start == end: return path if not self.dictionary.has_key(start): return None for node in self.dictionary[start]: if node not in path: newpath = self.find_path(node, end, path) if newpath: return newpath return None def find_all_paths(self, start, end, path=None): if not path: path = [] path = path + [start] if start == end: return [path] if not self.dictionary.has_key(start): return [] paths = [] for node in self.dictionary[start]: if node not in path: newpaths = self.find_all_paths(node, end, path) for newpath in newpaths: paths.append(newpath) return paths def find_shortest_path(self, start, end, path=None): if not path: path = [] path = path + [start] if start == end: return path if not self.dictionary.has_key(start): return None shortest = None for node in self.dictionary[start]: if node not in path: newpath = self.find_shortest_path(node, end, path) if newpath: if not shortest or len(newpath) < len(shortest): shortest = newpath return shortest g = Graph({'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C']}) print g.find_all_paths('A', 'C') Output: [['A', 'B', 'C'], ['A', 'B', 'D', 'C'], ['A', 'C']] Here are the changes I made. 1) Inherit from object. (Anticipation of 3.0) 2) Changed calls such as find_path(self.dictionary, node, end, path) to self.find_path(node, end, path). In python, an objects methods have no special privileges in calling its other methods. They call it like self.otherMethod(...). Also, the first parameter is supposed to be a Graph object. I'm not sure what the effect of calling it with a dictionary would be. BTW, "dictionary" seems like an uninformative name. Why not call it "adjacent" or "neighbor", or "successor"? 3) Changed the default value of path to None, as suggested by Bruno Desthuilliers. What he's telling you is that the default object is created only once; when the method is defined. If it's an int or a string, that doesn't matter. You can't change it, and so you will always have the same default value if you need it. If it's a mutable object, like a list, when your method changes it, as with path = path + [start] it changes the global default object; the next time you need it, it won't be [] but whatever you last changed it to. This last is a tricky point. I hope I've been clear. Saul From kurdayon at yahoo.com Fri Jun 27 18:41:22 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Fri, 27 Jun 2008 15:41:22 -0700 (PDT) Subject: Do I need "self" and "other"? References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> Message-ID: <04e2afb7-b96c-446a-816a-ffac0ea81d5b@p25g2000hsf.googlegroups.com> On Jun 27, 6:32 pm, Hans Nowak wrote: > Kurda Yon wrote: > > Hi, > > > I found one example which defines the addition of two vectors as a > > method of a class. It looks like that: > > > class Vector: > > def __add__(self, other): > > data = [] > > for j in range(len(self.data)): > > data.append(self.data[j] + other.data[j]) > > return Vector(data) > > > In this example one uses "self" and "other". Does one really need to > > use this words? And, if yes, why? I have replaced "self" by "x" and > > "other" by "y" and everything looks OK. Is it really OK or I can have > > some problem in some cases? > > You can use whichever (valid) names you want, but in general 'self' and 'other' > are used for clarity. In this case, they indicate the vector that is operated > on ("self") and another vector ("other"). Using 'x' and 'y' would be less clear > here. > > -- > Hans Nowak (zephyrfalcon at gmail dot com)http://4.flowsnake.org/ OK, I see. In the given example "self" is just a name which can be replace by whichever (valid) name. Is that always like that? I mean, does "slef" have a special meaning in some cases or it is always "just a name like any other"? I am asking that because "self" is highlighted in my text editor, so I assume that it can have a special meaning. I also heard that "self" refers to a object and I am not sure what that "refers" means. From Russ.Paielli at gmail.com Mon Jun 9 14:43:19 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 9 Jun 2008 11:43:19 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <4847d39d$0$7614$426a74cc@news.free.fr> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> <484cf5f6$0$15495$426a74cc@news.free.fr> Message-ID: <127975a3-b3d9-4799-9673-b292ec8d37e3@x19g2000prg.googlegroups.com> On Jun 9, 2:22 am, Bruno Desthuilliers wrote: > > Does > > anyone object to not having access from outside a function to local > > variables within the function? I doubt it. The other thing is that the > > vast majority of Python software, I would guess, is provided with > > source code. How many Python applications or libraries are provided > > without source code? If you have the source code, you can obviously > > just delete the "priv" keyword anywhere or everywhere it appears. > Yes, fine. And then have to maintain a fork of the source code, and > distribute it with the application. Honking great idea. doh :-( A client who wishes to bypass access restrictions need not maintain any "fork." If you have access to the source code, removing my proposed "priv" keyword from an entire library or application is a one- liner in sed. If you wish to remove only specific instances of its occurrences, that is also a trivial matter, and all that needs to be maintained by the client is a record of which instances were removed. In fact, the client doesn't even need to do that, because when the next version comes out they will be reminded very quickly of where they removed "priv." But such a client would be a real fool for depending on private data and/or methods, of course, because those are not part of the public API and are not guaranteed to remain unchanged. The whole reason for private data and methods is that they give the developers freedom to change the implementation without changing the interface. How about some common sense here. If you, the client, are convinced that something declared private should really be public, then perhaps you should contact the developer and explain your reasoning. If the developer agrees, then the problem is solved. If not, then perhaps it is *you*, the client who does not understand the proper usage of the code. I don't have time to reply to all or your claims, but my lack of a reply to any particular point should not be construed as implicit agreement. From michael at stroeder.com Mon Jun 2 11:15:29 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Mon, 02 Jun 2008 17:15:29 +0200 Subject: ThreadPoolingMixIn In-Reply-To: References: <3d9dac72-ce4d-4ce5-9213-4bb17aff2f9e@r66g2000hsg.googlegroups.com> <1c4d113e-b375-471d-9d54-1401c8844352@t12g2000prg.googlegroups.com> Message-ID: pavel.uvarov at gmail.com wrote: > To benchmark this I used a simple tcp server which writes a small > (16k) > string to the client and closes the connection. Just a general note: When benchmarking such a network service it would be valuable to see benchmark results for several data sizes. I'd expect better numbers for a ThreadPoolingMixIn when there are more requests with smaller data size. Ciao, Michael. From sasa.bistrovic at ck.t-com.hr Thu Jun 12 14:31:46 2008 From: sasa.bistrovic at ck.t-com.hr (Saąa Bistrović) Date: Thu, 12 Jun 2008 20:31:46 +0200 Subject: Exception : Unknown Run-Time error : 210 References: Message-ID: "Sa?a Bistrovi?" wrote in message news:g2rftn$ghv$1 at ss408.t-com.hr... > Sa?a Bistrovi? > Antuna Mihanvi?a 13 > 40000 ?akovec > Croatia > sasa.bistrovic at ck.t-com.hr > > FPC: Exception : Unknown Run-Time error : 210 > > Hi, I'm Sa?a from Croatia. > > And I have : > > Windows XP PRO SP3. > Pentium II MMX 400MHz. > 256 MB of RAM. > > I tried to compile fp.pas. > > But I get this error message : > > 'Running "c:\fpc\fpcbuild-2.2.0\fpcsrc\ide\fp.exe "' > 'Starting value of ConsoleMode is $0000001F' > 'Compiler Verison f p c b u i l d - 2 . 2 . 0 \ f p c s r c \ i d e \ f p > . e x e ' + same unknown exe characters as for GBD Verison > 'GBD Verison f p c b u i l d - 2 . 2 . 0 \ f p c s r c \ i d e \ f p . e > x e ' + same unknown exe characters as for Compiler Verison > 'Cygwin "C:\FPC\222A5D~1.0\BIN\I386-W~1\cygwin1.dll" version 1005.18.0.0' > 'An unhandled exception occurred at $004A74E6' > 'Exception : Unknown Run-Time error : 210' > ' $004A74E6 TSWITCHES__ADDBOOLEANITEM, line 602 of > c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/FPSwitch.pas' > ' $004A92F4 INITSWITCHES, line 1150 of > c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/FPSwitch.pas' > ' $004020DF main, line 382 of c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/fp.pas' > What is right newsgroup for Free Pascal Compiler ? Please HELP ! ! ! ! ! From Scott.Daniels at Acm.Org Sun Jun 8 20:02:54 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 08 Jun 2008 17:02:54 -0700 Subject: Q re documentation Python style In-Reply-To: References: Message-ID: kj wrote: > ... I want to document a function that takes a dictionary as argument, > and this dictionary is expected to have 5 keys. When the number of mandatory > arguments gets above 4, I find that it's too difficult to remember > their order, so I resort to using a dictionary as the single argument. Do you know you can call a function with mandatory args as keyword args? def f(value, scale, metrics, color, age, validity): print 'f', value, scale, metrics, color, age, validity ... f(23, age=6, scale=2.5, metrics=2, validity='strong', color='red') You can even use your arg dictionaries in transitional code: call_dict = {'value': 23, 'age': 6, 'scale': 2.5, 'metrics': 2, 'validity': 'strong', 'color': 'red'} f(**call_dict) --Scott David Daniels Scott.Daniels at Acm.Org From arslanburney at gmail.com Mon Jun 16 01:09:44 2008 From: arslanburney at gmail.com (arslanburney at gmail.com) Date: Sun, 15 Jun 2008 22:09:44 -0700 (PDT) Subject: Extrapolation In Gnuplot Message-ID: <1d05b0fd-612d-431d-89cf-c7c788651458@d1g2000hsg.googlegroups.com> How would u extrapolate/ extend a given line in gnu plot? From jarausch at igpm.rwth-aachen.de Thu Jun 5 05:58:14 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Thu, 05 Jun 2008 11:58:14 +0200 Subject: Python and Harry Potter? Message-ID: <6aprloF38p4l7U1@mid.dfncis.de> Hi, just to let you know ... Today I've got an email from Amazon recommending me Harry Potter and the Deathly Hallows and they told me why they recommended this book, because I've bought Core PYTHON Programming Didn't know, Harry Potter is a Python fan. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From timr at probo.com Thu Jun 5 03:17:31 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 05 Jun 2008 07:17:31 GMT Subject: line continuation for lines ending in "and" or "or" References: <90ee8b5d-1509-4463-aaab-f712f7e72d4b@j33g2000pri.googlegroups.com> Message-ID: <0n4f44tttul6kq9sogqnvtuvnvcn7us5cp@4ax.com> Dan Bishop wrote: >On Jun 4, 10:09?pm, "Russ P." wrote: >> I've always appreciated Python's lack of requirement for a semi-colon >> at the end of each line. I also appreciate its rules for automatic >> line continuation. If a statement ends with a "+", for example, Python >> recognizes that the statement obviously must continue. >> >> I've noticed, however, that the same rule does not apply when a line >> ends with "and," "or," or "not." Yes, it's a minor point, but >> shouldn't the same rule apply? >> >> Seems like it would be easy to add. >... >Implicit line continuation only happens if you have an unmatched '('. > >>>> x = (2 + >... 2 >... ) >>>> x >4 ... or an unmatched [ or an unmatched {. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gabriel.rossetti at arimaz.com Thu Jun 12 02:52:25 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Thu, 12 Jun 2008 08:52:25 +0200 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> References: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> Message-ID: <4850C7A9.9010108@arimaz.com> Mike Orr wrote: > On Jun 5, 8:40 am, Gabriel Rossetti > wrote: > >> Hello everyone, >> >> I had read somewhere that it is preferred to use >> self.__class__.attribute over ClassName.attribute to access class (aka >> static) attributes. I had done this and it seamed to work, until I >> subclassed a class using this technique and from there on things started >> screwing up. I finally tracked it down to self.__class__.attribute! What >> was happening is that the child classes each over-rode the class >> attribute at their level, and the parent's was never set, >> > > That's a misunderstanding of classes vs instances. If you have an > instance of MyClass(Superclass), there is one instance but several > classes. The instance is of MyClass; there is no instance of > Superclass. 'self' has a .__class__ attribute because it's an > instance, but MyClass and Superclass do not because they're already > classes. > > Yes, I know that > Going further, self.a retrieves the instance attribute if it exists, > or or MyClass.a if it doesn't, or Superclass.a if that doesn't. But > assigning to self.a always assigns to an instance attribute. To > assign a class attribute you must use .__class__ or TheClass. > Likewise, to retrieve a class attribute that has been overridden by a > subclass or instance, you must use .__class__ or TheClass. > > There's a very good reason to use self.__class__: it makes it possible > to subclass your class. In Jason Orendorff's path.py, some path > methods return new path objects. He uses 'path()' rather than > self.__class__ to construct these. So if you subclass 'path' to > extend it, these methods return path objects rather than your subclass > objects. In my Unipath package which was written later, I use > self.__class__ in these cases to allow users to extend my class. > > Ok, I see a use for that now, I also tried a minimal example of my problem and it worked as I expected, and thus I am unable to reproduce my problem outside of my code. It may be linked to the fact that I am using Zope interfaces and Tisted's plugin mechanism, as this problem was born in that context ; it's possible that something happens in the background that makes it behave strangely. Basically, I the base class for the plugins create a class attribute of an object that is a mutex and each subclass solicited it for access to the I/O. The class attribute was created only once in it's __init__ (using a conditional test). After running it though a debugger, I saw that in reality, every Child instantiated it, so every child had it's own mutex, thus they could each access the I/O even if it was "supposed" to be locked. I had been using "self.__class__.myMutex" everywhere, so I changed it to "MyClass.myMutex" and the code behaved correctly. This is what prompted me to write this thread. As i said before, I tried reproducing the problem out of context, with just regular classes, no interfaces & plugin mechanism, and it works as I had expected (originally). > It's a little annoying that if you want to print a class's name in > some unknown object, you have to use obj.__class__.__name__ if it's an > instance, and obj.__name__ if it's a class. I sometimes wish classes > had a .__class__ attribute that's the class itself, but I can see how > that would cause its own confusion (and recursion). > > Yes :-) > -- Mike Orr > -- > http://mail.python.org/mailman/listinfo/python-list > > > Gabriel From john.gerald.mason at gmail.com Sun Jun 1 17:52:32 2008 From: john.gerald.mason at gmail.com (Mason) Date: Sun, 1 Jun 2008 14:52:32 -0700 (PDT) Subject: convert binary to float References: <0c15e8e1-948b-4bd6-a312-b1e055da859e@t54g2000hsg.googlegroups.com> <829b1e8f-baac-4ff4-909b-b39df97a436c@d45g2000hsc.googlegroups.com> Message-ID: On Jun 1, 5:12 pm, George Sakkis wrote: > On Jun 1, 3:55 pm, Mason wrote: > > > > > I have tried and tried... > > > I'd like to read in a binary file, convert it's 4 byte values into > > floats, and then save as a .txt file. > > > This works from the command line (import struct); > > > In [1]: f = open("test2.pc0", "rb") > > In [2]: tagData = f.read(4) > > In [3]: tagData > > Out[3]: '\x00\x00\xc0@' > > > I can then do the following in order to convert it to a float: > > > In [4]: struct.unpack("f", "\x00\x00\xc0@") > > Out[4]: (6.0,) > > > But when I run the same code from my .py file: > > > f = open("test2.pc0", "rb") > > tagData = f.read(4) > > print tagData > > > I get this (ASCII??): > > ?@ > > Remembering to put that struct.unpack() call in your module might > help ;-) > > George Wow ... I did have it in there, but I forgot include it in my post. Anyway, this works just fine: f = open("test2.pc0", "rb") tagData = f.read(4) print struct.unpack("f", tagData) Thanks for waking me up George! From zaikenv at gmail.com Fri Jun 27 10:51:07 2008 From: zaikenv at gmail.com (Joel Corbin) Date: Fri, 27 Jun 2008 10:51:07 -0400 Subject: Use of the "is" statement Message-ID: Hello, I'm trying to clarify what exactly the behaviour of the is statement is (or should be). Naturally, this has been nearly impossible to google for, even using quotations... It is my impression that the is statement should be equivalent to "==", at least on some level. However, this equivalency seems to be inconsistent for reasons I can't decipher. Out of the following 3 cases, only 2 return True. What is the difference (and why is there one) in the third case? Python 2.5.2 >>> 'string' is 'string' #simple assignment works True >>> s = 'string' >>> s is 'string' True >>> def make_string(): return 'test' #but function behaviour varies >>> def arg_to_str(arg): return str(arg) >>> make_string() is 'test' True >>> arg_to_string('works') is 'works' # this works True >>> arg_to_string(15) is '15' # but this doesnt >>> arg_to_string(15) is arg_to_string(15) # nor this! >>> arg_to_string(15) '15' >>> arg_to_string(15) == arg_to_string(15) True This became a problem when I was using file.tell() and again when using a custom function. If I am using is in the wrong context, what is the right one? Joel -------------- next part -------------- An HTML attachment was scrubbed... URL: From jaywgraves at gmail.com Fri Jun 6 11:35:32 2008 From: jaywgraves at gmail.com (jay graves) Date: Fri, 6 Jun 2008 08:35:32 -0700 (PDT) Subject: File-writing not working in Windows? References: <80a7b951-591b-41a2-b76c-f97d75db0dad@25g2000hsx.googlegroups.com> Message-ID: <08442be2-13c0-44fc-add4-4907c1202f96@r66g2000hsg.googlegroups.com> On Jun 6, 10:18 am, tda... at gmail.com wrote: > This code works PERFECTLY in Linux. Where I have a match in the file > I'm processing, it gets cut out from the start of the match until the > end of the match, and written to the temporary file in tempdir. > It does not work in Windows. It does not create or write to the > temporary file AT ALL. It creates the tempdir directory with no > problem. In general, I don't use string concatenation when building paths. Especially on scripts that are meant to run on multiple platforms. > Here's the kicker: it works perfectly in Windows if Windows is running > in VMware on a Linux host! (I assume that that's because VMware is > passing some call to the host.) probably a red herring. > Can anyone tell me what it is that I'm missing which would prevent the > file from being created on Windows natively? Get rid of the 'posix' check and use os.path.join to create 'tempfileName' and see if it works. HTH. ... Jay Graves From rurpy at yahoo.com Tue Jun 24 21:51:22 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Tue, 24 Jun 2008 18:51:22 -0700 (PDT) Subject: how to convert '8868' to u'\u8868' References: <5268385d-04c7-4726-ab55-0f729ce8d883@a9g2000prl.googlegroups.com> Message-ID: On Jun 24, 7:30?pm, CodeHunter wrote: > a = '8868' > b = u'\u8868' > > I want to convert a to b > > who can help me ? > > thank you very much! >>> a='8868' >>> unichr(int(a,16)) u'\u8868' From workitharder at gmail.com Sat Jun 14 14:25:54 2008 From: workitharder at gmail.com (bukzor) Date: Sat, 14 Jun 2008 11:25:54 -0700 (PDT) Subject: Python + RDBM framework? References: <9PGdnQYEHsf_nsnVnZ2dnUVZ_t3inZ2d@comcast.com> Message-ID: <18e0d9e9-72f7-4745-8293-db3c504452ba@t12g2000prg.googlegroups.com> On Jun 14, 10:43?am, Larry Bates wrote: > bukzor wrote: > > It seems that whenever I have an application that uses a database > > (MySQL) I end up writing a database framework from scratch. Is there > > some accepted pre-existing project that has done this? > > > I see Django, but that seems to have a lot of web-framework that I > > don't (necessarily) need. I just want to have my objects go in and out > > of the database in a consistent manner without writing a ton of code. > > Can you just use the database part without making a full-blow web app? > > > I see Zope, but that doesn't use MySQL (as far as I can tell), which > > I've invested a lot of time learning to use and optimize. Also, my > > manager wants to be able to log into a MySQL prompt and be able to > > look at the data. > > > --Buck > > Zope definitely has MySQL interface, but if you think Django is a lot then Zope > is even more. ?If I'm understanding your correctly what you want is ORM/ ?These > links should help: > > http://pythonnotes.blogspot.com/2004/09/python-orm-tools.htmlhttp://www.sqlalchemy.org/http://www.sqlobject.org/ > > -Larry Both of those would work. I have a lot of data-integrity checks to make that would be impossible at the MySQL level and hard at the python/MySQLdb level. This will help a lot. I'll probably use the SQLAlchemy. Thanks so much! --Buck From deets at nospam.web.de Thu Jun 12 10:31:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 12 Jun 2008 16:31:47 +0200 Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <6bcokhF3b2mo7U1@mid.uni-berlin.de> Message-ID: <6bcqbpF3a3ubdU1@mid.uni-berlin.de> > To be honest I'm relatively new to Python, so I don't know too much > about how all the loop constructs work and how they differ to other > languages. I'm building an app in Django and this data is coming out > of a database and it looks like what I put up there! > > This was my (failed) attempt: > > predictions = Prediction.objects.all() > scores = [] > for prediction in predictions: > i = [prediction.predictor.id, 0] > if prediction.predictionscore: > i[1] += int(prediction.predictionscore) > scores.append(i) > > I did have another loop in there (I'm fairly sure I need one) but that > didn't work either. I don't imagine that snippet is very helpful, > sorry! It is helpful because it tells us what your actual data looks like. What you need is to get a list of (predictor, score)-pairs. These you should be able to get like this: l = [(p.predictor.id, p.predictionscore) for p in predictions] Now you need to sort this list - because in the next step, we will aggregate the values for each predictor. result = [] current_predictor = None total_sum = 0 for predictor, score in l: if predictor != current_predictor: # only if we really have a current_predictor, # the non-existent first one doesn't count if current_predictor is not None: result.append((predictor, total_sum)) total_sum = 0 current_predictor = predictor total_sum += score That should be roughly it. Diez From vasudevram at gmail.com Tue Jun 10 16:47:00 2008 From: vasudevram at gmail.com (vasudevram) Date: Tue, 10 Jun 2008 13:47:00 -0700 (PDT) Subject: Books for programmers References: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> <32791EDC-1033-4B65-BFB5-DF1CF71EF20D@comhem.se> Message-ID: <4639400c-ef38-4835-82cf-380d58800319@l42g2000hsc.googlegroups.com> On Jun 5, 3:09 am, goldw... at slu.edu (Michael H. Goldwasser) wrote: > Dick Moores writes: > > Do not neglect the 2008 book, "Object-Oriented Programming in Python", > > by Goldwasser and Letscher. > > > > > > > Dick Moores > > I'll note that our book is designed as a "CS1" text, and thus intended > primarly for beginners. So its probably not a match for the original > poster who wants a more advanced Python book. That said, I think its > a great book for those with less experience. > > +----------------------------------------------- > | Michael Goldwasser > | Associate Professor > | Dept. Mathematics and Computer Science > | Saint Louis University > | 220 North Grand Blvd. > | St. Louis, MO 63103-2007 Yes, "Python in a Nutshell" (also by Alex Martelli) and "Programming Python" (by Mark Lutz) are also quite good, as others have said above. - Vasudev Ram http://www.dancingbison.com From duncan.booth at invalid.invalid Thu Jun 12 08:23:03 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jun 2008 12:23:03 GMT Subject: get keys with the same values References: Message-ID: Nader wrote: > I have a dictionary and will get all keys which have the same values. > > d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} > > I will something as : > > d.keys(where their values are the same) > > With this statement I can get two lists for this example: > l1= ['a','e'] > l2=['b','d'] > > Would somebody tell me how I can do it? Here's one way: >>> import itertools, functools, operator >>> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} >>> get = functools.partial(operator.getitem, d) >>> for (k,v) in itertools.groupby(sorted(d, key=get), key=get): print k, list(v) 1 ['a', 'e'] 2 ['c'] 3 ['b', 'd'] 4 ['f'] or if you want a dictionary: >>> dict((k,list(v)) for (k,v) in itertools.groupby(sorted(d, key=get), key=get)) {1: ['a', 'e'], 2: ['c'], 3: ['b', 'd'], 4: ['f']} -- Duncan Booth http://kupuguy.blogspot.com From news at prodata.co.uk Fri Jun 20 07:19:32 2008 From: news at prodata.co.uk (John Dann) Date: Fri, 20 Jun 2008 12:19:32 +0100 Subject: Simple Python class questions References: Message-ID: Many thanks for the further comments: On Thu, 19 Jun 2008 21:24:31 -0400, Terry Reedy wrote: >> def __init__(self): >> Try >> Import serial # the pyserial library >The import should be at module level. You only want to do it once, not >for every link. And if the import fails, you should find out right >away. Yes I was wondering about that, but I wasn't clear about when 'body' code (ie not contained within a def block) in the module might run under Python. So it seemed to be safer to place the import statement inside the 'constructor' to get the earliest warning of non-visibility of pyserial. But you seem to be implying that the body code will run when the class is instantiated - have I understood that right? It surely doesn't run when the module containing the class is imported into the main module - does it?? It would certainly make life easier to place the import in the body of the module. I think that some of the other points hinge on the this one, so let me get my understanding straight on that first! > >I guess you learned by now why cut/paste/edit-down is superior to >re-typing ;-) Well I know what you mean, but actually in this instance my Python environment is a non-networked laptop , so no easy way to cut and paste to a networked PC! (Actually the laptop does have an Ethernet chip in but bizarrely the driver somehow manages to kill my ADSL connection at the exchange or ISP, which takes hours to reset so I take care not to use this option. But learning Linux/Python is a useful role for this otherwise defunct PC) JGD From jeffnyman at gmail.com Thu Jun 5 08:41:28 2008 From: jeffnyman at gmail.com (Jeff Nyman) Date: Thu, 5 Jun 2008 05:41:28 -0700 (PDT) Subject: Creating A Tuple From A List, Adding To Tuple As You Do Message-ID: Greetings all. The subject line of this thread is probably one of the worst ever. I was trying to encapsulate what I am doing. Based on my new-found knowledge from another thread, I'm able to get a list of directories and they come to me in the form of a list. Here is an example: from glob import glob DC_List = glob('\\\\vcdcflx006\\Flex\\Sites\\*\\') DC_List = ['Baltimore', 'Birmingham', 'Cincinnati', 'Cleveland', LosAngeles'] (Each element in the DC_List is actually a full directory path, but I shortened that in the interest of clarity.) The problem is that I need to pass this list to a list control in a wxWidgets application. In order to do that, I need to pass in a list like this: [ ('Baltimore', ''), ('Birmingham', ''), ('Cincinnati', ''), ('Cleveland', ''), ('LosAngeles', '') ] In other words, each element in the list is a tuple that has an empty second string. The problem I'm having is in converting my list above to be of this type. I can't do append because that (logically) puts everything at the end. I did try this: for count in range(0, len(DC_List)): DC_List.insert(count, '') Here I was thinking I could insert a '' into the right place after each entry in the list. That doesn't quite work. Does anyone have an idea of a good approach here? (I did search on tuples and lists and while I found a lot of information about both, I couldn't find a solution that did what I'm discussing above.) - Jeff From gherron at islandtraining.com Fri Jun 20 15:14:15 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 20 Jun 2008 12:14:15 -0700 Subject: Python "is" behavior In-Reply-To: <7578bd5a-c46c-4b29-a792-5b82513d68c7@s21g2000prm.googlegroups.com> References: <7578bd5a-c46c-4b29-a792-5b82513d68c7@s21g2000prm.googlegroups.com> Message-ID: <485C0187.9000503@islandtraining.com> michalis.avraam at gmail.com wrote: > On Jun 20, 9:38 am, Jean-Paul Calderone wrote: > >> On Fri, 20 Jun 2008 09:31:57 -0700 (PDT), michalis.avr... at gmail.com wrote: >> >>> I am not certain why this is the case, but... >>> >>>>>> a = 256 >>>>>> b = 256 >>>>>> a is b >>>>>> >>> True >>> >>>>>> a = 257 >>>>>> b = 257 >>>>>> a is b >>>>>> >>> False >>> >>> Can anyone explain this further? Why does it happen? 8-bit integer >>> differences? >>> >> http://mail.python.org/pipermail/python-list/2001-November/113994.html >> >> Jean-Paul >> > > Thank you for this Jean-Paul. I did know about the identity of > objects, but my curiosity is based on the 256 number. Are the 2^8 > integers cached due to the internal loops, or is there any other > specific reason? Is this something that can be controlled? > Python provides no way to change that number, but of course you can always fiddle with the source code and recompile. The actual value is a trade off (like any caching scheme) of cache-space versus efficiency gains. The value has changed at least once in recent versions of Python. Gary Herron > -- > http://mail.python.org/mailman/listinfo/python-list > From nagle at animats.com Mon Jun 2 12:40:52 2008 From: nagle at animats.com (John Nagle) Date: Mon, 02 Jun 2008 09:40:52 -0700 Subject: robotparser behavior on 403 (Forbidden) robot.txt files Message-ID: <48441f05$0$17181$742ec2ed@news.sonic.net> I just discovered that the "robotparser" module interprets a 403 ("Forbidden") status on a "robots.txt" file as meaning "all access disallowed". That's unexpected behavior. A major site ("http://www.aplus.net/robot.txt") has their "robots.txt" file set up that way. There's no real "robots.txt" standard, unfortunately. So it's not definitively a bug. John Nagle SiteTruth From deets at nospam.web.de Mon Jun 2 18:12:01 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 03 Jun 2008 00:12:01 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> Message-ID: <6aj9hiF2sturnU1@mid.uni-berlin.de> > > Well that's nice: you're accusing me of missing the point after having > quoted something I wrote as if it represented by own views, even > though I footnoted it and said I was only doing it for the sake of > argument. Perhaps, outside this discussion, I am totally getting "the > point". > > I can't tell, though, because I read your post twice and I have no > idea what you consider "the point" to be. > > Best as I can tell you are claiming that data hiding isn't important, > but then you go on to imply Python is blemished because it doesn't > hide data. It really makes no sense: perhaps you can help us out by > giving us an example of something that illustrates what you're saying? > > > (FWIW, my actual view on the matter is I don't give a lick about data > hiding or marking internals.) Do yourself a favor and google antoon's previous posts in this group. He sure is a clever guy & I wouldn't call him a troll - but a bit trollish.. Diez From dusan.smitran at gmail.com Tue Jun 10 04:03:56 2008 From: dusan.smitran at gmail.com (dusans) Date: Tue, 10 Jun 2008 01:03:56 -0700 (PDT) Subject: eric4 wont start Message-ID: <06c79177-25ee-464a-9387-ce016975cf90@t54g2000hsg.googlegroups.com> Hi i took a look at eric4, its nice, cuz u have the script output and console in the same window, which is why i love pyscripter. Then i upgradet eric4 to newest version: eric4-4.0.4, it doesnt start, even when i installed the old version: The error massage is: Warning: translation file 'qt_en_US'could not be loaded. Using default. Warning: translation file 'eric4_en_US'could not be loaded. Using default. Warning: translation file 'qscintilla_en_US'could not be loaded. Using default. It just stopes and doesnt go on. Anyone got an idea how to solve this, cuz i really like eric4 From aweraw at gmail.com Tue Jun 10 21:20:48 2008 From: aweraw at gmail.com (Aidan) Date: Wed, 11 Jun 2008 11:20:48 +1000 Subject: Dynamic HTML from Python Script In-Reply-To: <484f24e9$0$5020$607ed4bc@cv.net> References: <484f151c$0$5009$607ed4bc@cv.net> <484f21aa$1@dnews.tpgi.com.au> <484f24e9$0$5020$607ed4bc@cv.net> Message-ID: <484f2870$1@dnews.tpgi.com.au> asdf wrote: >> Well, there's a few ways you could approach it. >> >> You could create a cgi program from your script - this is probably the >> solution you're looking for. >> > > Output from the script does come up very often. There is a new output > every 10 secs and it's possible that the script might be run indefinitely. > Basically I want all that output displayed in a web browser Well, in that case you could simply append the new output to a static file every 10 seconds, or whenever there is new output. That way, you just need to refresh the static file in your browser to see updates... Given what I understand of your situation, that's how I'd do it. A constantly running CGI app is probably not the best idea, given timeouts and other such constraints you might run into. >> You could have the script run periodically and create a static html file >> in the webroot... this would be acceptable, maybe preferable, if the >> output from your script doesn't change frequently. >> From jaraco at jaraco.com Fri Jun 13 11:17:29 2008 From: jaraco at jaraco.com (Jason R. Coombs) Date: Fri, 13 Jun 2008 08:17:29 -0700 (PDT) Subject: namedtuple suggestions Message-ID: <318037bd-e126-4c41-ac65-c2afb9fd768d@w7g2000hsa.googlegroups.com> I see a new function in (python 2.6) lib/collections called namedtuple. This is a great function. I can see many places in my code where this will be immensely useful. I have a couple of suggestions. My first suggestion is to use self.__class__.__name__ instead of the hard-coded typename in __repr__, so that subclasses don't have to override these methods just to use the correct name. def __repr__(self): return self.__class__.__name__ + '(%(reprtxt)s)' %% self \n My other suggestion, which is perhaps more intrusive, would be to implement the underlying class as a metaclass, rather than constructing and exec'ing a string. This would make the code more readable (as there wouldn't be format string substitions in the class definition, and the code could be interpreted by editors for syntax highlighting, indentation support, etc). I'm willing to take up the latter effort if there's agreement this could be included in the release. Regards, Jason R. Coombs From mrmakent at cox.net Sat Jun 14 14:04:23 2008 From: mrmakent at cox.net (Mike Kent) Date: Sat, 14 Jun 2008 11:04:23 -0700 (PDT) Subject: Subclassing list, what special methods do this? References: <7ba7e964-2d34-4594-8cfc-79dbf904df18@f63g2000hsf.googlegroups.com> <20149773-a485-4762-b3d0-f5be948df1b0@27g2000hsf.googlegroups.com> Message-ID: <41293e17-69ab-4d4b-b7b1-cdd45764cec1@d77g2000hsb.googlegroups.com> On Jun 13, 8:43?pm, Matimus wrote: ...chop... > So, it looks like as long as you want to subclass list, you are stuck > implementing both __*slice__ and __*item__ methods. > > Matt Thanks. That was clear and concise, just what I needed. From eckhardt at satorlaser.com Tue Jun 3 10:22:35 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 03 Jun 2008 16:22:35 +0200 Subject: Image Processing (batch) References: <6akqd5F37rofnU1@mid.individual.net> Message-ID: Thomas Guettler wrote: > I tried PIL for image batch processing. But somehow I don't like it > - Font-Selection: You need to give the name of the font file. > - Drawing on an image needs a different object that pasting and saving. > - The handbook is from Dec. 2006. > > What image libraries do you suggest? I haven't looked at it yet, but I was thrilled to hear that GIMP (www.gimp.org) had the ability to be extended via Python scripts. Maybe that would help? Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From dullrich at sprynet.com Thu Jun 12 10:30:58 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 12 Jun 2008 09:30:58 -0500 Subject: regex for balanced parentheses? References: <7a054807-4b96-4acb-a21d-7970fd621715@8g2000hse.googlegroups.com> Message-ID: On Thu, 12 Jun 2008 06:38:16 -0700 (PDT), Paul McGuire wrote: >On Jun 12, 6:06?am, David C. Ullrich wrote: >> There's no regex that detects balanced parentheses, >> or is there? >> >> [...] > >Pyparsing includes several helper methods for building common >expression patterns, such as delimitedList, oneOf, operatorPrecedence, >countedArray - and a fairly recent addition, nestedExpr. nestedExpr >creates an expression for matching nested text within opening and >closing delimiters, such as ()'s, []'s, {}'s, etc. Keen. Howdya know I wanted that? Thanks. TeX is one of the amazing things about free software. Knuth is great in many ways. He totally blew it in one detail, unfortunately one that comes up a lot: '$' is an opening delimiter, for which the corresponding closing delimiter is also '$'. Then better yet, '$$' is another double-duty delimiter... what I've done with that is first split on '$$', taking the odd-numbered bits to be the parts enclosed in $$..$$, and then taking the remining parts and splitting on $. Not hard but it gives me a creepy feeling. Hence the question: Can pyparsing tell the difference between '$' and '$'? (heh-heh). > The default >delimiters are ()'s. You can also specify a content expression, so >that pyparsing will look for and construct meaningful results. The >default is to return any text nested within the delimiters, broken up >by whitespace. > >Here is your sample string parsed using the default nestedExpr: >>>> from pyparsing import nestedExpr >>>> for e in nestedExpr().searchString('and so ((x+y)+z) = (x+(y+z))'): >... print e[0] >... >[['x+y'], '+z'] >['x+', ['y+z']] > >Pyparsing found 2 matches in your input string. Note that the parens >are gone from the results - nestedExpr returns a nested list >structure, with nesting corresponding to the ()'s found in the >original string. > >Pyparsing supports parse-time callbacks, called 'parse actions', and >it comes with several commonly used methods, such as removeQuotes, >upcaseTokens, and keepOriginalText. The purpose of keepOriginalText >is to revert any structuring or parsing an expression or other parse >actions might do, and just return the originally matched text. > >Here is how keepOriginalText gives you back just the nested >parenthetical expressions, without any additional processing or >grouping: >>>> from pyparsing import keepOriginalText >>>> matchedParens = nestedExpr().setParseAction(keepOriginalText) >>>> for e in matchedParens.searchString('and so ((x+y)+z) = (x+(y+z))'): >... print e[0] >... >((x+y)+z) >(x+(y+z)) > >-- Paul David C. Ullrich From Chris8Boyd at gmail.com Fri Jun 6 14:25:08 2008 From: Chris8Boyd at gmail.com (Chris8Boyd at gmail.com) Date: Fri, 6 Jun 2008 11:25:08 -0700 (PDT) Subject: Cannot use Winpdb (or PyDev) to trace embedded Python script in MSVC++ application - ImportError: No module named _socket References: <8a739206-1f72-47ee-8a9f-50ec2c91bde2@j33g2000pri.googlegroups.com> <82989ee9-f9ce-4a88-84b8-c5a0fa2e784e@t12g2000prg.googlegroups.com> Message-ID: <12599118-73c9-45af-94fc-5a791713445d@v1g2000pra.googlegroups.com> On Jun 6, 1:13 am, Nir wrote: > You seem to be having a problem with the import path of the embedded > interpreter. I suppose the embedded interpreter includes some modules > in a particular folder and _socket is not one of them. For the sake of > debugging try adding the c:\python25\lib path to the sys.path variable > of the interpreter before attempting to import rpdb2. > > Does this work? > > Nir > > On Jun 5, 2:52 pm, Chris8B... at gmail.com wrote: > > > I am embedding Python in a MSVC++ (2005) application. The application > > creates some environment and then launches a Python script that will > > call some functions exported from the MSVC++ application. > > > I want to be able to debug the Python script by using a debug server, > > likeWinpdb(winpdb.org). > > > I use ActivePython 2.5.2.2, Microsoft Visual Studio 2005, andWinpdb > > 1.3.8. > > > When I launch a script like "e:>python test.py" everything is O'K and > > I can useWinpdbto trace/debug. > > > When I run the same script from the MSVC++ application, there is > > always a complain "ImportError: No module named _socket". > > > Here is the basic test script I use: > > > def Process( something ): > > print "\n\nStarted debugging\n=================\n" > > #pydevd.settrace() > > import rpdb2; rpdb2.start_embedded_debugger("1") > > print "\n\nStopped debugging\n=================\n" > > > if __name__ == '__main__': > > Process( "test" ) > > <<< > > > In the MSVC++ application I tried many approaches, as suggested by > > many people, and all of them work to launch the script, but none of > > them works withWinpdb(or PyDev for Eclipse - same problem). Just for > > completeness - here is one: > > > PyRun_SimpleString("import sys"); > > PyRun_SimpleString("import os"); > > PyRun_SimpleString( "fullpath = os.path.abspath(\"E:/Test.py\")" ); > > PyRun_SimpleString( "g = globals().copy()" ); > > PyRun_SimpleString( "g['__file__'] = fullpath"); > > PyRun_SimpleString( "execfile(fullpath, g) "); > > <<< > > > If I use pdb (import pdb + pdb.runcall(something) ) everything works > > fine, but I need the performance and convinience ofWinpdb. > > > What am I doing wrong? > > > Your help is highly appreciated! > > > Best regards, > > Chris Nir, > Does this work? Unfortunately, not. I did some experiments to check the sys.path hypothesis: - In my MSVC++ application I did PyRun_SimpleString("import cgi"); - it complained about missing _socket. - Did PyRun_SimpleString("print sys.path") to get the sys.path as seen from within the application environment (that does not find _socket) - Did the same in "test.py" and ran ...>Python test.py to get the sys.path for the environment that _does_ find _socket - Compared the two - the working environment had two more paths: C:\\WINDOWS\\system32\\python25.zip C:\\Python25\\lib\\plat-win - Added the missing path to the embedded environment: PyRun_SimpleString("import sys"); PyRun_SimpleString("import os"); PyRun_SimpleString("sys.path.append(\"C:\\WINDOWS\\system32\ \python25.zip\")"); PyRun_SimpleString("sys.path.append(\"C:\\Python25\\lib\\plat-win \")"); PyRun_SimpleString("print sys.path"); PyRun_SimpleString("import cgi"); Not all paths that are in the working environment are present in the embedded environment, but still there is a problem: Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\cgi.py", line 40, in import urllib File "c:\Python25\lib\urllib.py", line 26, in import socket File "c:\Python25\lib\socket.py", line 45, in import _socket ImportError: No module named _socket Chris From rhamph at gmail.com Fri Jun 20 13:50:59 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Fri, 20 Jun 2008 10:50:59 -0700 (PDT) Subject: How do i : Python Threads + KeyboardInterrupt exception References: <089f56d2-5e44-4161-b580-84881717bd05@w4g2000prd.googlegroups.com> <6cfbfaa2-293f-41d3-b544-fd47f05d0d36@j33g2000pri.googlegroups.com> <93eb3402-1dde-4ad3-b91f-d4b091048ac0@g16g2000pri.googlegroups.com> Message-ID: On Jun 19, 11:09?pm, Brendon Costa wrote: > > If only the main thread can receive KeyboardInterrupt, is there any > > reason why you couldn't move the functionality of the Read thread into > > the main thread? It looks like it's not doing any work, just waiting > > for the Proc thread to finish. > > > You could start the Proc thread, do the current Read thread > > functionality until the interrupt occurs, put the apporpriate message > > in the queue, and then wait for the Proc thread to finish. > > It is already doing that. You will notice that the Proc() function is > called by a threading.Thread instance so Proc() is running in a > thread, but the Read() function is being called by the main thread > right after this. It DOES work with the Ctrl + C, but i can find no > way at all of closing down the script from within the Proc() thread. > > The relevant bit of code is: > t = MyThread(Proc, queue, sys.stderr, None) > Read(queue, sys.stdin, sys.stderr) > > In the end, the problem is that i am trying to multiplex IO and other > operations. In UNIX i would use select with the input file descriptor > and an anonymous pipe for the extra commands to achieve this without > any threads, but this script needs to run primarily on a windows box > and i would like to use it on UNIX too. I thought i could use threads > to achieve the IO Multiplexing in python, but it seems not or at least > not simply. > > How do people usually manage IO multiplexing (not just using sockets) > cross platform in python? > > I only need to multiplex two sources really: > * Input file or stdin > * A input event queue > ? ?This will have messages injected from various locations: timers, > the processing thread itself, and possibly from a single GUI thread at > a later point in time. > > Though i can foresee that at some point in the future i may also need > to multiplex those two above and some sockets (For a server with a few > clients). > > I was thinking of looking at some asynchronous IO libraries for python > on Windows + UNIX, any suggestions (Must include more than just > sockets)? They either use an event-driven library.. or they use a timeout of around 1 second. 1 second will definitely waste power on laptops (and desktops), but it *works*. python-safethread has this fixed - any lowlevel trickery needed is done for you - but it's not ported to windows yet. From subhabrata.iisc at hotmail.com Fri Jun 13 03:12:47 2008 From: subhabrata.iisc at hotmail.com (subhabrata.iisc at hotmail.com) Date: Fri, 13 Jun 2008 00:12:47 -0700 (PDT) Subject: HTML FORM AND PYTHON Message-ID: Dear Members of the group, I have a small question, if you can help me to find the answer. I have one function: def add_string(n): print ?Print Two strings? print ?Print the First String? a1=raw_input(?PRINT THE FIRST STRING?) a2=raw_input(?PRINT THE SECOND STRING?) print ?CONCATENATING THE TWO GIVEN STRINGS? a3=a1+a2 print ?THE RESULT IS? print a3 Now, I have designed one HTML form which has two input fields for text and an output field for the result. I like to bind the python program into HTML form. i) Is there any way I can keep both my existing python code and HTML code and bind them? If any one can suggest with example. ii) Do I have to write the whole code in a way in python so that it would work the function as well as generate HTML form I am looking for? If any one can suggest with example. iii) Is there any other way? Best Regards, Subhabrata. From lajam at caramail.com Fri Jun 27 09:36:47 2008 From: lajam at caramail.com (lajam at caramail.com) Date: Fri, 27 Jun 2008 06:36:47 -0700 (PDT) Subject: where is the error? References: <8f8e1bf7-78b0-4292-9d56-396527b9dfb1@z66g2000hsc.googlegroups.com> <15ea1cb1-76a3-4fd3-8e4c-521b9aefcca2@m3g2000hsc.googlegroups.com> Message-ID: <19295372-0910-4d79-9ceb-52ca88d04729@y38g2000hsy.googlegroups.com> > > I think that you mean that diff_temp will be an array of the numberS > (plural) of the lines (rows?) in values array that met the -2 < x < 2 > criterion. Now you want to be able to use diff_temp to get the > corresponding subset of some other array. Am I getting close? I think that you're getting close. I want to get the lines that met the criterion. Diff_temp is an array containing the values of the lines. So bascially, > Now you want to be able to use diff_temp to get the corresponding > subset of some other array. Am I getting close? yes > Perhaps you need something like other_array.take(diff_temp) ? And my problem was that the commands worked on windows but not on linux. > By the way, shouldn't you be using numpy? I thought numarray was going > away by mid-2008 i.e. now. I know, but i'm not sure that it's the problem. Thanks Cedric From thermate2 at india.com Tue Jun 3 00:22:46 2008 From: thermate2 at india.com (thermate2 at india.com) Date: Mon, 2 Jun 2008 21:22:46 -0700 (PDT) Subject: Errata competion for the LaTeX Graphics Companion, Second edition --- first winner References: Message-ID: It is not difficult to predict that your book will soon be scanned and appear on the khazar site http://betah.co.il Even if does not appear there, the khazar site, namely books.google.com will get it scanned. Now what gives google the right to scan a book and store it on their computers ? Why cant we do it ? Why cant we employ every single argument that google will concoct to justify this action ? The fact is that the Israeli hackers are the leaders in all the copyright violations and have recruited PATSIES from other races and nationalities to take the crumbs in the more open forums, while Israeli hackers work in the hiding. But since this enmasse intellectual property theft (or potential theft) which is a RTN away, ie one command, not even a screw away as is alleged for IRAN nuclear crap, The whole world in implementing SELECTIVE copyright will be CUTTING their OWN FEET with their OWN HANDS. There is no way to send US army into Israeli houses and buildings to check every place and dig every floor for hard disks containing the intellectual property on google-israel. The RUBICON has been crossed. The JINNI is out of the bottle. I am just bringing the argument to the forefront. Nothing can be done now. Either live with a super race of all intellectual property in Israel and cut your own feet. In either case its loss - loss. On Jun 2, 6:08 am, Frank Mittelbach wrote: > I'm pleased to announce that we have a first winner: > > Milan Vujtek > > Congratulation to a free book from A-W. > > The number of misprints found so far is rather low, so either we got better > with this book (my hope :-) but I don't really believe this) or people are > not sending me the errors they have found. Please do, it helps everybody > and it might earn you the next prize which will be due in about a year. > > Details of the contest and the current list of errata entries can be found > at > > http://www.latex-project.org/guides/books.html > > There you can also find excerpts from all (or most of all) chapters to give > you an impression of the books content. > > http://www.latex-project.org/guides/lgc2-excerpts.pdf (2.9 mb!) > > thanks for participating in the contest (sending in errors benefits all > readers) and good luck > > frank > > ps there are no plans to translate the book to German, which is why I > cross-posted to the German de.comp.text.tex rather than announcing a German > competion From paddy3118 at googlemail.com Thu Jun 12 14:07:43 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 12 Jun 2008 11:07:43 -0700 (PDT) Subject: Counting things fast - was Re: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> Message-ID: <20049a04-37cd-4c2c-a9e8-67360706ea77@a1g2000hsb.googlegroups.com> On Jun 12, 4:14 pm, Gerhard H?ring wrote: > Aidan wrote: > > does this work for you? > > > users = [1,1,1,2,2,3,4,4,4] > > score = [0,1,5,3,1,2,3,3,2] > > > d = dict() > > > for u,s in zip(users,score): > > if d.has_key(u): > > d[u] += s > > else: > > d[u] = s > > > for key in d.keys(): > > print 'user: %d\nscore: %d\n' % (key,d[key]) > > I've recently had the very same problem and needed to optimize for the > best solution. I've tried quite a few, including: > > 1) using a dictionary with a default value > > d = collections.defaultdict(lambda: 0) > d[key] += value > <> > -- Gerhard This might be faster, by avoiding the lambda: d = collections.defaultdict(int) d[key] += value - Paddy. From sjmachin at lexicon.net Tue Jun 17 08:07:55 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 17 Jun 2008 05:07:55 -0700 (PDT) Subject: Numeric type conversions References: Message-ID: <23739f6d-d48a-46ec-be88-2092c68f4124@j33g2000pri.googlegroups.com> On Jun 17, 9:28 pm, John Dann wrote: > I'm new to Python and can't readily find the appropriate function for > the following situation: > > I'm reading in a byte stream from a serial port (which I've got > working OK with pyserial) and which contains numeric data in a packed > binary format. Much of the data content occurs as integers encoded as > 2 consecutive bytes, ie a 2-byte integer. > > I'm guess that there should be a function available whereby I can say > something like: > > My2ByteInt = ConvertToInt(ByteStream[12:13]) > > to take a random example of the 2 bytes occurring at positions 12 and > 13 in the byte stream. > > Can anyone point me in the right direction towards a suitable function > please? > > NB I don't know without further checking exactly how the bytes are > encoded, but I'm just transcribing some code across from a Windows > VB.Net program and these same bytes could be read straight into a > standard 2-byte signed short int, so I can be confident that it's a > fairly standard Windows-compatible encoding. You need the unpack function of the struct module. Supposing you have a four-byte string containing two such short ints, first + 1 then -1 then this will work: >>> import struct >>> two_shorts = '\x01\x00\xff\xff' >>> struct.unpack('>> In the format string, '<' means little-endian (almost universal on PCs running Windows), and 'h' means a signed 'half-word'. See the struct manual section for more options. You can write a function called convert_to_int (take a hint on naming conventions) and use it a slice at a time, or you can use struct.unpack to grab a whole record at once. Here's a real live example of that: ( f.height, option_flags, f.colour_index, f.weight, f.escapement_type, f.underline_type, f.family, f.character_set, ) = unpack(' <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> Message-ID: <6b367e4a-9d8a-493e-91b6-0661efa48e0a@c58g2000hsc.googlegroups.com> On Jun 2, 8:14 am, Carl Banks wrote: > Fair enough, but I don't see anything in your example that suggests a > way to discriminate between access from within the class and access > from outside the class, which is the crucial aspect of data hiding. And, if you want an example of something that does that, how about this metaclass. It creates a class that checks the stack frame to see if the caller was defined in the same class. Issues: Classes are prevented from defining their own __setattr__ and __getattribute__. Classes and subclasses should not use the same names for their private variables. Private attribute access is pretty slow, but that's obvious. Pretty easy to thwart. #---------------------------------- import sys import itertools class PrivateAccessError(Exception): pass class PrivateDataMetaclass(type): def __new__(metacls,name,bases,dct): function = type(lambda x:x) privates = set(dct.get('__private__',())) codes = set() for val in dct.itervalues(): if isinstance(val,function): codes.add(val.func_code) getframe = sys._getframe count = itertools.count def __getattribute__(self,attr): if attr in privates: for i in count(1): code = getframe(i).f_code if code in codes: break if code.co_name != '__getattribute__': raise PrivateAccessError( "attribute '%s' is private" % attr) return super(cls,self).__getattribute__(attr) def __setattr__(self,attr,val): if attr in privates: for i in count(1): code = getframe(i).f_code if code in codes: break if code.co_name != '__setattr__': raise PrivateAccessError( "attribute '%s' is private" % attr) return super(cls,self).__setattr__(attr,val) dct['__getattribute__'] = __getattribute__ dct['__setattr__'] = __setattr__ cls = type.__new__(metacls,name,bases,dct) return cls #---------------------------------- import traceback class A(object): __metaclass__ = PrivateDataMetaclass __private__ = ['internal'] def __init__(self,n): self.internal = n def inc(self): self.internal += 1 def res(self): return self.internal class B(A): __private__ = ['internal2'] def __init__(self,n,m): super(B,self).__init__(n) self.internal2 = m def inc(self): super(B,self).inc() self.internal2 += 2 def res(self): return self.internal2 + super(B,self).res() def bad(self): return self.internal2 + self.internal a = A(1) a.inc() print "Should print 2:" print a.res() print print "Should raise PrivateAccessError:" try: print a.internal except PrivateAccessError: traceback.print_exc() print b = B(1,1) b.inc() print "Should print 5:" print b.res() print print "Should raise PrivateAccessError:" try: print b.internal2 except PrivateAccessError: traceback.print_exc() print print "Should raise PrivateAccessError:" try: print b.bad() except PrivateAccessError: traceback.print_exc() print #---------------------------------- Carl Banks From nick at craig-wood.com Sat Jun 7 06:30:21 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 07 Jun 2008 05:30:21 -0500 Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> Message-ID: David wrote: > Would it be possible for a 3rd-party threading library to an > 'interruptible' version of Queue? > > The same methods as the normal Queue, but when you call a new .kill() > method on the queue, all the threads locking on the queue get a > "QueueKilled" exception thrown. > > It might be as simple as a Queue wrapper where .kill() adds a speciall > Killed value to the queue, and the .get() wrapper throws a QueueKilled > exception (after re-putting Killed) when it reads Killed. There seem to me to be 2 basic types of threads - I'll call them client threads and server threads. A client thread listens on a Queue for its instructions and replies via a different Queue, or via Queues passed in in its instructions. That kind of thread can easily have an instruction which means quit. When it isn't processing instructions there is a nice clean moment for it to quit. However if the processing takes a long time then there will be a long wait for the thread to die. This is the scenario described above. The server type thread is processing all the time. Every now and again it sends its results via a Queue. An example of this type of thread might be one listening on a socket. This type of thread has no nice moment to listen for instructions to quit as it might well be blocked on something else (eg listening to a socket). To make this type of thread kill nicely you have to go back to breaking up your work into chunks (eg polling the socket asynchronously) and polling the command queue to wait for your quit instruction which is wastefull of CPU resources. So it seems to me that there isn't a good solution to killing python threads of either type, other than coding them carefully and checking for quit instructions regularly. You can kill them using the internal python API and ctypes, but you run the risk of leaving things in an inconsistent state which is why that API isn't exposed. Here is an attempt at a killable thread http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496960 and http://sebulba.wikispaces.com/recipe+thread2 Read the caveats! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From cricket.keith at gmail.com Wed Jun 11 12:40:51 2008 From: cricket.keith at gmail.com (Keith Nation) Date: Wed, 11 Jun 2008 11:40:51 -0500 Subject: Reading info from an active file Message-ID: <21935b370806110940y3c4f4a33l8fd06ad679fb6863@mail.gmail.com> I have a program that writes a log file as it is running to give status of the job. I would like to read that file, pull certain lines of text from it, and write to a new file. Because I am such a novice user, I was hoping someone had covered this before and could let me know of your methods. If I open and close the file repeatedly to get refreshed information, I assume it would slow the system down. Any thoughts? Keith Nation -------------- next part -------------- An HTML attachment was scrubbed... URL: From szrRE at szromanMO.comVE Mon Jun 2 01:24:42 2008 From: szrRE at szromanMO.comVE (szr) Date: Sun, 1 Jun 2008 22:24:42 -0700 Subject: Python's doc problems: sort References: <929d5ce9-9063-4e6c-98aa-89526f89fba3@y18g2000pre.googlegroups.com> Message-ID: szr wrote: > J?rgen Exner wrote: >> "Andrew Koenig" wrote: >>> wrote in message >> >> [Subject: Python's doc problems: sort] >>>> I want to emphasize a point here, as i have done quite emphatically >>>> in the past. The Python documentation, is the world's worst >>>> technical >> >> And WTF does Python documentation have to do with Perl of Lisp? >> >> szr, do you still have any doubts about the nature of xahlee? > > I wasn't involved in this thread, but no, after that statement > comparing Perl's and Python's docs, I no doubts. * should have been, ", I have no doubts." -- szr From asdf at asdf.com Tue Jun 10 22:16:20 2008 From: asdf at asdf.com (asdf) Date: 11 Jun 2008 02:16:20 GMT Subject: Dynamic HTML from Python Script References: <484f151c$0$5009$607ed4bc@cv.net> <484f21aa$1@dnews.tpgi.com.au> <484f24e9$0$5020$607ed4bc@cv.net> <484f2870$1@dnews.tpgi.com.au> Message-ID: <484f3574$0$4998$607ed4bc@cv.net> On Wed, 11 Jun 2008 11:20:48 +1000, Aidan wrote: > asdf wrote: >>> Well, there's a few ways you could approach it. >>> >>> You could create a cgi program from your script - this is probably the >>> solution you're looking for. >>> >>> >> Output from the script does come up very often. There is a new output >> every 10 secs and it's possible that the script might be run >> indefinitely. Basically I want all that output displayed in a web >> browser > > Well, in that case you could simply append the new output to a static > file every 10 seconds, or whenever there is new output. That way, you > just need to refresh the static file in your browser to see updates... > Given what I understand of your situation, that's how I'd do it. > The problem with this is that browser would have to be refreshed manually every 10 seconds. Unless there is a way to set this in the script itself. > A constantly running CGI app is probably not the best idea, given > timeouts and other such constraints you might run into. > > >>> You could have the script run periodically and create a static html >>> file in the webroot... this would be acceptable, maybe preferable, if >>> the output from your script doesn't change frequently. >>> From precisionreplicas at gmail.com Wed Jun 4 12:18:44 2008 From: precisionreplicas at gmail.com (Best Replica Watches) Date: Thu, 5 Jun 2008 00:18:44 +0800 Subject: perfect replica watches for sale Message-ID: perfect replica watches for sale I wanted to purchase a new Rolex, but couldn't afford it. I looked for high quality replica watches for sale online and finaly found Precision Replicas(URL: http://www.precisionreplicas.com) I was impressed that they show the picture of the replica watch you get. I recommend them. From hniksic at xemacs.org Thu Jun 19 07:04:29 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 19 Jun 2008 13:04:29 +0200 Subject: python string comparison oddity References: <3ebd170e-8686-4bb4-9e47-0fba2179feb3@p39g2000prm.googlegroups.com> Message-ID: <87iqw5heiq.fsf@mulj.homelinux.net> Faheem Mitha writes: > Yes, but why is '-' and 'foo' cached, and not '--'? Do you know what > the basis of the choice is? Caches such as intern dictionary/set and one-character cache are specific to the implementation (and also to its version version, etc.). In this case '-' is a 1-character string, all of which are cached. Python also interns strings that show up in Python source as literals that can be interpreted as identifiers. It also reuses string literals within a single expression. None of this should be relied on, but it's interesting to get insight into the implementation by examining the different cases: >>> '--' is '--' True # string repeated within an expression is simply reused >>> a = '--' >>> b = '--' >>> a is b False # not cached >>> a = '-' >>> b = '-' >>> a is b False # all 1-character strings are cached >>> a = 'flobozz' >>> b = 'flobozz' >>> a is b True # flobozz is a valid identifier, so it's cached >>> a = 'flo-bozz' >>> b = 'flo-bozz' >>> a is b False From miller.paul.w at gmail.com Mon Jun 2 17:24:21 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Mon, 2 Jun 2008 14:24:21 -0700 (PDT) Subject: Checking each item in m.group()? References: Message-ID: <2d1b2ac1-3fa1-41c7-a2c2-560c8322b6fb@z72g2000hsb.googlegroups.com> On Jun 2, 5:06?pm, Peter Otten <__pete... at web.de> wrote: > You are taking the wrong approach here. > > Don't build SQL statements as strings; you are enabling the next SQL > injection attack. Pass parameters using the DB API instead. > > Don't use regular expressions to parse a CSV file. Python's csv module is > more likely to deal correctly with the quirks of that standard. > I'd like to second both these statements. Regardless of whether these CSV files are from a trusted source or not, it's a virtual truism of programming that eventually, any application will be used in ways it was not intended. Since using a parameterized query is a simple way to avoid a common security hole, even if such a thing could never be exploited by the app in its current configuration, you should do things the Right Way. That way, even if your code is twisted to some other use in the future, it's less likely to cause problems. From M8R-yfto6h at mailinator.com Mon Jun 23 23:31:10 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Mon, 23 Jun 2008 20:31:10 -0700 Subject: Question: How do I format printing in python References: Message-ID: <_76dnUf30a3n9_3VnZ2dnUVZ_omdnZ2d@comcast.com> wrote in message news:c6e1cfa9-207a-461b-babe-2a14cdd1b25a at y21g2000hsf.googlegroups.com... > Hi All, > > How do I format printed data in python? > I could not find this in the Python Reference Manual: > http://docs.python.org/ref/print.html > Nor could I find it in Matloff's great tutorial: > http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf > > > For example, how do I turn this: > > 512 Jun 5 2004 X11r6 > 22 Jan 17 2005 a2p > 22 Jan 17 2005 acctcom > 5374 Sep 15 2002 acledit > 5664 May 13 2004 aclget > 12020 May 13 2004 aclput > 115734 Jun 2 2004 adb > 46518 Jun 4 2004 admin > 66750 Sep 16 2002 ali > 1453 Sep 15 2002 alias > 28150 Jun 4 2004 alog > 15 May 12 2005 alstat > > into this: > > 512 Jun 5 2004 X11r6 > 22 Jan 17 2005 a2p > 22 Jan 17 2005 acctcom > 5374 Sep 15 2002 acledit > 5664 May 13 2004 aclget > 12020 May 13 2004 aclput > 115734 Jun 2 2004 adb > 46518 Jun 4 2004 admin > 66750 Sep 16 2002 ali > 1453 Sep 15 2002 alias > 28150 Jun 4 2004 alog > 15 May 12 2005 alstat > > Thank you data = '''\ 512 Jun 5 2004 X11r6 22 Jan 17 2005 a2p 22 Jan 17 2005 acctcom 5374 Sep 15 2002 acledit 5664 May 13 2004 aclget 12020 May 13 2004 aclput 115734 Jun 2 2004 adb 46518 Jun 4 2004 admin 66750 Sep 16 2002 ali 1453 Sep 15 2002 alias 28150 Jun 4 2004 alog 15 May 12 2005 alstat '''.split('\n') for line in data: elements = line.split() print '%-11s%-6s%-4s%-8s%s' % tuple(elements) -Mark From roy at panix.com Fri Jun 27 22:15:21 2008 From: roy at panix.com (Roy Smith) Date: Fri, 27 Jun 2008 22:15:21 -0400 Subject: Do I need "self" and "other"? References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> Message-ID: In article <68566b52-100d-40ee-a0c6-bde20df9ecd4 at a70g2000hsh.googlegroups.com>, Kurda Yon wrote: > Hi, > > I found one example which defines the addition of two vectors as a > method of a class. It looks like that: > > class Vector: > def __add__(self, other): > data = [] > for j in range(len(self.data)): > data.append(self.data[j] + other.data[j]) > return Vector(data) > > In this example one uses "self" and "other". Does one really need to > use this words? And, if yes, why? I have replaced "self" by "x" and > "other" by "y" and everything looks OK. Is it really OK or I can have > some problem in some cases? Technically, Python doesn't care what you call them. You could write: def __add__(luxury_yacht, throat_warbler_mangrove): etc, etc, etc and it would run exactly the same. That being said, don't do that. The use of "self" and "other" are pretty much de rigueur. Experienced Python programers will instantly understand what they mean. If you use anything else, they will have to spend more time trying to understand your code. From deets at nospam.web.de Mon Jun 16 17:16:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 16 Jun 2008 23:16:54 +0200 Subject: How to request data from a lazily-created tree structure ? In-Reply-To: References: Message-ID: <6bo3ifF3dj7dmU1@mid.uni-berlin.de> m?choui schrieb: > Problem: > > - You have tree structure (XML-like) that you don't want to create > 100% in memory, because it just takes too long (for instance, you need > a http request to request the information from a slow distant site). > - But you want to be able to request data from it, such has "give me > all nodes that are under a "//foo/bar" tree, and have a child with an > "baz" attribute of value "zzz". > > Question : > > Do you have any other idea to request data from a lazily-created tree > structure ? > > And does it make sense to create a DOM-like structure and to use a > generic XPath engine to request the tree ? (and does this generic > XPath engine exist ?) > > The idea is to have the tree structure created on the fly (we are in > python), only when the XPath engine requests the data. Hopefully the > XPath engine will not request all the data from the tree (if the > request is smart enough and does not contain **, for instance). Generic XPath works only with a DOM(like) structure. How else would you e.g. evaluate an expression like foo[last()]? So if you really need lazy evaluation, you will need to specifically analyze the query of interest and see if it can be coded in a way that allows to forget as much of the tree as possible, or even better not query it. Diez From sniipe at gmail.com Tue Jun 24 06:11:03 2008 From: sniipe at gmail.com (sniipe at gmail.com) Date: Tue, 24 Jun 2008 03:11:03 -0700 (PDT) Subject: Difference between two dates Message-ID: Hi! I am new in Python, so I count for your help. I need to get difference in months between two dates. How to do it in python? I am substracting two dates, for example date1 - date2 and I got result in days, how to change it? Best regards From chris.ortner at googlemail.com Mon Jun 23 04:22:04 2008 From: chris.ortner at googlemail.com (Chris Ortner) Date: Mon, 23 Jun 2008 01:22:04 -0700 (PDT) Subject: Python module for working with a sudden motion sensor on Linux Message-ID: Hi everyone, I am looking for a python module or something similar which makes use of the capabilities of the kernel module applesmc to provide support for the sudden motion sensor in Apple hardware. It should be something like this: http://pypi.python.org/pypi/PyAppleSMS/1.0 Would it make sense to look for a generic accelerometer module or do I have to use something specific? Thanks for your help in advance! Chris From salmoni at gmail.com Mon Jun 16 07:17:40 2008 From: salmoni at gmail.com (Alan J. Salmoni) Date: Mon, 16 Jun 2008 04:17:40 -0700 (PDT) Subject: Notify of change to list References: <8b34cc2b-aa3a-4788-b849-1f926284c7ca@m36g2000hse.googlegroups.com> <90336d65-1537-46a5-92e1-9a8712d56e88@8g2000hse.googlegroups.com> Message-ID: Paul - thank you very much for your help, it was much appreciated. I thought that this was the kind of thing I had to do. I also messed around with properties to try and solve this problem, but noticed a similar thing (ie, that changing a mutable attribute's element is different to rebinding it): when a "propertied" attribute is rebound, the set method is called as expected. However, when setting an element of a mutable like a list, the get method is called and the set is not. This seems to be a bit of a gotcha. I'm sure that calling the get method is justified in the terms of Python internals, but as a user it seems a little counter-intuitive. Without being an expert on language design, my first thought was that changing an element was a "set" operation. Here's a toy: class tobj(object): def __init__(self): self._x = [0,1,2,3,4,5,6] def setx(self, x): print "At setx" self._x = x def getx(self): print "At getx" return self._x d = property(getx, setx) a = tobj() print "setting one element only" a.d[1] = 3 print "rebinding the attribute" a.d = 99 which comes up with: setting one element only At getx rebinding the attribute At setx Does anyone know why it works like this? I would guess that to "set" one element, the attribute needs to be retrieved which means the get method is called. I also guess that only rebinding calls the set method which is why it isn't called here. Alan On Jun 13, 11:19 am, Paul Hankin wrote: > On Jun 13, 12:00 pm, "Alan J.Salmoni" wrote: > > > My question is how can my program be notified of a change to a class > > attribute that is a list? > > You can't. But you can replace lists inside your class with a list > that notifies changes. > > Something like this: > > class NotifyingList(list): > def __setitem__(self, i, v): > print 'setting', i, 'to', v > list.__setitem__(self, i, v) > > [[You'll likely need to redefine __setslice__, __delitem__, > __delslice__, append and extend as well]]. > > >>> x = NotifyingList([1, 2, 3]) > >>> x[1] = 4 > setting 1 to 4 > >>> x > > [1, 4, 3] > > If users of your class are allowed to replace attributes with their > own lists, you'll have to catch these and convert to NotifyingLists; > and it may be somewhat messy. > > I hope this is useful to you. > > -- > Paul Hankin From duncan.booth at invalid.invalid Fri Jun 20 03:38:08 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Jun 2008 07:38:08 GMT Subject: Regular expression References: <42396af0-29aa-45ea-8588-186b0ccbab58@z16g2000prn.googlegroups.com> Message-ID: Sallu wrote: > string = 'rich?' ... > unicode(string)).encode('ASCII', 'ignore') ... > > Output : > > sys:1: DeprecationWarning: Non-ASCII character '\xc3' in file regu.py > on line 4, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details > rich? > Traceback (most recent call last): > File "regu.py", line 13, in ? > msg=strip_accents(string) > File "regu.py", line 10, in strip_accents > return unicodedata.normalize('NFKD', > unicode(string)).encode('ASCII', 'ignore') > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position > 4: ordinal not in range(128) > > The problem is the expression: unicode(string) which is equivalent to saying string.decode('ascii') The string contains a non-ascii character so the decode fails. You should specify whatever encoding you used for the source file. From the error message it looks like you used utf-8, so "string.decode('utf-8')" should give you a unicode string to work with. -- Duncan Booth http://kupuguy.blogspot.com From altricial at gmail.com Mon Jun 30 19:28:49 2008 From: altricial at gmail.com (vumensurvey) Date: Mon, 30 Jun 2008 16:28:49 -0700 (PDT) Subject: Male participants needed for body image research Message-ID: <68357e45-a61e-41b4-9a19-b2b635284992@q27g2000prf.googlegroups.com> Dear all, You are invited to participate in an online research on male body image. (If you are female, please pass this on to your male friends.) An Internet Study: The relationships between men's self-reported physical attributes, body image, self-esteem and internet dating. http://men.questionpro.com/ There has been quite a lot of research conducted on women's body image and we have a reasonable understanding of the types of factors that impact on women's body image and that ultimately lead to disorders like Anorexia and Bulimia Nervosa. However, we know very little about men's body image and the factors that impinge on the way males think about their bodies. Consequently we also know very little about how this impacts on men's health. Do you want to do something about it? If so, you are invited to take part in a research project that will focus exclusively on men's body image. Previous research has highlighted the impact of men's physical attributes on body image and how men perceive their own body. The purpose of this study is to further explore the relationship between physical qualities of men, their body image and self-esteem, using an Internet sample. All men above the age of 18, who have at least basic literacy in English, are invited to participate in this study. If possible, please have a tape measure ready. The questionnaire consists of 62 mostly multiple-choice questions and should take approximately 15 minutes to complete. Your responses will remain anonymous and no identifying information will be collected. You are free to withdraw from this study at any time. If you understand the information stated above and would like to participate in this study, please click on the link below: http://men.questionpro.com/ Thank you in advance for your time and input. Regards, Victoria University From Lie.1296 at gmail.com Wed Jun 11 08:14:35 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 11 Jun 2008 05:14:35 -0700 (PDT) Subject: can't assign to literal References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> <1a244dc4-4d10-491d-8ec7-224f3a1f0df5@m73g2000hsh.googlegroups.com> Message-ID: <12040996-7018-457d-93f8-253f0fbe5ba2@i18g2000prn.googlegroups.com> On Jun 11, 3:32?pm, MRAB wrote: > On Jun 10, 10:57 pm, "Steven Clark" wrote: > > > > for 1 in oids, vals head_oids: > > > SyntaxError: can't assign to literal > > > -- > > > 1 is a literal, you can't assign it to something. Are you trying to > > use it as a variable name? > > Slightly OT, but is there an editor that can display digits in a > different colour to letters? Most programmer oriented editors could, some even have full syntax coloring, they would color keywords (like def, class, etc), literals (1, 'hello', etc), and commonly used built-in function (int, ord, iter, etc). It really helped if you have to read/write lots of codes From bryancchan at gmail.com Thu Jun 19 15:46:47 2008 From: bryancchan at gmail.com (Chanman) Date: Thu, 19 Jun 2008 12:46:47 -0700 (PDT) Subject: [xlwt] Changing Cell Background Color Message-ID: I've posted this on the python-excel group, but perhaps people here know what to do. How does one change the cell background color using the xlwt module? I've looked at several tutorials but none show how to change the background color. I've tried the following: badBG = xlwt.Pattern() badBG.SOLID_PATTERN = 0x34 badBG.NO_PATTERN = 0x34 badBG.pattern_fore_colour = 0x34 badBG.pattern_back_colour = 0x34 badFontStyle = xlwt.XFStyle() badFontStyle.Pattern = badBG sheet1.write(1,1,'hello world', badFontStyle) However, the background cell color still remains white. Any help appreciated. From stephan.diehl at gmx.net Mon Jun 9 11:22:33 2008 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Mon, 09 Jun 2008 17:22:33 +0200 Subject: money data type Message-ID: Hi lazyweb, I'm wondering, if there is a usable money data type for python available. A quick search in pypi and google didn't convey anything, even though the decimal data type seemed to be planned as a money data type originaly. Thanks for any pointers Stephan From gagsl-py2 at yahoo.com.ar Tue Jun 17 02:42:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 17 Jun 2008 03:42:19 -0300 Subject: Buffer size when receiving data through a socket? References: <20080616202135.41c407de.johnjsal@NOSPAMgmail.com> Message-ID: En Mon, 16 Jun 2008 21:21:35 -0300, John Salerno escribi?: > I wrote some pretty basic socket programming again, but I'm still confused about what's happening with the buffer_size variable. Here are the server and client programs: > > -------------- > > from socket import * > > host = '' > port = 51567 > address = (host, port) > buffer_size = 1024 > > server_socket = socket(AF_INET, SOCK_STREAM) > server_socket.bind(address) > server_socket.listen(5) > > while True: > print 'waiting for connection...' > client_socket, client_address = server_socket.accept() > print '...connected from:', client_address > > while True: > data = client_socket.recv(buffer_size) > if not data: > break > client_socket.send('%s %s' % ('You typed:', data)) > > client_socket.close() > > server_socket.close() > > ------------ > > from socket import * > > host = 'localhost' > port = 51567 > address = (host, port) > buffer_size = 1024 > > client_socket = socket(AF_INET, SOCK_STREAM) > client_socket.connect(address) > > while True: > data = raw_input('> ') > if not data: > break > client_socket.send(data) > data = client_socket.recv(buffer_size) > if not data: > break > print data > > client_socket.close() > > --------------- > > I tried changing buffer_size to 10 and I got this output: > > john at john-laptop:~$ python myclient.py >> hello > You typed: >> something > hello >> this is a long string > You typed: >> why doesn't this work right > something >> > john at john-laptop:~$ > > My first question is, isn't buffer_size the number of bytes being sent at one time? If so, why doesn't 'hello' get printed after the server returns the data to the client? Isn't 'hello' just 5 bytes? Both programs say recv(buffer_size) - buffer_size is the maximum number of bytes to be RECEIVED, that is, READ. recv will return at most buffer_size bytes. It may return less than that, even if the other side sent the data in a single operation. Note that most of the time you want to use the sendall() method, because send() doesn't guarantee that all the data was actually sent. > Secondly, how is it working that once I type in a new string (e.g. 'something') and then the server returns data to the client, it prints the *previous* string, (i.e. 'hello')? Wouldn't the data variable get overwritten with the value, or is the value being stored somewhere else at this point? Yes, it is stored in an intermediate buffer until you read it. You typed "hello" and sent it, the server replied with the string "You typed: hello"; the OS stores it. You read only 10 bytes "You typed:", the remaining are still in the buffer. Next round: you type something, the server replies, you read the remaining bytes from the original reply, and so on... (Note that in this particular configuration, the client will fill its buffer at some time: because the server sends at least 11 bytes each round, but the client reads at most 10 bytes, so the client is always behind the server...) -- Gabriel Genellina From john.dohn.john at gmail.com Fri Jun 6 09:16:05 2008 From: john.dohn.john at gmail.com (John Dohn) Date: Sat, 7 Jun 2008 01:16:05 +1200 Subject: Python CGI Upload from Server Status In-Reply-To: <9999810b0806060550w5a7297dbm8ba5cc902cad6f8b@mail.gmail.com> References: <9999810b0806060550w5a7297dbm8ba5cc902cad6f8b@mail.gmail.com> Message-ID: <608040960806060616ja7fbc89ya9c5f92c881b14d@mail.gmail.com> On Sat, Jun 7, 2008 at 12:50 AM, Derek Tracy wrote: > I am trying to create a simple python cgi app that allows the user to kick > off an ftp from the server the cgi is on to another server; I have that > piece working using ftplib but since the files in question are usually very > large (500mb to 2gb) in size I want to be able to display some sort of > status to the user, preferrably a progress bar of some sort. You'll need some AJAX progress bar (hint: google for this term ;-) that will be getting updates from the server or request an update every second or so. The question is if your upload code can provide progress tracking? If it's just a call to some xyz.upload("/here/is/my-500M-file.bin") that only returns after several minutes of uploading without giving you any updates on how fast things go you're probably out of luck. OTOH if it can do e.g.callbacks for progress reporting or if it can run in a separate thread that you could query somehow you can hook that to that AJAX thing of your choice. JDJ -------------- next part -------------- An HTML attachment was scrubbed... URL: From jhenRemoveThis at talk21.com Sun Jun 29 22:52:47 2008 From: jhenRemoveThis at talk21.com (John Henderson) Date: Mon, 30 Jun 2008 12:52:47 +1000 Subject: How to invoke the Python idle References: <08484763-05df-49ee-b308-2dd64b7e2379@e39g2000hsf.googlegroups.com> Message-ID: <6cr040F3ihfodU1@mid.individual.net> Only-Trouble wrote: > Hi all > I am running openSUSE 10.3 > I am learning python on my own, it seems like the system has > already installed a python IDLE > The question is how to invoke it? If it's anything like my Red Hat system, I had to find the command first. In my case, at: /usr/lib/python2.2/site-packages/idle/idle I copied that file to somewhere where it was available on my $PATH variable. John From gagsl-py2 at yahoo.com.ar Thu Jun 19 02:56:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 19 Jun 2008 03:56:01 -0300 Subject: Doc tests in Python References: <7d08373e-7b52-4c6a-a77f-29d3f9fc5672@59g2000hsb.googlegroups.com> Message-ID: En Thu, 19 Jun 2008 02:46:15 -0300, J-Burns escribi?: > Hello. Im new to using doctests in python. Could some1 tel me how to > use doctests if i have a constructor in my code? Just construct the desired objects inside the doctest. See the difflib module for a couple examples. If it's hard/undesirable/annoying to construct the objects for every test, you may use the "globs" or "extraglobs" argument to doctest.testmod. Something like this: class SomeClass: def __init__(self, a, lot, of arguments, are, required): ... def some_method(self, arg): """Does this and that... In the test below, obj refers to the already created instance (below, in _test) >>> obj.some_method(self, 123) True >>> obj.some_method(self, "hi") False """ ... def _test(): import doctest obj = SomeClass(create, the instance, using, a, lot, of, arguments) doctest.testmod(extraglobs={'obj': obj}) if __name__=='__main__': _test() But I prefer to keep the doctests self-contained whenever possible. -- Gabriel Genellina From google at mrabarnett.plus.com Thu Jun 19 09:58:42 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 19 Jun 2008 06:58:42 -0700 (PDT) Subject: Simple Python implementation of bag/multiset Message-ID: <9ddb3f88-f326-4015-906f-3fd242ae2d88@34g2000hsh.googlegroups.com> While another thread is talking about an ordered dict, I thought I'd try a simple implementation of a bag/multiset in Python. Comments/ suggestions welcome, etc. class bag(object): def __add__(self, other): result = self.copy() for item, count in other.iteritems(): result._items[item] = result._items.get(item, 0) + count return result def __and__(self, other): result = bag() for item, count in other.iteritems(): new_count = min(self._items.get(item, 0), count) if new_count > 0: result._items[item] = new_count return result def __contains__(self, item): return item in self._items def __eq__(self, other): return self._items == other._items def __getitem__(self, item): return self._items[item] def __iadd__(self, other): self._items = self.__add__(other)._items return self def __iand__(self, other): self._items = self.__and__(other)._items return self def __init__(self, iterable=None): self._items = {} if iterable is not None: for item in iterable: self._items[item] = self._items.get(item, 0) + 1 def __ior__(self, other): self._items = self.__or__(other)._items return self def __isub__(self, other): self._items = self.__sub__(other)._items return self def __iter__(self): for item, count in self.iteritems(): for counter in xrange(count): yield item def __ixor__(self, other): self._items = self.__xor__(other)._items return self def __len__(self): return sum(self._items.itervalues()) def __ne__(self, other): return self._items != other._items def __or__(self, other): result = self.copy() for item, count in other.iteritems(): result._items[item] = max(result._items.get(item, 0), count) return result def __repr__(self): result = [] for item, count in self.iteritems(): result += [repr(item)] * count return 'bag([%s])' % ', '.join(result) def __setitem__(self, item, count): if not isinstance(count, int) or count < 0: raise ValueError if count > 0: self._items[item] = count elif item in self._items: del self._items[item] def __sub__(self, other): result = bag() for item, count in self.iteritems(): new_count = count - other._items.get(item, 0) if new_count > 0: result._items[item] = new_count return result def __xor__(self, other): result = self.copy() for item, count in other.iteritems(): new_count = abs(result._items.get(item, 0) - count) if new_count > 0: result._items[item] = new_count elif item in result._item: del result._items[item] return result def add(self, item): self._items[item] = self._items.get(item, 0) + 1 def discard(self, item): new_count = self._items.get(item, 0) - 1 if new_count > 0: self._items[item] = new_count elif new_count == 0: del self._items[item] def clear(self): self._items = {} def copy(self): result = bag() result._items = self._items.copy() return result def difference(self, other): return self.__sub__(other) def difference_update(self, other): self._items = self.__sub__(other)._items def get(self, item, default=0): return self._items.get(item, default) def intersection(self, other): return self.__and__(other) def intersection_update(self, other): self.__iand__(other) def items(self): return self._items.items() def iteritems(self): return self._items.iteritems() def iterkeys(self): return self._items.iterkeys() def itervalues(self): return self._items.itervalues() def keys(self): return self._items.keys() def pop(self): item = self._items.keys()[0] self._items[item] -= 1 if self._items[item] == 0: del self._items[item] return item def remove(self, item): new_count = self._items[item] - 1 if new_count > 0: self._items[item] = new_count else: del self._items[item] def symmetric_difference(self, other): return self.__xor__(other) def symmetric_difference_update(self, other): self.__ixor__(other) def union(self, other): return self.__or__(other) def update(self, other): self.__ior__(other) def values(self): return self._items.values() From deets at nospam.web.de Mon Jun 9 11:35:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 09 Jun 2008 17:35:52 +0200 Subject: How to find the first space? References: <7a91cc8f-2e93-46e9-8360-a01da9170187@m44g2000hsc.googlegroups.com> Message-ID: <6b5100F3a49r4U2@mid.uni-berlin.de> Russell Blau wrote: > "Johny" wrote in message > news:7a91cc8f-2e93-46e9-8360-a01da9170187 at m44g2000hsc.googlegroups.com... >> How can I find the first space using regex? >> >> For example I have text >> Text=' This is a sample ' > > Why do you need to use a regex? > > text = text.replace(" ", "") You are aware that this is producing nonsense given the OP's requirements? >>> print Text.replace(" ", "") Thisisasample Instead, the OP wants >>> print Text.strip() This is a sample Diez From alexnbryan at gmail.com Wed Jun 11 17:04:37 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 11 Jun 2008 14:04:37 -0700 (PDT) Subject: problems with opening files due to file's path In-Reply-To: <__W3k.6394$ZE5.2948@nlpi061.nbdc.sbc.com> References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> <77acc29a-fffa-44d6-b07b-6bcf8b5bdd74@h1g2000prh.googlegroups.com> <__W3k.6394$ZE5.2948@nlpi061.nbdc.sbc.com> Message-ID: <17787228.post@talk.nabble.com> Haha, okay well sorry that I was being so stupid, but I get it now and I apoligize for causing you all the frustration. But I did get it to work finally. Carsten Haese-2 wrote: > > Alexnb wrote: >> I don't get why yall are being so rude about this. > > We're frustrated with your apparent inability to understand anything > we're saying. > >> My problem is this; the >> path, as a variable conflicts with other characters in the path, creating >> escape characters I don't want, so I need a way to send the string to the >> os.startfile() in raw, or, with all the backslashes doubled. > > No, no, no, no, NO! That is not your problem! You are drawing unfounded > conclusions from the fact that you had to double up backslashes when the > filename came from a string literal. The situation is entirely different > when the filename comes from user input. No doubling up of backslashes > is necessary when the filename comes from user input. TRUST ME! > > For simplicity, start with this code to convince yourself: > > import os > filename = raw_input("Please enter a filename: ") > os.startfile(filename) > > Once you get that to work, replace raw_input with a function that gets > the filename from your GUI. > > Hope this helps, > > -- > Carsten Haese > http://informixdb.sourceforge.net > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17787228.html Sent from the Python - python-list mailing list archive at Nabble.com. From lists at cheimes.de Sun Jun 15 10:05:22 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 15 Jun 2008 16:05:22 +0200 Subject: 32 bit or 64 bit? In-Reply-To: References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> Message-ID: ram.rachum at gmail.com wrote: > Does it mean that even now it does arithmetic in 64 bit? > I'm not getting enough precision. Is there any way to increase it? Buy a good book about numerics or take a course. ;) Seriously, computers and IEEE 754 floating point numbers have a lot of pit falls. If you chose the wrong algorithm you *will* get wrong results. With floats a*b*c and a*c*b can give you a different result. The decimal module is not an option if you need speed. From gagsl-py2 at yahoo.com.ar Tue Jun 17 03:46:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 17 Jun 2008 04:46:38 -0300 Subject: print problem References: <2MWdnYXqCY3yy8rVnZ2dnUVZ_sbinZ2d@posted.internode> <48576371.7000209@gmail.com> Message-ID: En Tue, 17 Jun 2008 04:10:41 -0300, Rich Healey escribi?: > Gabriel Genellina wrote: >> En Tue, 17 Jun 2008 03:15:11 -0300, pirata escribi?: >> >>> I was trying to print a dot on console every second to indicates >>> running process, so I wrote, for example: >>> >>> for i in xrange(10): >>> print ".", >>> time.sleep(1) >>> >>> Idealy, a dot will be printed out each second. But there is nothing >>> print out until after 10 seconds, all 10 dots come out together. >>> >>> I've tried lose the comma in the print statement, and it works. >>> >>> Is that because of the print statement buffer the characters until >>> there is a new line character? >> >> Very probably, altough I can't reproduce it on Windows. Try invoking the script with python -u (unbuffered input/output): >> >> python -u your_script.py >> > Or just write to sys.stdout without the print wrapper.. I think the output is still buffered, even if you write directly to sys.stdout, but I don't have a Linux box to test right now. -- Gabriel Genellina From nick at craig-wood.com Thu Jun 12 15:31:05 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 12 Jun 2008 14:31:05 -0500 Subject: get keys with the same values References: <3fdafa74-2043-4052-bdec-843f69d9e5fa@e39g2000hsf.googlegroups.com> Message-ID: Paul McGuire wrote: > Instead of all that try/except noise, just use the new defaultdict: > > >>> from collections import defaultdict > >>> > >>> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} > >>> > >>> dd = defaultdict(list) > >>> for key, value in d.items(): > ... dd[value].append(key) > ... > >>> for k,v in dd.items(): > ... print k,':',v > ... > 1 : ['a', 'e'] > 2 : ['c'] > 3 : ['b', 'd'] > 4 : ['f'] > Or use the little understood dict.setdefault method which has been with us from time immemorial... >>> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} >>> dd = {} >>> for k, v in d.items(): ... dd.setdefault(v, []).append(k) ... >>> dd {1: ['a', 'e'], 2: ['c'], 3: ['b', 'd'], 4: ['f']} >>> -- Nick Craig-Wood -- http://www.craig-wood.com/nick From nospam at nospam.com Sun Jun 1 09:17:44 2008 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 01 Jun 2008 15:17:44 +0200 Subject: [Business apps for Windows] Good grid + calendar, etc.? References: Message-ID: <888544pf6jfdb2bj537dpqpfa7vn5n7u98@4ax.com> On Sun, 1 Jun 2008 21:59:29 +0900, "Ryan Ginstrom" wrote: >wxPython can be made to look pretty nice. Check out Chandler for an example. >http://chandlerproject.org/ Yup, they developped some nice-looking widgets, but it doesn't seem like there's an ecosystem around wxWidgets. I, for one, wouldn't mind paying for widgets missing from the stock version. >If you don't mind being Windows-only, there's another approach that I've >been working on. Thanks for the idea, but I don't have the skills for something like that :-) Besides, the reason for Python is to make it faster/easier to write apps, so WTL + browser + COM seems too hard for me. From bruno.desthuilliers at gmail.com Mon Jun 30 16:53:32 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 30 Jun 2008 13:53:32 -0700 (PDT) Subject: list extension ? References: <4868b0ba$0$17063$426a34cc@news.free.fr> Message-ID: On 30 juin, 21:05, Stef Mientki wrote: > thanks guys, > > >> def __init__ ( self, value = [] ) : > > > Gotcha : default argument values are eval'd only once. Also, it would > > make more sense IMHO to follow the parent's class initializer's > > behaviour: Ah hem.... Sorry, should have double-checked: > > def __init__(self, *args) > > >> list.__init__ ( self, value ) > > > list.__init__(self, *args) > > that's even better, except the call must be > list.__init__ ( self, args ) Indeed. Which makes my whole comment about "following parent's class behaviour" totally off-tracks. Should have shut up here :( From hancock.robert at gmail.com Mon Jun 16 13:59:30 2008 From: hancock.robert at gmail.com (milan_sanremo) Date: Mon, 16 Jun 2008 10:59:30 -0700 (PDT) Subject: sqlite3 and Python 2.5.1 Message-ID: <612ed26a-c6cf-4133-af6c-f256484e3928@x41g2000hsb.googlegroups.com> I have sqlite installed, but when I try to import sqlite3 I receive: Python 2.5.1 (r251:54863, Nov 3 2007, 02:54:36) [C] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 Traceback (most recent call last): File "", line 1, in ImportError: No module named sqlite3 >>> Yet: # find /usr/local/python -name "sqlite*" -print /usr/local/python/lib/python2.5/sqlite3 # /opt/csw/bin/sqlite3 SQLite version 3.2.2 Enter ".help" for instructions sqlite> What is missing? From stdenton at sbcglobal.net Sat Jun 7 17:38:19 2008 From: stdenton at sbcglobal.net (Sam Denton) Date: Sat, 07 Jun 2008 16:38:19 -0500 Subject: simple question on list manipulation from a newbie In-Reply-To: <76ccc0a8-90de-4717-9e6f-06836827b1e1@i18g2000prn.googlegroups.com> References: <76ccc0a8-90de-4717-9e6f-06836827b1e1@i18g2000prn.googlegroups.com> Message-ID: <6hD2k.4836$co7.3109@nlpi066.nbdc.sbc.com> Sengly wrote: > Dear all, > > I am working with wordnet and I am a python newbie. I'd like to know > how can I transfer a list below > > In [69]: dog > Out[69]: > [{noun: dog, domestic_dog, Canis_familiaris}, > {noun: frump, dog}, > {noun: dog}, > {noun: cad, bounder, blackguard, dog, hound, heel}, > {noun: frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, > weenie}, > {noun: pawl, detent, click, dog}, > {noun: andiron, firedog, dog, dog-iron}] > > to a list like this with python: > > [dog, domestic_dog, Canis_familiaris, > frump, dog, > dog, > cad, bounder, blackguard, dog, hound, heel, > frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, > weenie}, > pawl, detent, click, dog}, > andiron, firedog, dog, dog-iron] I can't help you with the formatting, but here's a solution using Python data structures: >>> alist = [ {'noun': ('dog', 'domestic_dog', 'Canis_familiaris')}, {'noun': ('frump', 'dog')}, {'noun': ('dog',)}, {'noun': ('cad', 'bounder', 'blackguard', 'dog', 'hound', 'heel')}, {'noun': ('frank', 'frankfurter', 'hotdog', 'hot_dog', 'dog', 'wiener', 'wienerwurst', 'weenie')}, {'noun': ('pawl', 'detent', 'click', 'dog')}, {'noun': ('andiron', 'firedog', 'dog', 'dog-iron')}, ] >>> merged = {} >>> for d in alist: for key, value in d.iteritems(): merged.setdefault(key, []).extend(value) >>> merged {'noun': ['dog', 'domestic_dog', 'Canis_familiaris', 'frump', 'dog', 'dog', 'cad', 'bounder', 'blackguard', 'dog', 'hound', 'heel', 'frank', 'frankfurter', 'hotdog', 'hot_dog', 'dog', 'wiener', 'wienerwurst', 'weenie', 'pawl', 'detent', 'click', 'dog', 'andiron', 'firedog', 'dog', 'dog-iron']} From exarkun at divmod.com Mon Jun 16 13:09:16 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 16 Jun 2008 13:09:16 -0400 Subject: String Concatenation O(n^2) (was: Re: Explaining Implementing a Binary Search Tree.) In-Reply-To: <3fc761710806160941q3c1a93b5p7761fbe148718585@mail.gmail.com> Message-ID: <20080616170916.4714.1881297769.divmod.quotient.9773@ohm> On Mon, 16 Jun 2008 10:41:05 -0600, Ian Kelly wrote: >On Mon, Jun 16, 2008 at 4:34 AM, Bart Kastermans wrote: >> This is interesting. I had never attempted to verify a big O >> statement >> before, and decided that it would be worth trying. So I wrote some >> code to >> collect data, and I can't find that it goes quadratic. I have the >> graph >> at >> >> http://kasterma.wordpress.com/2008/06/16/complexity-of-string-concatenation/ >> >> It looks piecewise linear to me. > >I don't think there's any question that it's quadratic. Just look at >the C code, and you'll see that every time you concatenate the entire >string has to be copied. It will depend what version of Python you're using and the *exact* details of the code in question. An optimization was introduced where, if the string being concatenated to is not referred to anywhere else, it will be re-sized in place. This means you'll probably see sub-quadratic behavior, but only with a version of Python where this optimization exists and only if the code can manage to trigger it. Jean-Paul From casey.mcginty at gmail.com Fri Jun 6 16:43:15 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Fri, 6 Jun 2008 10:43:15 -1000 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: References: <484808F7.5040203@arimaz.com> Message-ID: On Thu, Jun 5, 2008 at 11:39 AM, Terry Reedy wrote: > > If you want to access the attribute of a particular class, to read or > write, use that class. > SomeClass.attr > Note that no instance is required or relevant. > > If you want to read the attrubute of the class of an instance (or the first > superclass with the attribute, whatever that class might be, use self.attr > or self.__class__.attr. (Use the latter if the instance has (or might > have) an attribute of the same name). > > For setting an attribute, self.attr = x sets it on the instance while > self.__class__.attr = x sets it on its class. > > So the key here is that obj.__class__.attr will only access the immediate child class name space, but SuperClass.attr will guarantee your are access the first super class namespace? If that is true, then the bug makes sense. -------------- next part -------------- An HTML attachment was scrubbed... URL: From remy.blank at pobox.com Wed Jun 4 16:23:06 2008 From: remy.blank at pobox.com (Remy Blank) Date: Wed, 04 Jun 2008 22:23:06 +0200 Subject: Exit from os.chroot() In-Reply-To: References: Message-ID: Thomas Bellman wrote: > That might not be the best idea... Suddenly the chroot:ed > program has access to the real /usr/bin; and since it likely is > running as root (it was allowed to call chroot()), it can do bad > things to the things in /usr/bin. If a chrooted process is running as root, it can very easily break out of the chroot anyway. So... > Also remember, a chroot:ing process should permanently relinquish > its privileges as soon as possible after chroot:ing. There are > way too many fun things a root-running process can do even when > chroot:ed, like creating device files or setuid binaries. ...this is imperative. > All this is of course assuming that the chroot is done for > security reasons. But here's something that might be interesting: http://kerneltrap.org/Linux/Abusing_chroot Short story: chroot is not and never has been a security tool. -- Remy From mccredie at gmail.com Mon Jun 30 18:49:34 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 30 Jun 2008 15:49:34 -0700 (PDT) Subject: raw_input into Tkinter ? References: <634e2b50-45ba-4b93-89b4-0afd739adaf3@z66g2000hsc.googlegroups.com> Message-ID: <9571b5b0-7b18-4045-a912-6635a6e86500@l42g2000hsc.googlegroups.com> On Jun 30, 9:55?am, jamitwi... at gmail.com wrote: > Is there any way to type into a Tkinter frame window? > I want to use raw_input() within a Tkinter frame. `raw_input(prompt)` just calls `sys.stdout.write(prompt)` and returns `sys.stdin.readline()`. So, you can just create file-like objects to replace stdout and stdin that are aware of your Tkinter gui. Alternatively, you could just replace __builtins__.raw_input with your own version. Actual implementation left as an exercise for the user. Matt From bmilliron at gmail.com Wed Jun 11 15:34:36 2008 From: bmilliron at gmail.com (Ben) Date: Wed, 11 Jun 2008 12:34:36 -0700 (PDT) Subject: *** Massive Copyright Violation by the US Government *** References: <06c58239-b892-4e16-b4dc-5a2d9f528946@j22g2000hsf.googlegroups.com> Message-ID: On Jun 11, 3:06 pm, lemnit... at india.com wrote: > Printing dollar is a copyright violation > ---------------------------------------------------- > > I recently heard that the USA government or the unfederal reserve is > printing dollars. Is this a copyright violation ? > > Is this also a theft ? > > Is there a scheme to print dollars in such a way to selectively > deflate the dollars owned by non-US entities while unaffecting the > wealth or wealth ratio of the native population ? Is there a scheme to > give people the difference by this method ? Are there any grants or > subsidies to implement this scheme/scam ? > > Lyman L. Lemnitzer > Master schemer of Operation Northwoods > > please look at my favorite websites:http://iamthewitness.com > > Also look at > Painful Deceptions by Alex Jones and Eric Hufschmidt. > > Do you know if war on terror was genuine, the anthrax mailer would > have been caught first ? This group is to answer questions about the Python programming language. Please respect that and start your own group for political theory/speculation. From jeffnyman at gmail.com Thu Jun 5 08:58:47 2008 From: jeffnyman at gmail.com (Jeff Nyman) Date: Thu, 5 Jun 2008 05:58:47 -0700 (PDT) Subject: Creating A Tuple From A List, Adding To Tuple As You Do References: Message-ID: <84ce4c88-ff69-413e-961f-ffbb17ed5a95@t54g2000hsg.googlegroups.com> Thanks to everyone who responded! Yes, those solutions all work and do what I need. I'm also getting much more familiar with how flexible Python is in terms of its language. I think that's been the hardest challenge for me. I'm usually finding I try to "overdo it" when coming up with solutions. Once again, many thanks. - Jeff From gnewsg at gmail.com Fri Jun 13 14:36:07 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Fri, 13 Jun 2008 11:36:07 -0700 (PDT) Subject: best way to create a timer References: Message-ID: On 13 Giu, 07:42, Alexnb wrote: > I am wondering what is the best way to create a timer, like an alarm, once it > reaches a time, it triggers an event. I have a way of doing this but it > seems like it isn't good at all. If it helps at all I am using a Tkinter, > but that probably doesn't mean much. The way I was doing it was using a > while loop, and just saying while current time is not = to trigger time, do > nothing, and when it is, do event. > -- > View this message in context:http://www.nabble.com/best-way-to-create-a-timer-tp17815502p17815502.... > Sent from the Python - python-list mailing list archive at Nabble.com. I think that threading.Timer could be what you're searching for. --- Giampaolo http://code.google.com/p/pyftpdlib/ From reckoner at gmail.com Mon Jun 9 21:57:22 2008 From: reckoner at gmail.com (Reckoner) Date: Mon, 9 Jun 2008 18:57:22 -0700 (PDT) Subject: access variables from one Python session to another on the same machine? References: <6ea6b084-3897-43f9-b8e0-dff52b47f1a0@w1g2000prd.googlegroups.com> Message-ID: On Jun 9, 5:23 pm, "Daniel Fetchinson" wrote: > > Suppose I have two different command windows going on the same > > machine, each running their own Python interpreters. > > > Is it possible to access the variables in one of the interpreter- > > sessions from the other? > > > It turns out I have limited control over one of the sessions (i.e. > > cannot control all the code that is run from there), but complete > > control over the other. > > > I get the feeling this has been asked before, but I'm not sure how to > > pose the question in such a way that it would show up on a search. > > It's confusing. > > Depending on what 'limited control' means, the simplest choice would > be writing stuff to a plain text file from the master and reading it > from the slave. This may or may not work depending on your environment > though. > > Cheers, > Daniel > -- > Psss, psss, put it down! -http://www.cafepress.com/putitdown This disk-writing approach seems to be simplest & less intrusive. Thanks! I'll try it. From fetchinson at googlemail.com Sat Jun 21 21:17:01 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 21 Jun 2008 18:17:01 -0700 Subject: Connecting a Desktop App to a Web App In-Reply-To: References: Message-ID: > Okay, this is my first post to this mailing list, so first off if I > shouldn't be sending something here, PLEASE correct me. Okay, so I > want to create an app that has a GUI (most likely Tkinter) and will > prompt the user to choose files and such and then will upload those > files, either regularly or one time, whatever. But I don't know how to > go abou doing such a thing, that is creating a app that will > automatically upload to a back-up website(online storage). So if > anyone can help me out or point me in the right direction that would > be great. Thanks! There are two cases: (1) you are in control of the web app (2) you are not in control of the web app. (1) So you need to make the web app yourself too. There are several options for this the most popular ones are django and turbogears. For more see http://wiki.python.org/moin/WebFrameworks Once you have your web app up and running you can connect to it using some modules in the stdlib: http://docs.python.org/lib/module-urllib2.html http://docs.python.org/lib/module-httplib.html Basically you just create http requests in your desktop app and send those just as a browser would do. (2) You need to figure out the API of the web app you want to connect to. Once you have that use the stdlib modules to create the appropriate http requests just as above. HTH, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From karsten.heymann at blue-cable.net Fri Jun 13 11:55:44 2008 From: karsten.heymann at blue-cable.net (Karsten Heymann) Date: Fri, 13 Jun 2008 17:55:44 +0200 Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <878wx9leiv.fsf@ara.blue-cable.net> Message-ID: <873anhtjlr.fsf@ara.blue-cable.net> Hi Maric, Maric Michaud writes: > So, writing C in python, which has dictionnary as builtin type, > should be considered "more elegant" ? IMO that's a bit harsh. > You are comparing apples with lemons, there is no such a difference > between list index access and dictionnary key access in Python. [...] > If you know in advance the number and names of users, what prevent > you to initialize completelly the target dictionnary ? > > The following code compare the same algorithm, once with list and > the second time with dict : [...] > The result is pretty close now : > > maric at redflag1 17:04:36:~$ ./test.py > with list 1.40726399422 > with dict 1.63094091415 > > So why use list where the obvious and natural data structure is a > dictionnary ? I'd never argue that using a dictionary is the obvious and natural data structure for this case. But is it the best? Honestly, as your very nice example shows, we have two solutions that are equally fast, equally complex to code and equally robust, but one needs approximately the double amount of memory compared to the other. So, as much as i like dictionaries, what's the gain you get from using it in this corner case? Yours, Karsten From basti.wiesner at gmx.net Mon Jun 9 14:05:50 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Mon, 09 Jun 2008 20:05:50 +0200 Subject: Separators inside a var name References: Message-ID: Rainy at Montag 09 Juni 2008 19:29: > I have a stylistic question. In most languages words in var. name are > separated by underscores or cap letters, resulting in var names like > var_name, VarName and varName. I don't like that very much because all > 3 ways of naming look bad and/or hard to type. Then you better get used to such names, as they are common for many widely spread languages including C, C++, C#, Java, Python, Ruby, Perl and many more ;) You may like these or dislike these names, but you won't come around them ;) > From what I understand, scheme can have variables like var-name. I'm > curious about reasons that python chose to disallow this. "-" is an operator in Python. How should the parser know, whether "var-name" means "the object bound to var_dash_name" or "subtract the object bound to name from the object bound to var"? Scheme can allows such names, because its a functional programming language. Subtracting in this language is not done through operators, but through functions. Therefore there is a clear difference between referencing a name or subtracting two ones: var-name vs (- var name). > Another question I have is what other languages allow this naming scheme? Other lisp dialects do, due to the same reasons as scheme. > Were there any languages that allowed space as a separator? None that I know of. Probably one could use unicode characters, that look like a space in languages, which allow unicode characters in identifiers (as Java or C#, iirc), but I doubt this. Anyway, even if allowed, this would be silly, since it obscures code to the eyes of the reader. > What would be a practical way to separate variables from keywords in that > case? "some long variable name", 'just a string', or maybe using 2 spaces: > one var + other var + third var ? I can't image a practical way to allow a space as character in names, while still maintaining it syntactic element for separation of names. Quotes are normally used for string or characters literals and a double space is hard to distinguish from a single space, and things like ${a name with spaces} is a lot nastier than names with underscores (which aren't bad at all, imho). > I think being able to easy have very long names for vars that are easy to > type would be a fairly significant advantage. Names shouldn't be long, they should be expressive. If you can't give an object a _short_, but _expressive_ name, your object is too complicated ;) Btw, I don't really understand your refusal of underscores. In my opinion such names are harder to read than underscores, which look more like a real space, because the leave a space in the middle of a line, that you look at. If they are too hard for you to type, whats the point in swapping the dash and the underscore in your keyboard layout? -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From sjmachin at lexicon.net Mon Jun 2 20:48:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 2 Jun 2008 17:48:28 -0700 (PDT) Subject: Importing xlrd References: Message-ID: On Jun 3, 8:23 am, Chanman wrote: > This is probably a simple question to most of you, but here goes. > I've downloaded the xlrd (version 0.6.1) module and placed in in the > site-packages folder. Now, when I write a script, I type: > > import sys > import xlrd > > When I run it, there is an import error saying there is no module > named xlrd. However when I type sys.path, the site-packages folder is > definitely in the path. Do I somehow need to run the xlrd setup.py > first before importing? > > Any help would be appreciated. >From the xlrd home-page (http://www.lexicon.net/sjmachin/xlrd.htm): """ Installation: * Windows only: download and run this installer xlrd-0.6.1.win32.exe. Any platform: download this ZIP file xlrd-0.6.1.zip which you unzip into a suitable directory, then cd to that directory, and do "python setup.py install". """ >From the xlrd README file: """ Installation: * On Windows: use the installer. * Any OS: Unzip the .zip file into a suitable directory, chdir to that directory, then do "python setup.py install". * If PYDIR is your Python installation directory: the main files are in PYDIR/Lib/site-packages/xlrd (except for Python 2.1 where they will be in PYDIR/xlrd), the docs are in the doc subdirectory, and there's a sample script: PYDIR/Scripts/runxlrd.py * If os.sep != "/": make the appropriate adjustments. """ From maxm at mxm.dk Wed Jun 4 15:46:01 2008 From: maxm at mxm.dk (Max M) Date: Wed, 04 Jun 2008 21:46:01 +0200 Subject: ANN: Sydebar 1.0 - A browser sidebar generator for Python documentation In-Reply-To: <4846D09B.3090502@pobox.com> References: <4846D09B.3090502@pobox.com> Message-ID: Remy Blank skrev: > (I apologize for the poorly formatted message. Something between my news > client and the server decided, besides delaying the message for over 17 > hours, to add an empty line for every line of text, which obviously > messed up some headers. Here's the content again, and hopefully this > message comes through unaltered.) > > > I am pleased to announce the first release of Sydebar, a browser sidebar > generator for Python documentation. For the impatient, sample outputs > for all Python versions ever released can be found here: > > http://c-space.org/download/Sydebar/samples/ This looks great. I have been missing my chm based docs since moving to Python. This goes a long way. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From nicodotti2 at gmail.com Wed Jun 25 18:59:35 2008 From: nicodotti2 at gmail.com (nicodotti2) Date: Wed, 25 Jun 2008 15:59:35 -0700 (PDT) Subject: Communication between Python and PHP References: Message-ID: <8cd5f9db-46bc-491a-a58a-4ccc7086fa72@z16g2000prn.googlegroups.com> On Jun 25, 1:50 pm, Larry Bates wrote: > nicodotti2 wrote: > > Don't ask me why, but we have a bunch of legacy code in PHP on a > > server and a wee-bit of Python code for integrating GData google > > calendar services. We now need to build a way of sending messages > > between them. The general flow is: > > > PHP Web Page(on apache) ---> Python Gdata Consumer -----> Gdata > > and then json is returned back like: > > PHP Web Page<----json data---- Pthon Gdata Consumer > > > So I tried to convince my boss to let me use the python c extension to > > write a native bridge but 'no dice'. He also does not want anything > > 'experimental' so pyphp is out. He'd like me to basically have them > > communicate by passing the json via http/apache - so in essence, I'll > > have to make (what I feel) are very expensive calls between two > > objects that, in a perfect world, would be on the same machine in the > > same language! I see this as a potential bottleneck. Any suggestions? > > I have to start prototyping this today so the sooner the better, um, > > please ;) Thanks gurus out there. > > Use sockets. They are efficient and both languages have good implementations. > > -Larry Thanks Larry I'll look into going that route. From fernandes.fd at gmail.com Tue Jun 3 09:43:34 2008 From: fernandes.fd at gmail.com (Filipe Fernandes) Date: Tue, 3 Jun 2008 09:43:34 -0400 Subject: parser recommendation Message-ID: <11397a330806030643w3ff0ddd0v4ed74f57d49088a7@mail.gmail.com> I have a project that uses a proprietary format and I've been using regex to extract information from it. I haven't hit any roadblocks yet, but I'd like to use a parsing library rather than maintain my own code base of complicated regex's. I've been intrigued by the parsers available in python, which may add some much needed flexibility. I've briefly looked at PLY and pyparsing. There are several others, but too many to enumerate. My understanding is that PLY (although more difficult to use) has much more flexibility than pyparsing. I'm basically looking to make an informed choice. Not just for this project, but for the long haul. I'm not afraid of using a difficult (to use or learn) parser either if it buys me something like portability (with other languages) or flexibility). I've been to a few websites that enumerate the parsers, but not all that very helpful when it came to comparisons... http://nedbatchelder.com/text/python-parsers.html http://www.python.org/community/sigs/retired/parser-sig/towards-standard/ I'm not looking to start a flame war... I'd just like some honest opinions.. ;) thanks, filipe From mensanator at aol.com Sun Jun 8 12:04:10 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 8 Jun 2008 09:04:10 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net><484ad07b$0$25721$607ed4bc@cv.net> <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> Message-ID: On Jun 8, 3:19?am, "Terry Reedy" wrote: > "Mensanator" wrote in message > > news:8d7c0912-422f-4480-a034-078f9dbcae24 at 2g2000hsn.googlegroups.com... > | On Jun 7, 6:43?pm, "Terry Reedy" wrote: > | > zip(range(9,2000000000), iterable) > | > | Oh, dear. You didn't actually try this, did you? > > Works fine in Py3, which is what I use now. You really ARE cruel to the newbies, aren't you? Don't you think it would have been appropriate to attach a large red label: WARNING! PY3! From fc14301589 at icqmail.com Thu Jun 12 02:03:37 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Thu, 12 Jun 2008 14:03:37 +0800 Subject: can't assign to literal References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> <1a244dc4-4d10-491d-8ec7-224f3a1f0df5@m73g2000hsh.googlegroups.com> <484feda6_2@news.tm.net.my> Message-ID: <4850bc42_1@news.tm.net.my> On 01:37, gioved? 12 giugno 2008 Ethan Furman wrote: > Do you mean indenting, or wrapping? I mean fill the line by increasing spaces between words in order to get a paragraph aligned both side, left and right on the page. So if the width is 78 chars it wouldn't have jig saw end to the right side, unless applying some word hyphenation. This feature would be nice for writing here and some plain documentation plain text. Beside that it might doing for Python scripts as well. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From __peter__ at web.de Tue Jun 17 07:02:53 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 17 Jun 2008 13:02:53 +0200 Subject: 'string'.strip(chars)-like function that removes from the middle? References: <48569B9E.6030206@admailinc.com> <200806161839.13647.omer@no-log.org> Message-ID: Sion Arrowsmith wrote: > In article , > Peter Otten <__peter__ at web.de> wrote: >>Terry Reedy wrote: >>> >>> 'abcde'.translate(str.maketrans('','','bcd')) >>> 'ae' >>You should mention that you are using Python 3.0 ;) >>The 2.5 equivalent would be >> >>>>> u"abcde".translate(dict.fromkeys(map(ord, u"bcd"))) >>u'ae' > > Only if you're using Unicode: ... which is what you do if you are using the str type in 3.0. Peter From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 9 04:59:53 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 09 Jun 2008 10:59:53 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> Message-ID: <484cf0bb$0$4973$426a34cc@news.free.fr> Russ P. a ?crit : > On Jun 8, 5:40 am, Mark Wooding wrote: >> Russ P. wrote: >>> The idea of being able to discern properties of an object by its name >>> alone is something that is not normally done in programming in >>> general. >> Really? You obviously haven't noticed Prolog, Smalltalk, Haskell, ML, >> or Erlang then. And that's just the ones I can think of off the top of >> my head. >> >> * Prolog and Erlang distinguish atoms from variables by the case of >> the first letter; also `_' is magical and is equivalent to a new >> variable name every time you use it. >> >> * Smalltalk distinguishes between global and local variables according >> to the case of the first letter. >> >> * Haskell distinguishes between normal functions and constructors >> (both data constructors and type constructors) by the case of the >> first letter, and has Prolog's `_' convention. >> >> * ML allows a single-quote in variable names, but reserves names >> beginning with a single-quote for type variables. It also has >> Prolog's `_' convention. >> >> As far as I can see, discerning properties of a thing from its name >> seems relatively common. > > Well, "common" in Prolog, Smalltalk, Haskell, ML, and Erlang is hardly > common in general. I'll bet that Java and C/C++ are used more in North > Dakota than all those languages combined are used in the entire world. And you'll very probably loose. > That's not to say they aren't interesting academic languages, of > course. Erlang an "academic" language ? Man, you're either a troll or totally clueless. From alexnbryan at gmail.com Fri Jun 13 14:13:40 2008 From: alexnbryan at gmail.com (Alexnb) Date: Fri, 13 Jun 2008 11:13:40 -0700 (PDT) Subject: os.startfile() on a mac Message-ID: <17829335.post@talk.nabble.com> So i have a mac and pc, and just found out that os.startfile() doesn't work on a mac. So is there anything like that besides os.system()? -- View this message in context: http://www.nabble.com/os.startfile%28%29-on-a-mac-tp17829335p17829335.html Sent from the Python - python-list mailing list archive at Nabble.com. From hniksic at xemacs.org Thu Jun 12 08:50:40 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 12 Jun 2008 14:50:40 +0200 Subject: ClassName.attribute vs self.__class__.attribute References: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> <4850e95d$0$10444$426a74cc@news.free.fr> Message-ID: <8763sees0v.fsf@mulj.homelinux.net> Duncan Booth writes: > In fact, thinking about it a bit more, I think that if you did have > another metaclass which is its own metaclass then the class cannot > subclass 'object'. You could if the metaclass of your metaclass inherited from 'type'. Then your types could still be binary-compatible with Python types, and your objects with 'object'. It's difficult to envision what you'd gain with a custom meta-meta-class, but it seems possible: >>> class MetaMeta(type): pass ... >>> class Meta(type): ... __metaclass__ = MetaMeta ... >>> class Foo(object): ... __metaclass__ = Meta ... >>> f = Foo() >>> f <__main__.Foo object at 0xb7d27bec> >>> type(f) >>> type(type(f)) >>> type(type(type(f))) >>> isinstance(f, object) True From mensanator at aol.com Sun Jun 15 14:41:53 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 15 Jun 2008 11:41:53 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> Message-ID: <1f658382-1f45-41c2-a884-5478fef394bf@j22g2000hsf.googlegroups.com> On Jun 15, 12:10?pm, "ram.rac... at gmail.com" wrote: > On Jun 15, 7:43?pm, Peter Otten <__pete... at web.de> wrote: > > > ram.rac... at gmail.com wrote: > > > On Jun 15, 6:58?pm, Christian Meesters wrote: > > >> > I do need speed. Is there an option? > > > >> Mind telling us what you *actually* want to achieve? (What do you want to > > >> calculate?) > > > >> Christian > > > > Physical simulations of objects with near-lightspeed velocity. > > > How did you determine that standard python floats are not good enough? > > I have a physical system set up in which a body is supposed to > accelerate and to get very close to lightspeed, while never really > attaining it. After approx. 680 seconds, Python gets stuck and tells > me the object has passed lightspeed. I put the same equations in > Mathematica, again I get the same mistake around 680 seconds. So I > think, I have a problem with my model! Then I pump up the > WorkingPrecision in Mathematica to about 10. I run the same equations > again, and it works! At least for the first 10,000 seconds, the object > does not pass lightspeed. > I concluded that I need Python to work at a higher precision. > > > Everything beyond that is unlikely to be supported by the hardware and will > > therefore introduce a speed penalty. > > I have thought of that as well. However I have no choice. I must do > these calculations. If you know of any way that is supported by the > hardware, it will be terrific, but for now the slower things will have > to do. > > > Did you try gmpy? > > Not yet: I was kind of set back when I saw their homepage was last > updated 2002. Try looking here: http://code.google.com/p/gmpy/ The developers have abandoned SourceForge. > But I'll give it a try. You think it's the best thing > there is? I haven't tried everything, but it's very good. You might also want to go to the GMP site itself and get their manual. Likee anything else, your results will be no better than your algorithms. > > Thanks, > Ram. From mccredie at gmail.com Wed Jun 25 11:35:00 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 25 Jun 2008 08:35:00 -0700 (PDT) Subject: Sequence iterators with __index__ References: <433c6aca-745e-4c9f-b182-d76291449829@m73g2000hsh.googlegroups.com> <119bb268-2064-4128-8006-f5564f0c62f8@q27g2000prf.googlegroups.com> Message-ID: <44e89b70-e2b9-44a5-a02a-27482b6be681@d1g2000hsg.googlegroups.com> On Jun 24, 4:19?pm, schickb wrote: > On Jun 24, 3:45?pm, Matimus wrote: > > > > > > I think it would be useful if iterators on sequences had the __index__ > > > method so that they could be used to slice sequences. I was writing a > > > class and wanted to return a list iterator to callers. ?I then wanted > > > to let callers slice from an iterator's position, but that isn't > > > supported without creating a custom iterator class. > > > Could you post an example of what you are talking about? I'm not > > getting it. > > Interactive mock-up: > > >>> a = ['x','y','z'] > >>> it = iter(a) > >>> a[it:] > ['x', 'y', 'z'] > >>> it.next() > 'x' > >>> a[it:] > ['y', 'z'] > >>> a[:it] > ['x'] > >>> it.next() > 'y' > >>> a[it:] > > ['z'] > > This lets you use sequence iterators more general position indicators. > Currently if you want to track a position and slice from a tracked > position you must do it manually with an integer index. It's not > difficult, but given that sequence iterators already do that already > it seems redundant (and of course more error prone). > > > In any case, the first step is writing a PEP.http://www.python.org/dev/peps/ > > Ok thanks, but I do want some idea of interest level before spending a > bunch of time on this. > > -Brad I have no problem with being able to query the position (state) of an iterator without changing its state. I think using the iterator itself as the index or part of a slice in the original sequence is non- obvious and also less useful than just a new method to query state. "Explicit is better than Implicit". I would rather see just `it.index()` or `it.state()` than the new specialized behavior implied by `it.__index__()`. I'm leaning towards `state` because sequences already have an `index` method, and two methods of the same name with different behaviors may be confusing. This gives you essentially the same ability, and the code seems a little more obvious IMHO. >>> a = ['x','y','z'] >>> it = iter(a) >>> a[it.state():] ['x', 'y', 'z'] >>> it.next() 'x' >>> a[it.state():] ['y', 'z'] >>> a[:it.state()] ['x'] >>> it.next() 'y' >>> a[it.state():] ['z'] >>> it.state() 2 Matt From maehhheeyy at gmail.com Thu Jun 5 15:58:53 2008 From: maehhheeyy at gmail.com (maehhheeyy) Date: Thu, 5 Jun 2008 12:58:53 -0700 (PDT) Subject: Token Error: EOF in multiline statement Message-ID: I'm not sure what it means but it always highlights the last line with nothing on it. My program has 63 lines and it highlights the 64th line. This keeps popping up whenever I try to run my program. Can you please help me fix this? From johnjsal at NOSPAMgmail.com Tue Jun 17 09:34:24 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 17 Jun 2008 09:34:24 -0400 Subject: Buffer size when receiving data through a socket? References: <20080616202135.41c407de.johnjsal@NOSPAMgmail.com> Message-ID: <03b332ec$0$27271$c3e8da3@news.astraweb.com> "Gabriel Genellina" wrote in message news:mailman.547.1213684963.1044.python-list at python.org... > Both programs say recv(buffer_size) - buffer_size is the maximum number of > bytes to be RECEIVED, that is, READ. recv will return at most buffer_size > bytes. It may return less than that, even if the other side sent the data > in a single operation. > Note that most of the time you want to use the sendall() method, because > send() doesn't guarantee that all the data was actually sent. > I was wondering about sendall(). The examples I've read in two different books are consistent in their use of send() and don't even mention sendall(), so I thought maybe it was for a more specialized situation. > Yes, it is stored in an intermediate buffer until you read it. You typed > "hello" and sent it, the server replied with the string "You typed: > hello"; the OS stores it. You read only 10 bytes "You typed:", the > remaining are still in the buffer. Next round: you type something, the > server replies, you read the remaining bytes from the original reply, and > so on... Oh!!!! I didn't even count "You typed:" as part of the 10 bytes! And what a coincidence that it happens to be exactly 10 characters! That really helped to hide the problem from me! > (Note that in this particular configuration, the client will fill its > buffer at some time: because the server sends at least 11 bytes each > round, but the client reads at most 10 bytes, so the client is always > behind the server...) How is the server sending back 11 bytes? Is it because it's sending at least the 10 characters, plus the extra space? Thanks! From mikecdj at gmail.com Tue Jun 24 20:30:16 2008 From: mikecdj at gmail.com (mikecdj at gmail.com) Date: Tue, 24 Jun 2008 17:30:16 -0700 (PDT) Subject: Porn Addiction References: <0bc1d618-f140-4390-9dd0-4ade923ab054@w1g2000prd.googlegroups.com> Message-ID: On Jun 24, 7:24 pm, Hughjar... at gmail.com wrote: > Help, I'm addicted to porn. I've been downloading porn online and > masturbating to it for a few years... Lately it's gotten even worse, I > spend hours and hours surfing and masturbating to it. It's taking over > my life and ruining everything.. I even missed days from work because > of this addiction. > > I'm going to the porn as a way to avoid unwanted feelings or > procrastination and then it just takes over. > > What can I do to end this horrible addiction? > > -Hugh Install a porn filter immediately. This will block explicit sexual material from entering your computer. Download the Optenet porn filter at http://www.optenetpc.com/ You can beat this thing. From fuzzyman at gmail.com Wed Jun 11 15:17:50 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Wed, 11 Jun 2008 12:17:50 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <6e6df35e-e641-44d9-9f56-c0732306eec2@q27g2000prf.googlegroups.com> <13db98b5-ed2e-45ef-97ec-ad3caeeed10e@j1g2000prb.googlegroups.com> <074caf4a-de1e-4290-b688-30148786952c@z72g2000hsb.googlegroups.com> <776fd3e3-7c2e-45b1-8196-7cde93e72da3@w1g2000prd.googlegroups.com> <98d541c3-e974-4a8c-961c-2a59f6bf32ea@v26g2000prm.googlegroups.com> Message-ID: <4beb7bc4-61ae-4c61-b182-270ec1dd06cf@25g2000hsx.googlegroups.com> On Jun 11, 6:49?pm, Rhamphoryncus wrote: > On Jun 11, 7:56 am, Fuzzyman wrote: > > > > > On Jun 11, 6:56 am, Rhamphoryncus wrote: > > > > On Jun 10, 3:41 pm, Fuzzyman wrote: > > > > > On Jun 10, 2:03 am, Rhamphoryncus wrote: > > > > How does that protect code like this? > > > > f = open('somefile', 'w') > > > # interruption here > > > try: > > > ? ? ... > > > finally: > > > ? ? ... > > > How does it *not* protect you if you write this instead: > > > f = None > > try: > > ? f = open('somefile', 'w') > > ? ... > > finally: > > ? if f is not None: > > ? ? ... > > Yeah, that should be safe, so long as the open call itself is > protected. > > > > > > > The calculation is 'coarse grained' (it can call into .NET APIs that > > > > can take a relatively long time to return) - so polling for exit > > > > wouldn't work anyway. We also run user code and can't expect their > > > > code to poll for exit conditions. > > > > Do those .NET get interrupted at arbitrary points? ?Is this > > > "untrusted" user code also audited for correctness? ?(Although I'd bet > > > you simply document what you do and blame the user if something > > > breaks.) > > > We don't audit our user code - of course. We do document and assist > > them as necessary. Changing to a more restrictive model still wouldn't > > meet our use case and put *more* of a burden on our users. > > > Our situation is not the only one. In general there are situations > > where you may want to put a long running calulcation on a background > > thread and you *know* that it is safe to interrupt - but Python > > currently won't let you. > > > > I'm not saying it can't be made to work in your specific case - it > > > likely does work well for you. ?I'm saying it can't work *in > > > general*. ?Stretching it out for general use turns those little cracks > > > into massive canyons. ?A language needs a general mechanism that does > > > work - such as a polite cancellation API. > > > Neither *works in general* - polite cancellation *doesn't* work for > > our us. That's my point - you probably want *both* for different use > > cases. :-) > > Yeah, but mine's less icky. ;) > But requires more code. :-) > I think the ideal for you would be a separate process. ?I'd also > suggest a restricted VM only in a thread, but that probably wouldn't > work for those long-running .NET APIs. ?Now, if those long- > running .NET APIs did polite cancellation, then you could combine that > with a restricted VM to get what you need. No - we need to pull a large object graph *out* of the calculation (with no guarantee that it is even serializable) and the overhead for marshalling that puts using multiple processes out of the running. What we *want* is what we've got! And it works very well... None of the problems you predict. :-) We may at a future date look to using AppDomains to sandbox user code - but haven't needed to yet. Michael http://www.ironpythoninaction.com/ > > I think what bothers me is, even if those external APIs support polite > cancellation properly, your forced interruptions will bleed over and > mess them up. ?There needs to be a way of containing it better. > Writing them in another language (as C is used for most of Python's > builtins today) isn't a reasonable requirement. From johnjsal at NOSPAMgmail.com Thu Jun 5 10:20:53 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 5 Jun 2008 10:20:53 -0400 Subject: Proof that \ is a better line joiner than parenthetical sets Message-ID: <4847f59f$0$25187$c3e8da3@news.astraweb.com> Goofy post of the day... According to the Zen of Python, "explicit is better than implicit", and the section in the Reference Manual describing the \ line joiner is called "Explicit line joining" and the section describing parentheticals is called "Implicit line joining." So there! ;) From deets at nospam.web.de Mon Jun 16 05:04:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 16 Jun 2008 11:04:52 +0200 Subject: Removing inheritance (decorator pattern ?) References: <6blbcoF3b6v17U1@mid.uni-berlin.de> Message-ID: <6bmomrF3d11s6U1@mid.uni-berlin.de> Diez B. Roggisch wrote: > George Sakkis schrieb: >> I have a situation where one class can be customized with several >> orthogonal options. Currently this is implemented with (multiple) >> inheritance but this leads to combinatorial explosion of subclasses as >> more orthogonal features are added. Naturally, the decorator pattern >> [1] comes to mind (not to be confused with the the Python meaning of >> the term "decorator"). >> >> However, there is a twist. In the standard decorator pattern, the >> decorator accepts the object to be decorated and adds extra >> functionality or modifies the object's behavior by overriding one or >> more methods. It does not affect how the object is created, it takes >> it as is. My multiple inheritance classes though play a double role: >> not only they override one or more regular methods, but they may >> override __init__ as well. Here's a toy example: >> >> class Joinable(object): >> def __init__(self, words): >> self.__words = list(words) >> def join(self, delim=','): >> return delim.join(self.__words) >> >> class Sorted(Joinable): >> def __init__(self, words): >> super(Sorted,self).__init__(sorted(words)) >> def join(self, delim=','): >> return '[Sorted] %s' % super(Sorted,self).join(delim) >> >> class Reversed(Joinable): >> def __init__(self, words): >> super(Reversed,self).__init__(reversed(words)) >> def join(self, delim=','): >> return '[Reversed] %s' % super(Reversed,self).join(delim) >> >> class SortedReversed(Sorted, Reversed): >> pass >> >> class ReversedSorted(Reversed, Sorted): >> pass >> >> if __name__ == '__main__': >> words = 'this is a test'.split() >> print SortedReversed(words).join() >> print ReversedSorted(words).join() >> >> >> So I'm wondering, is the decorator pattern applicable here ? If yes, >> how ? If not, is there another way to convert inheritance to >> delegation ? > > Factory - and dynamic subclassing, as shown here: > > import random > > class A(object): > pass > > class B(object): > pass > > > def create_instance(): > superclasses = tuple(random.sample([A, B], random.randint(1, 2))) > class BaseCombiner(type): > > def __new__(mcs, name, bases, d): > bases = superclasses + bases > return type(name, bases, d) > > class Foo(object): > __metaclass__ = BaseCombiner > return Foo() > > for _ in xrange(10): > f = create_instance() > print f.__class__.__bases__ Right now I see of course that I could have spared myself the whole __metaclass__-business and directly used type()... Oh well, but at least it worked :) Diez From bruno.desthuilliers at gmail.com Fri Jun 6 15:02:24 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 6 Jun 2008 12:02:24 -0700 (PDT) Subject: Assigning to __class__ : bad form? References: <61f33$48497912$7402@news.teranews.com> Message-ID: On 6 juin, 19:51, The Pythonista wrote: > I've been wondering for a while about whether assigning to __class__ is > bad form or not. Specifically, I mean doing so when some other method of > implementing the functionality you're after is available (i.e. using an > adapter, or something like the strategy pattern). > > To give an example and a non-example of what I'm talking about, consider > the following recipes from the online Python Cookbook: > > Ring Buffer:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68429 > > In this case, I think the assignment to __class__ just obfuscates things, > and the example would be better coded as a single class. > > On the other hand, > > Fast copy of an object having a slow __init__ : http:// > aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66507 > > This seems like a reasonable use case for assigning to __class__ (except > that it's already implemented in the 'new' module, but, read the Martelli- > bot's comments near the end of the recipe). I consider this a reasonable > use case for assigning to __class__, because, short of the 'new' module, > I don't see any other way to accomplish it. > > So, what is the opinion of the broader Python community? My first opinion is that your formulation, ie "assigning *to* __class__" is perhaps a bit misleading. What you're talking about is rebinding the __class__ attribute, while, from your subject line, I thought you were talking about reassigning to (rebinding) a class attribute from the instance, ie : self.__class__.attrib = value. Now to the point: > Is code that > assigns to __class__ just clever trickiness to be avoided, or is it > sometimes a good thing? Both, definitively !-) Like most of Python's "advanced" features, it's nice to have it because it can easily solve problems that would otherwise be at best a PITA, but it's not something you use on a daily basis - nor without thinking twice. And obviously, there's no clear rule here, except good taste and common sense. Anyway, the mere fact that you're asking yourself if it's a good idea in such or such case is a probably a good indication that you'll find out by yourself the day you'll be tempted to use this trick whether it's a good or bad idea in this particular context. From deets at nospam.web.de Tue Jun 10 10:30:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 10 Jun 2008 16:30:58 +0200 Subject: str to float (rounded) References: Message-ID: <6b7hi9F3augt4U1@mid.uni-berlin.de> Nader wrote: > Hello, > > I have a list of tuple with strin elements. These elements are number, > but they are save as string. Now I will change the string to number > which will be rounded. An example will make it more clear. > > t = [('35.757', '-0.239'), ('33.332', '-2.707'), ('33.640', '-2.423')] > > And I will have the next list: > > t = [(35.76, -2.24), (33.33, -2.71), (33.64, -2.42)] > > The elements of tuple are not more as string. > > Would somebody tell me how I can do that? use float("123.45") to convert a string to a float. Of course you need to do that on all your elements above by e.g. a list-comprehension. Diez From tim.tadh at gmail.com Wed Jun 11 11:47:53 2008 From: tim.tadh at gmail.com (Tim Henderson) Date: Wed, 11 Jun 2008 08:47:53 -0700 (PDT) Subject: How to find duplicate 3d points? References: Message-ID: <4c86fa4b-1710-4e44-b2ed-0f4d82264bcb@d77g2000hsb.googlegroups.com> On Jun 11, 11:35?am, oprah.cho... at gmail.com wrote: > I have a large data file of upto 1 million x,y,z coordinates of > points. I want to identify which points are within 0.01 mm from each > other. I can compare the distance from each point to every other > point , but this takes 1 million * 1 million operations, or forever! > > Any quick way to do it, perhaps by inserting just the integer portion > of the coordinates into an array, and checking if the integer has > already been defined before inserting a new point? what many people do when doing collision detection in 3d games in instead of having one massive list of the vertices will break the field into bounding boxes. in the 2d situation that would look like this. |----|----|----|----| |. . | | .| | |----|----|----|----| |. |. | . |. | |----|----|----|----| | | . | . | | |----|----|----|----| | | | | . .| |----|----|----|----| That so instead of comparing all points against all other points instead sort them into bounding cubes. that should make doing the comparisons more reasonable. now the only sticky bit will be comparing two vertices that are in two different boxes but so close to the edges that they are under .01mm from each other. in this situation if a point is less that .01mm from any edge of its bounding cube you must compare it against the points in the adjacent cubes. hope this helps a bit. cheers Tim Henderson From rocky at panix.com Fri Jun 13 07:21:30 2008 From: rocky at panix.com (R. Bernstein) Date: Fri, 13 Jun 2008 07:21:30 -0400 Subject: Debuggers References: <485220ca_1@news.tm.net.my> Message-ID: TheSaint writes: > Hi, > > while testing my program I found some strange happening with pdb and pydb. > > I like pydb because let me restart the program and nicer features, but if > errors pop up, then it will forget all variables (globals and locals gone). I'm not completely sure what you mean, but I gather that in post-mortem debugging you'd like to inspect local variables defined at the place of error. For example in this program def raise_error: x=5 raise FloatingPointError raise_error you'd like to look at x. Python as a language is a little different than say Ruby. In Python the handler for the exception is called *after* the stack is unwound while in Ruby it is called before. What this means to you is basically what you reported: that you are not going to be able to see some local variables after an exception occurs (i.e. in post-mortem debugging) whether pydb, pdb, any debugger or any Python program you write. This was mentioned a while back: http://groups.google.com/group/comp.lang.python/browse_thread/thread/23418f9450c13c2d/b0b1908495dde7bc?lnk=st&q=#b0b1908495dde7bc By the way, although Ruby *does* call the exception handler before the stack is unwound, there's no way that I know to *clear* the exception so that you can dynamically "handle" it. This has a certain legitimacy since it might be dangerous to continue in some exception and the state of the interpreter may be inconsistent. For example if I write x = 1/0 or if 1/0 > 5 : what value do I use for 1/0? (Far worse is where something like a SEGV occurs, but I'm not sure that will raise an exception instead of terminate Python.) > I've to go for pdb because it isn't affected by that problem, but also in > some case pdb doesn't recognize a fix after a post-mortem restart. The funny > thing is that it shows the line corrected, but pdb execute the one it put in > memory. > However, I think also python shell has such flaw. I'd like to know how to > blank all current data and restart a program or re-import a corrected class > sentence. > Any other to try? > I'm also prone to use Ipython, but I still miss some learning how to run a > program within Ipython itself. > So if I do: > > import myprogram > myprogram.__main__ > > Will it run? And then the other arguments from CLI, how do I pass them in? > -- > Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From Russ.Paielli at gmail.com Thu Jun 5 00:50:19 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 4 Jun 2008 21:50:19 -0700 (PDT) Subject: line continuation for lines ending in "and" or "or" References: <90ee8b5d-1509-4463-aaab-f712f7e72d4b@j33g2000pri.googlegroups.com> Message-ID: <0d723e6d-f81b-4545-b406-fc60b20c5433@u6g2000prc.googlegroups.com> On Jun 4, 9:01 pm, Dan Bishop wrote: > On Jun 4, 10:09 pm, "Russ P." wrote: > > > I've always appreciated Python's lack of requirement for a semi-colon > > at the end of each line. I also appreciate its rules for automatic > > line continuation. If a statement ends with a "+", for example, Python > > recognizes that the statement obviously must continue. > > > I've noticed, however, that the same rule does not apply when a line > > ends with "and," "or," or "not." Yes, it's a minor point, but > > shouldn't the same rule apply? > > > Seems like it would be easy to add. > > Huh? This doesn't work either: > > >>> x = 2 + > > File "", line 1 > x = 2 + > ^ > SyntaxError: invalid syntax > > Implicit line continuation only happens if you have an unmatched '('. > > >>> x = (2 + > > ... 2 > ... )>>> x > > 4 Darnit! You're right. I've been reading up on Scala lately, and I guess I got confused. Well, it wouldn't be a bad idea for Python to do what I thought it did, *plus* what I said it ought to do. Scala is a nice language, by the way. Check it out when you get a chance (http://www.scala-lang.org). I'm thinking about switching over to it from Python if I can. I just wish it had default arguments and argument passing by keyword. Now, those are a couple of features that I really appreciate in Python. Oh, and I wish Scala used "and" and "or" rather than "&&" and "||". There's another thing Python got right. From google at mrabarnett.plus.com Wed Jun 25 09:41:04 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 25 Jun 2008 06:41:04 -0700 (PDT) Subject: Send output to printer References: <013c01c8d67f$869bfea0$1f01a8c0@RAZAK> Message-ID: <53fe9013-47d3-4e3d-a873-ab046812ab20@m3g2000hsc.googlegroups.com> On Jun 25, 7:49?am, "Jorgen Bodde" wrote: > Hi, > > It depends on how your printer can be accessed. Is there a driver for > it? The most simple way might be using ShellExecute (under windows) > but I found ?no way to supress the print dialog. > > Another way is using win32com module and instantiate an IE automation > object, which you feed a HTML page and issue a print. Be careful about > printing too fast allow it 4-5 seconds to process or successive print > jobs will fail. > > Here is a snippet of code to get you on your way; > > from win32com import client > ie = client.Dispatch("InternetExplorer.Application") > ie.Navigate(fn) ? ? ?# fn = filename (to temp file) to print > time.sleep(2) > ie.ExecWB(6, 2) > time.sleep(2) > ie.Quit() > ie = None > > For successive prints it is better to instantiate one IE object per > multiple print jobs, but once done, release it and set it up again. > > - Jorgen > > On Wed, Jun 25, 2008 at 6:54 AM, ajak_yahoo wrote: > > Need some help from you all, > > > I already manage to write a program to print a packaging label. > > > The output on screen is as below, > > > Part Number ? : ?PWEE1111AA > > Quantity ? ? ? ? : ?100 pcs > > Lot Number ? ? : ?10A2008 > > Customer ? ? ? ?: ?ABC Pte. Ltd. > > > My questions is how can I send this output to my Panasonic KX-P1121 dot > > matric printer, > > Is it a module that i can used, previously i wrote my program using foxpro > > 2.6, i have no experience in python. > > > Regards, > > Ajak > > -- > >http://mail.python.org/mailman/listinfo/python-list > > If it's connected to the PC's parallel printer port then you could try writing to "LPT1:": printer = open("LPT1:", "wb") printer.write("Hello world!\r\n") printer.close() Note that in order to advance to the next line you'll need to write a carriage return and linefeed ("\r\n"), as above. From mal at egenix.com Fri Jun 27 06:38:05 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 27 Jun 2008 12:38:05 +0200 Subject: Getting column names from a cursor using ODBC module? In-Reply-To: References: Message-ID: <4864C30D.2090209@egenix.com> John Machin wrote: > On Jun 21, 11:58 pm, dana... at yahoo.com wrote: >> Is there any way to retrieve column names from a cursor using the ODBC >> module? Or must I, in advance, create a dictionary of column position >> and column names for a particular table before I can access column >> values by column names? I'd prefer sticking with the ODBC module for >> now because it comes standard in Python. >> >> I'm using Python 2.4 at the moment. >> > > Do you mean the odbc module? If so, it doesn't come standard in > Python; it's part of the win32 package. > > I haven't used it for years -- my preference on Windows these days > would be mxODBC if the client would pay the licence fee, otherwise > pyodbc. Sorry I'm not answering your question ... perhaps you should > be asking a different question :) mxODBC comes with a cursor.columns() method which allows you to query column names and many other column specific details of the database. See the documentation for details: http://www.egenix.com/products/python/mxODBC/#Documentation If you just want to access the result set columns by name, you can use the cursor.description tuple to map names to positions. Please also see the FAQ of the DB API spec reagrding the issues involved with this approach: http://www.python.org/dev/peps/pep-0249/ -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From fc14301589 at icqmail.com Fri Jun 13 02:53:41 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Fri, 13 Jun 2008 14:53:41 +0800 Subject: can't assign to literal References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> <1a244dc4-4d10-491d-8ec7-224f3a1f0df5@m73g2000hsh.googlegroups.com> <484feda6_2@news.tm.net.my> <4850bc42_1@news.tm.net.my> Message-ID: <4852197f_1@news.tm.net.my> On 15:11, gioved? 12 giugno 2008 Dennis Lee Bieber wrote: > Word spaced line justification is only feasible if one is using a > fixed width font and have a line length defined in "characters/line". ===8<======8<======8<======8<======8<======8<======8<======8<======8<======8< line= 'fixed width font and have a line length defined in "characters/line".' lenLine= 78; newLine= ''; Words= line.split(' ') lnWords= len(Words); norm_spc= lnWords-1; xtr_spc = lenLine -len(line) lenChr= len(line)-norm_spc numspc= (norm_spc+ xtr_spc)/ norm_spc lstword= len(Words[norm_spc]) for spc in range(lnWords): if len(newLine)+lstword + numspc > lenLine : break newLine += Words[spc]+(' '* numspc) if xtr_spc: newLine += ' '; xtr_spc -= 1 print newLine+ ' '+ Words[spc] ===8<======8<======8<======8<======8<======8<======8<======8<======8<======8< In my mind it took me just few seconds :), but to get it working I spent nearly *one* hour. I admit that my skill lacks of knowledge ]) -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From nick at craig-wood.com Tue Jun 24 07:32:12 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 24 Jun 2008 06:32:12 -0500 Subject: Python 3000 vs Perl 6 References: Message-ID: Corey G. wrote: > The main concern (my concern) is whether or not Perl 6 is > more like Java with pre-compiled byte code (did I say that right) See below for some python VM comments > and whether or not individuals without the ability to see past the > surface will begin to migrate towards Perl 6 for its seemingly > faster capabilities. I doubt it but you never know! > With Perl 6 taking 10+ years, if/when it actually gets released, will > it be technically ahead of Python 3000? Perl 6 was a major reason for me to switch to using python. To make that radical a change in the language seemed reckless. The fact that it still hasn't been released after 8 years of development (Larry announced it in his State of the Onion speech in 2000 I think) makes me think that I made the right choice. Python 3.0 is a very gentle change to python in comparison. You won't have to change much of your code and when you do you'll think - that looks better! > Is Parrot worth the extra wait the Perl 6 project is enduring? My > own answer would be a resounding no, but I am curious as to what > others think. :) Another VM to run python would be nice of course, but we already have jython, ironpython and pypy. Both jython and ironpython use JIT, pypy can compile to native code and you can use psyco for JIT code also in normal python. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From xdicry at gmail.com Fri Jun 27 10:48:17 2008 From: xdicry at gmail.com (Evan) Date: Fri, 27 Jun 2008 07:48:17 -0700 (PDT) Subject: what is meaning of "@" in pyhon program. Message-ID: <88990b3d-1916-413f-83b9-796aabf43623@l28g2000prd.googlegroups.com> HI, When I check example of "cmd2" module (a enhancement of cmd module), I can not understand all, for example: the character "@", +++++++++++++++++++++++++++++++++++++++++++++++++++++ def options(option_list): .................. class cmd(...): ............................... @options([make_option('-p', '--piglatin', action="store_true", help="atinLay")]) +++++++++++++++++++++++++++++++++++++++++++++++++++++ I do not understand what "@options" does, most time, I know what the meaning of character "*" and character "**", but I was not use "@" before. Thanks for your help. From george.sakkis at gmail.com Thu Jun 12 00:51:05 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 11 Jun 2008 21:51:05 -0700 (PDT) Subject: Producer-consumer threading problem References: Message-ID: On Jun 11, 10:13?am, Jean-Paul Calderone wrote: > On Tue, 10 Jun 2008 22:46:37 -0700 (PDT), George Sakkis wrote: > >On Jun 10, 11:47 pm, Larry Bates wrote: > > >> I had a little trouble understanding what exact problem it is that you are > >> trying to solve but I'm pretty sure that you can do it with one of two methods: > > >Ok, let me try again with a different example: I want to do what can > >be easily done with 2.5 Queues using Queue.task_done()/Queue.join() > >(see example athttp://docs.python.org/lib/QueueObjects.html), but > >instead of ?having to first put all items and then wait until all are > >done, get each item as soon as it is done. > > >> 1) Write the producer as a generator using yield method that yields a result > >> every time it is called (something like os.walk does). ?I guess you could yield > >> None if there wasn't anything to consume to prevent blocking. > > >Actually the way items are generated is not part of the problem; it > >can be abstracted away as an arbitrary iterable input. As with all > >iterables, "there are no more items" is communicated simply by a > >StopIteration. > > >> 2) Usw somethink like Twisted insted that uses callbacks instead to handle > >> multiple asynchronous calls to produce. ?You could have callbacks that don't do > >> anything if there is nothing to consume (sort of null objects I guess). > > >Twisted is interesting and very powerful but requires a different way > >of thinking about the problem and designing a solution. More to the > >point, callbacks often provide a less flexible and simple API than an > >iterator that yields results (consumed items). For example, say that > >you want to store the results to a dictionary. Using callbacks, you > >would have to explicitly synchronize each access to the dictionary > >since they may fire independently. > > This isn't true. ?Access is synchronized automatically by virtue of the > fact that there is no pre-emptive multithreading in operation. ?This is > one of the many advantages of avoiding threads. :) ?There may be valid > arguments against callbacks, but this isn't one of them. > > Jean-Paul Thanks for the correction; that's an important advantage for callbacks in this case. George From delfick755 at gmail.com Fri Jun 6 07:19:56 2008 From: delfick755 at gmail.com (Stephen Moore) Date: Fri, 6 Jun 2008 19:19:56 +0800 Subject: creating yaml without tags using pyyaml Message-ID: hello I have a situation where I have quite a large python object which I want to convert to yaml so I can then send it to a flex application using pyamf. I've managed to create a yaml document using the python object (http://flashbsm.googlecode.com/svn/testing/yamlTest/tester.yaml) (using pyyaml) however when I send the result of decoding the python object to yaml to the flex app, the flex app complains about expecting a block end, but not getting one. I have come to the conclusion that this is the fault of the tags (for example, !!python/tuple) as getting rid of them gets rid of the errors. So I'm wondering if there is an option to YAML.decode that will create a yaml document without the tags? Thankyou Regards Stephen From ram.rachum at gmail.com Sun Jun 15 15:10:16 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Sun, 15 Jun 2008 12:10:16 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> Message-ID: <7be098bd-7d14-44d0-ac69-0c5fb261d454@25g2000hsx.googlegroups.com> On Jun 15, 8:52?pm, Peter Otten <__pete... at web.de> wrote: > ram.rac... at gmail.com wrote: > > I have a physical system set up in which a body is supposed to > > accelerate and to get very close to lightspeed, while never really > > attaining it. After approx. 680 seconds, Python gets stuck and tells > > me the object has passed lightspeed. I put the same equations in > > Mathematica, again I get the same mistake around 680 seconds. So I > > think, I have a problem with my model! Then I pump up the > > WorkingPrecision in Mathematica to about 10. I run the same equations > > again, and it works! At least for the first 10,000 seconds, the object > > does not pass lightspeed. > > That the values are possible doesn't mean that you can trust them. > I do not understand this comment. > > I concluded that I need Python to work at a higher precision. > > How is WorkingPrecision defined? Python floats have about 16 significant > digits in base 10, so at first glance I would guess that you switched to > a /lower/ precision. > I don't know how WorkingPrecision is defined. However, I think it's not lower, it's higher. > But I've come to agree with Christian that it would be good to show your > model to a physics and/or numerical maths expert. Perhaps you can find a > way for the errors to cancel out rather than accumulate. I might try that. From boingy.boingy at gmail.com Wed Jun 25 17:37:41 2008 From: boingy.boingy at gmail.com (idiolect) Date: Wed, 25 Jun 2008 14:37:41 -0700 (PDT) Subject: Newbie question about tuples and list comprehensions Message-ID: Hi all - Sorry to plague you with another newbie question from a lurker. Hopefully, this will be simple. I have a list full of RGB pixel values read from an image. I want to test each RGB band value per pixel, and set it to something else if it meets or falls below a certain threshold - i.e., a Red value of 0 would be changed to 50. I've built my list by using a Python Image Library statement akin to the following: data = list(image.getdata()) Which produces a very long list that looks like [(0,150,175), (50,175,225),...]. I'm trying to figure out a fast and pythonic way to perform my operation. The closest I've come so far to a succinct statement is a list comprehension along the syntax of: source = [((x,y,z),(x+50,y+50,z+50))[bool(x or y or z < 50)] for (x,y,z) in source] ...which kind of approaches the effect I'm looking for, but it doesn't really test and change each value in the tuple individually. My understanding of the things you can do with lists and python in general is rather naive, so I would appreciate any insight anyone can offer since I am not sure if I'm even headed down the correct path with list comprehensions. Much obliged! From morton.thomas at googlemail.com Tue Jun 10 03:28:14 2008 From: morton.thomas at googlemail.com (Thomas Morton) Date: Tue, 10 Jun 2008 08:28:14 +0100 Subject: Getting current screen resolution References: Message-ID: <6FD81F1D7C2C4CBEAAA31E9D5174172C@ErrantGaming> Yeh that's not such an issue - this is for some basic image analysis for a document / report. It's not HUGELY important data (it can be wrong with no real come back) but it has to be roughly accurate... The idea is I have an image and I need to work out how big it displays on the monitor of the computer running the script :) Thanks for the replies so far ppl :) I think I might have it....... Tom -------------------------------------------------- From: "Larry Bates" Sent: Monday, June 09, 2008 11:16 PM Newsgroups: comp.lang.python To: Subject: Re: Getting current screen resolution > Thomas Morton wrote: >> This is a "thing" that has been annoying me all morning: and I can't >> work out how to do it. >> >> I need a way to get the DPI or screen resolution of the monitor that a >> script is currently runnign on. >> >> I have a way in Windows but it doesnt port to Unix (which is important). >> >> Any ideas? >> > > warning - be very careful about trying to come up with something like > this. > Today it is common for people to have more than one monitor, so you will > need to take that into account. Just getting resolution of one monitor > might not be enough (but then I don't know EXACTLY what is is that you are > doing with the > resolution). I see a lot of software that ignores the dual-monitor > possibility. > > -Larry > -- > http://mail.python.org/mailman/listinfo/python-list From google at mrabarnett.plus.com Thu Jun 12 21:20:09 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 12 Jun 2008 18:20:09 -0700 (PDT) Subject: Charset (hopefully for the last time I ask) References: Message-ID: On Jun 12, 8:04 pm, Gandalf wrote: > now I understand my problem better so their is a good chance you > manage to help me. > > I have a SQlite database full with ANSI Hebrew text , and program that > uses WXpython > Now, I use a- 'wx.TextCtrl' item to receive input from the user, and > when I try to search the database he don't understand this chars. > > it's quite reasonable consider the fact the program set to work on > UTF-8 charset, except for: > > 1. it doesn't work when I delete the charset too > > 2. when I try to use function like decode and encode it output error > like this: > ascii' codec can't encode characters in position 0-4: ordinal not in > range(128) > ascii' codec can't encode characters in position 0-2: ordinal not in > range(128) > > 3. I don't know how to translate my DB from ANSI to UTF-8 > > 4. when I don't use the user WX items input I can change my editor > charset to ansi and it works fine > > Thank you all Have you tried something like: unicode_text = text_from_db.decode("cp1255") print unicode_text utf8_text = unicode_text.encode("utf8") print utf8_text (I believe the codepage 1255 is Hebrew.) From basti.wiesner at gmx.net Tue Jun 10 07:26:59 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Tue, 10 Jun 2008 13:26:59 +0200 Subject: Python, subprocess, dump, gzip and Cron References: <484e0521$1@dnews.tpgi.com.au> <6870ff12-a1f3-419a-9a8e-62c02e33d118@l17g2000pri.googlegroups.com> <484e0f65$1@dnews.tpgi.com.au> Message-ID: Aidan at Dienstag 10 Juni 2008 07:21: > TT wrote: >> On Jun 10, 2:37 pm, Aidan wrote: >>> Hi, >>> >>> I'm having a bit of trouble with a python script I wrote, though I'm not >>> sure if it's related directly to python, or one of the other software >>> packages... >>> >>> The situation is that I'm trying to create a system backup script that >>> creates an image of the system, filters the output though gzip, and then >>> uploads the data (via ftp) to a remote site. >>> >>> The problem is that when I run the script from the command line, it >>> works as I expect it, but when it is run by cron I only get a 20 byte >>> file where the compressed image should be... does anyone have any idea >>> as to why this might be happening? Code follows >>> >>> >>> >>> #!/usr/bin/python >>> >>> from subprocess import PIPE, Popen >>> from ftplib import FTP >>> >>> host = 'box' >>> >>> filename = '%s.img.gz' % host >>> ftp_host = '192.168.1.250' >>> ftpuser, ftppass = 'admin', 'admin' >>> dest_dir = '/share/%s' % host >>> >>> dump = Popen('dump 0uaf - /',shell=True,stdout=PIPE) You should avoid the use of ``shell=True`` here and use a argument list instead: dump = Popen(['dump', '0uaf', '-', '/'], stdout=PIPE) This results in an exception thrown if the executable doesn't exist. This exception can be caught and handle for instance with the logging module. >>> gzip = Popen('gzip',shell=True,stdin=dump.stdout,stdout=PIPE) Same here, but why don't you use the gzip functionality from the standard library? -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From benjamin.kaplan at case.edu Mon Jun 9 23:10:17 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 9 Jun 2008 23:10:17 -0400 Subject: Odd behavior of python module listing In-Reply-To: <7bfeb431-ea2c-4fd1-8263-8f0d25159269@s33g2000pri.googlegroups.com> References: <7bfeb431-ea2c-4fd1-8263-8f0d25159269@s33g2000pri.googlegroups.com> Message-ID: On Mon, Jun 9, 2008 at 4:58 PM, Lie wrote: > Yesterday I installed compiz-icon in my Ubuntu. Today, when I go to > the python interpreter, I happen to do this: > > ### START OF PYTHON SESSION ### > Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> help() > > Welcome to Python 2.5! This is the online help utility. > > If this is your first time using Python, you should definitely check > out > the tutorial on the Internet at http://www.python.org/doc/tut/. > > Enter the name of any module, keyword, or topic to get help on writing > Python programs and using Python modules. To quit this help utility > and > return to the interpreter, just type "quit". > > To get a list of available modules, keywords, or topics, type > "modules", > "keywords", or "topics". Each module also comes with a one-line > summary > of what it does; to list the modules whose summaries contain a given > word > such as "spam", type "modules spam". > > help> modules > > Please wait a moment while I gather a list of all available modules... > > * Starting Compiz > ... executing: compiz.real --replace --sm-disable --ignore-desktop- > hints ccp > Starting gtk-window-decorator > compiz.real (video) - Warn: No 8 bit GLX pixmap format, disabling YV12 > image format > GConf backend: There is an unsupported value at path /apps/compiz/ > plugins/scale/allscreens/options/initiate_edge. Settings from this > path won't be read. Try to remove that value so that operation can > continue properly. > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/site.py", line 342, in __call__ > return pydoc.help(*args, **kwds) > File "/usr/lib/python2.5/pydoc.py", line 1649, in __call__ > self.interact() > File "/usr/lib/python2.5/pydoc.py", line 1667, in interact > self.help(request) > File "/usr/lib/python2.5/pydoc.py", line 1683, in help > elif request == 'modules': self.listmodules() > File "/usr/lib/python2.5/pydoc.py", line 1804, in listmodules > ModuleScanner().run(callback) > File "/usr/lib/python2.5/pydoc.py", line 1855, in run > for importer, modname, ispkg in pkgutil.walk_packages(): > File "/usr/lib/python2.5/pkgutil.py", line 125, in walk_packages > for item in walk_packages(path, name+'.', onerror): > File "/usr/lib/python2.5/pkgutil.py", line 110, in walk_packages > __import__(name) > File "/usr/lib/python2.5/site-packages/FusionIcon/interface_gtk/ > __init__.py", line 3, in > import main > File "/usr/lib/python2.5/site-packages/FusionIcon/interface_gtk/ > main.py", line 213, in > gtk.main() > KeyboardInterrupt > >>> > ### END OF PYTHON SESSION ### > > How on earth could python's help utility crashed compiz-icon, and made > compiz crash too (I lost my windows decoration after the crash). This > is repeatable, until I uninstalled compiz-icon. After uninstalling, I > retried help -> modules again, same problem, different program, now a > blank Tk window showed up and it printed this traceback: > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/site.py", line 342, in __call__ > return pydoc.help(*args, **kwds) > File "/usr/lib/python2.5/pydoc.py", line 1649, in __call__ > self.interact() > File "/usr/lib/python2.5/pydoc.py", line 1667, in interact > self.help(request) > File "/usr/lib/python2.5/pydoc.py", line 1683, in help > elif request == 'modules': self.listmodules() > File "/usr/lib/python2.5/pydoc.py", line 1804, in listmodules > ModuleScanner().run(callback) > File "/usr/lib/python2.5/pydoc.py", line 1855, in run > for importer, modname, ispkg in pkgutil.walk_packages(): > File "/usr/lib/python2.5/pkgutil.py", line 125, in walk_packages > for item in walk_packages(path, name+'.', onerror): > File "/usr/lib/python2.5/pkgutil.py", line 110, in walk_packages > __import__(name) > File "/usr/lib/python2.5/site-packages/OpenGL/Tk/__init__.py", line > 87, in > _default_root.tk.call('package', 'require', 'Togl') > _tkinter.TclError: can't find package Togl > > OK, I don't think I can uninstall Tk without messing up a lot of > harmless python programs later, and by now, I figured out that the > problem isn't in compiz-icon afterall. > > So, has anyone got something like this? > > PS: Ubuntu Hardy Heron (8.04) + Python 2.5.2 > -- The error appears to be in OpenGL. Maybe you should ask the Ubuntu people about it. > > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cokofreedom at gmail.com Wed Jun 18 06:32:48 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 18 Jun 2008 03:32:48 -0700 (PDT) Subject: dict order References: Message-ID: <4804032a-adef-4973-ae21-acc4ad2dce37@z72g2000hsb.googlegroups.com> On Jun 18, 11:22 am, Robert Bossy wrote: > Hi, > > I wish to know how two dict objects are compared. By browsing the > archives I gathered that the number of items are first compared, but if > the two dict objects have the same number of items, then the comparison > algorithm was not mentioned. > > Note that I'm not trying to rely on this order. I'm building a > domain-specific language where there's a data structure similar to > python dict and I need an source of inspiration for implementing > comparisons. > > Thanks > RB I'm a little confused as to what you want. Are you asking whether two dictionary objects have the same keys AND values, or just the Keys? As dictionaries are unordered the best technique is to go through one dictionary and take out a key, then see if that key exists in the other dictionary, and if so do they share the same values. # untested 2.5 for keys in dict_one.items(): if keys in dict_two: if dict_one[keys] != dict_two[keys]: # values are different else: # key is not present This probably isn't the most efficient way, but can quickly find differences... From nick at craig-wood.com Mon Jun 9 05:30:46 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 09 Jun 2008 04:30:46 -0500 Subject: time.clock() or Windows bug? References: <0uep44hpn8rupgr15a135f37q346tif9v2@4ax.com> Message-ID: Tim Roberts wrote: > Nick Craig-Wood wrote: > > > >time.clock() uses QueryPerformanceCounter under windows. There are > >some known problems with that (eg with Dual core AMD processors). > > > >See http://msdn.microsoft.com/en-us/library/ms644904.aspx > > > >And in particular > > > > On a multiprocessor computer, it should not matter which processor > > is called. However, you can get different results on different > > processors due to bugs in the basic input/output system (BIOS) or > > the hardware abstraction layer (HAL). To specify processor > > affinity for a thread, use the SetThreadAffinityMask function. > > That's an extremely arrogant statement on their part, because the fault > here is entirely within Windows. > > Through Windows 2000, the operating system actually synchronized the cycle > counters on the additional processors as they came out of reset at boot > time. (The cycle counter is, after all, a writable register.) As a > result, the cycle counters were rarely off by more than about 20 cycles. > > Beginning with XP, they stopped doing that. As a result, the cycle > counters on multiprocessor machines can vary by millions or even tens of > millions of cycles. Hmmm, 10,000,000 cycles (40 ms @2.5GHz) is nowhere near the ~90,000 second jump in time.clock() output reported by the OP. I wonder if there could be a different cause? -- Nick Craig-Wood -- http://www.craig-wood.com/nick From Wayne.Oosthuizen at gmail.com Sat Jun 14 09:34:43 2008 From: Wayne.Oosthuizen at gmail.com (Constantly Distracted) Date: Sat, 14 Jun 2008 06:34:43 -0700 (PDT) Subject: How do I sort items in a tableview without a column being selected? Message-ID: I have this TableView, which is sorted by column when the user clicks on the header. The problem is though, that all the items are selected and nothing gets sorted. But if the window loses focus everything's get's sorted. Basically I have list of tags say, [{"artist":"Artist1","title":Title1"} , {"artist":"Artist2" , "title": "Title2"}] etc. Where each tag is listed in a column. Then I sort them and reset. Here's the code: def sort(self,column,order=Qt.DescendingOrder): tag=self.headerdata.text newdic={} li=[] i=0 for z in self.taginfo: #taginfo has all the tags if not newdic.has_key(z[tag]): newdic[z[tag]]=z li.append(z[tag]) else: newdic[z[tag] + str(i)]=z li.append(z[tag] + str(i)) i+=1 li.sort() self.taginfo=[newdic[z] for z in li] self.reset() Any ideas? From cokofreedom at gmail.com Fri Jun 13 06:29:00 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Fri, 13 Jun 2008 03:29:00 -0700 (PDT) Subject: boolian logic References: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> Message-ID: <21cca7a7-6f83-4812-bbf5-d91a91fda297@r66g2000hsg.googlegroups.com> > > if var not in (A, B, C): > do_something() > And this is why I love python. From deets at nospam.web.de Wed Jun 18 10:29:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 18 Jun 2008 16:29:43 +0200 Subject: Looking for lots of words in lots of files References: Message-ID: <6bskfpF3d3v42U1@mid.uni-berlin.de> brad wrote: > Just wondering if anyone has ever solved this efficiently... not looking > for specific solutions tho... just ideas. > > I have one thousand words and one thousand files. I need to read the > files to see if some of the words are in the files. I can stop reading a > file once I find 10 of the words in it. It's easy for me to do this with > a few dozen words, but a thousand words is too large for an RE and too > inefficient to loop, etc. Any suggestions? Use an indexer, like lucene (available as pylucene) or a database that offers word-indices. Diez From matei.zaharia at gmail.com Sat Jun 28 18:29:06 2008 From: matei.zaharia at gmail.com (Matei Zaharia) Date: Sat, 28 Jun 2008 15:29:06 -0700 (PDT) Subject: Is there a sampling profiler for Python? Message-ID: I'm looking for a sampling profiler which I can attach to a running Python process without modifying the source code or affecting performance. So far I've only seen references to instrumentation-based profilers. Is any sampling-based tool available? From aisaac at american.edu Sun Jun 29 00:20:27 2008 From: aisaac at american.edu (Alan Isaac) Date: Sun, 29 Jun 2008 04:20:27 GMT Subject: Market simulations with Python In-Reply-To: <8288a0f3-6d0a-4c01-9cf0-295e3a95328a@m73g2000hsh.googlegroups.com> References: <8288a0f3-6d0a-4c01-9cf0-295e3a95328a@m73g2000hsh.googlegroups.com> Message-ID: xamdam wrote: > I am interested in market simulation with Python, simulating buyers > and sellers arriving with goods at random times. I looked at SimPy, > it's pretty nice, but all the examples are around congestion problems. > Should I a) dig deeper b) write something from scratch c) look at > another library? You could use SimPy. Also see: http://gnosis.cx/publish/programming/charming_python_b10.html http://www.mech.kuleuven.be/lce2006/147.pdf If you plan to share you efforts, please post updates here. Alan Isaac From toby at tobiah.org Thu Jun 5 15:24:55 2008 From: toby at tobiah.org (Tobiah) Date: Thu, 05 Jun 2008 12:24:55 -0700 Subject: Question regarding re module References: <9165ed46-4077-44a8-ae93-ceafda975f04@56g2000hsm.googlegroups.com> Message-ID: >> > It could be that the result overloads the __getattr__-method to delegate >> > calls to some object. Thus it's not part of the outer instance. >> > > Didn't I read that Py3 will support a __dir__ method so that classes > *could* report such pseudo-attributes in response to dir? > > -- Paul I don't believe that it possibly could: class foo(object): def __getattr__(self, what): if what[0] == 't': return True f = foo() print f.toby ** Posted from http://www.teranews.com ** From fuzzyman at gmail.com Mon Jun 30 18:15:00 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 30 Jun 2008 15:15:00 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: Message-ID: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > I don't want to be so mean here, but how hard it could be be writing a > freesoftware which would automatically/intelligently auto complete > Python code? (I mean something that really does the job, like > Microsoft's Visual Studio or Sun's NetBeans or something else, you > name it, but just don't give me PyDev please...) > > This could be an extension, a plugin, an Emacs mode, a new editor or > even a brand new huge all-fancy IDE, I don't care, but what am I > missing here? > > Could someone please point me out something that I'm really missing > which is already present in the wild, otherwise I'd like discuss with > whoever is willing to help me to get this thing done. I made my mind > and I could volunteer to make this happen as thesis project for my > incoming graduation in the next year. > > Regards you all, > Ali Servet D?nmez Vim, Emacs, Wing, Komodo, ... more? Yeah, I guess you're missing something. :-) Michael Foord http://www.ironpythoninaction.com/ http://www.trypython.org/ From toby at tobiah.org Tue Jun 3 17:57:20 2008 From: toby at tobiah.org (Tobiah) Date: Tue, 03 Jun 2008 14:57:20 -0700 Subject: Keep a script running in the background References: <210b7fc6-ed52-461d-8b53-455e247d7a29@e39g2000hsf.googlegroups.com> Message-ID: > I need a script to keep running in the background after it's loaded > some data. It will make this data available to the main program in the > form of a dictionary, but I don't want to reload the calculated data > every time the user needs it via the main program. If it were me, I'd go with a database server like mysql. ** Posted from http://www.teranews.com ** From ErendisAldarion at gmail.com Sun Jun 1 19:54:41 2008 From: ErendisAldarion at gmail.com (Aldarion) Date: Sun, 1 Jun 2008 16:54:41 -0700 (PDT) Subject: a question about the #prefix of sys.argv Message-ID: for the little script #egg.py import sys for k,v in enumerate(sys.argv): print k,v it ignores the part after # on linux below is the running output on windows and linux. no clue here. D:\python\note>egg.py #test 0 D:\python\note\egg.py 1 #test D:\python\note>egg.py for bar #spam egg 0 D:\python\note\egg.py 1 for 2 bar 3 #spam 4 egg ddd at bbb:~/transfer$ python2.5 egg.py #test 0 egg.py ddd at bbb:~/transfer$ python2.5 egg.py foo bar #spam egg 0 egg.py 1 foo 2 bar From circularfunc at yahoo.se Wed Jun 11 23:07:26 2008 From: circularfunc at yahoo.se (cirfu) Date: Wed, 11 Jun 2008 20:07:26 -0700 (PDT) Subject: catastrophic regexp, help! References: <26bda6a4-ad16-4b06-aff4-12e311ebaf81@59g2000hsb.googlegroups.com> Message-ID: On 11 Juni, 10:25, Chris wrote: > On Jun 11, 6:20 am, cirfu wrote: > > > pat = re.compile("(\w* *)*") > > this matches all sentences. > > if fed the string "are you crazy? i am" it will return "are you > > crazy". > > > i want to find a in a big string a sentence containing Zlatan > > Ibrahimovic and some other text. > > ie return the first sentence containing the name Zlatan Ibrahimovic. > > > patzln = re.compile("(\w* *)* zlatan ibrahimovic (\w* *)*") > > should do this according to regexcoach but it seems to send my > > computer into 100%CPU-power and not closable. > > Maybe something like this would be of use... > > def sentence_locator(s, sub): > cnt = s.upper().count(sub.upper()) > if not cnt: > return None > tmp = [] > idx = -1 > while cnt: > idx = s.upper().find(sub.upper(), (idx+1)) > a = -1 > while True: > b = s.find('.', (a+1), idx) > if b == -1: > b = s.find('.', idx) > if b == -1: > tmp.append(s[a+1:]) > break > tmp.append(s[a+1:b+1]) > break > a = b > cnt -= 1 > return tmp yes, seems very unpythonic though :) must be a simpler way that isnt slow as hell. From tjreedy at udel.edu Fri Jun 6 02:44:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 6 Jun 2008 02:44:52 -0400 Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> Message-ID: "Mensanator" wrote in message news:bbd90051-36be-4378-9a27-2a47a5471d12 at a1g2000hsb.googlegroups.com... | On Jun 5, 10:42?pm, John Salerno wrote: | > Is it possible to write a list comprehension for this so as to produce a | > list of two-item tuples? | > | > base_scores = range(8, 19) | > score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] | > print zip(base_scores, score_costs) | > | > I can't think of how the structure of the list comprehension would work | > in this case, because it seems to require iteration over two separate | > sequences to produce each item in the tuple. Which is exactly the purpose of zip, or its specialization enumerate! | > zip seems to work fine anyway, but my immediate instinct was to try a | > list comprehension (until I couldn't figure out how!). And I wasn't sure | > if list comps were capable of doing everything a zip could do. | | base_scores = range(8, 19) | score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] | print zip(base_scores, score_costs) | | s = [(i+8,j) for i,j in enumerate( [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3])] | print s | | ##>>> | ##[(8, 0), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, | 2), (16, 2), (17, 3), (18, 3)] | ##[(8, 0), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, | 2), (16, 2), (17, 3), (18, 3)] | ##>>> Of course, enumerate(iterable) is just a facade over zip(itertools.count(), iterable) From carbonimax at gmail.com Fri Jun 20 11:04:57 2008 From: carbonimax at gmail.com (Carbonimax) Date: Fri, 20 Jun 2008 08:04:57 -0700 (PDT) Subject: py2exe, PyQT, QtWebKit and jpeg problem Message-ID: hello I have a problem with py2exe and QtWebKit : I make a program with a QtWebKit view. If I launch the .py directly, all images (jpg, png) are displayed but if I compile it with py2exe I have only png images. No jpg ! No error message, nothing. Have you a solution ? Thank you. From chardish at gmail.com Tue Jun 10 11:47:25 2008 From: chardish at gmail.com (chardish at gmail.com) Date: Tue, 10 Jun 2008 08:47:25 -0700 (PDT) Subject: Instructions on how to build py2exe 0.6.8 (or an installer would be nice, too!) References: <5426baaf-2ba6-41b0-a0ec-1070429b5195@x35g2000hsb.googlegroups.com> Message-ID: <7f3360e4-8a12-45cf-99fa-6172cb5a1aaa@a1g2000hsb.googlegroups.com> On Jun 10, 11:34?am, Mike Driscoll wrote: > Maybe I'm missing something, but I can rename the executables I create > using py2exe 0.6.6 to anything I want after they're created. > > Or are you talking about a Windows installer for the py2exe module > itself? Where are you finding this 0.6.8 version anyway? I can't find > it onwww.py2exe.org > > Anyway, what Thomas is talking about is that the only way to create a > usable installer of py2exe on Windows is to use the same compiler that > the Python you are using. As I understand it, Python 2.4 and 2.5 used > Visual Studio 2003. I think 2.3 used VS6. I have both, so I can try to > compile an installer for any of those versions if you can link me to > the source. > > Mike > > Python Extension Building Network: ? ? http:\\www.pythonlibrary.org The issue with renaming executables only applies to single-file executables, i.e. ones created with zipfile = None as an argument to setup() and --bundle 1 as a command line argument. This is a known issue as of 0.6.6: http://py2exe.org/index.cgi/ProblemsToBeFixed I found sources for 0.6.8 on CVS at: http://sourceforge.net/cvs/?group_id=15583 A Windows installer for the 0.6.8 py2exe module would be ideal, but somehow I doubt that's going to happen anytime soon since there hasn't been a new installer since 2006. If you are willing to build that for me (since I don't have VS) I'd really appreciate it : ) I'm using 32- bit WinXP on this computer. From larry.bates at websafe.com` Mon Jun 23 23:36:45 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 23 Jun 2008 22:36:45 -0500 Subject: 32-bit python memory limits? In-Reply-To: References: Message-ID: Gary Robinson wrote: > I'm running a Python job on OS X 10.5.3 and the Python 2.5.2 that's available as a binary download at python.org for OS X. > > I ran a python program tonight that ended up using much more memory than anticipated. It just kept on using more and more memory. Instead of killing it, I just watched it, using Activity Monitor. I assumed that when it had 2GB allocated it would blow up, because I thought 32-bit python could only address 2GB. > > But Activity Monitor reported that it had allocated 3.99GB of virtual memory before it finally blew up with malloc errors. Was my understanding of a 2GB limit wrong? I guess so! But I'm pretty sure I saw it max out at 2GB on linux... > > Anybody have an explanation, or is it just that my understanding of a 2GB limit was wrong? Or was it perhaps right for earlier versions, or on linux...?? > > Thanks for any thoughts, > Gary > > Yep, 2Gb is only 31 bits. 4Gb is 32 bits (since memory address is an unsigned). -Larry From cmoney62 at gmail.com Wed Jun 18 20:56:50 2008 From: cmoney62 at gmail.com (cmoney62 at gmail.com) Date: Wed, 18 Jun 2008 17:56:50 -0700 (PDT) Subject: FREE YOUR HOME BUSINESS EARN 150 US $$ PER DAY. Message-ID: <88f0c3ba-46e1-4b30-a61d-482e5ecf339a@t12g2000prg.googlegroups.com> FREE YOUR HOME BUSINESS EARN 150 US $$ PER DAY http://govindswamy-govindaswamy.blogspot.com http://kavigovindan.blogspot.com http://govindaswamy-amman.blogspot.com http://govindaswamy10.blogspot.com From grante at visi.com Sat Jun 14 15:15:46 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 14 Jun 2008 14:15:46 -0500 Subject: Making wxPython a standard module? References: <6bidd7F3bg8usU1@mid.uni-berlin.de> Message-ID: On 2008-06-14, Diez B. Roggisch wrote: >>> And on a personal note: I find it *buttugly*. >> >> Do you mind explaining "why" you find it *buttugly*? [...] > For the curious: Not the look & feel (albeit I prefer KDE on > linux over Gnome, which is a Qt/GTK thing and thus affects wx > look & feel as well), but the code & the designers. I've never used any of the designers, but I agree 100% that wxPython code is nasty ugly. wxPython has a very un-Pythonic API that's is, IMO, difficult to use. The API isn't really Robin Dunn's fault: wxPython is a very thin wrapper around wxWidgets, so it largely retains the same nasty low-level C++ API that wxWidgets has. I presume much of wxPython is generated in some automated fasion (a la swing). There have been a couple attempts to wrap wxPython in a cleaner, more Pythonic API, but they've have limited success (wax is the one I can think of off the top of my head). -- Grant Edwards grante Yow! If I had a Q-TIP, I at could prevent th' collapse visi.com of NEGOTIATIONS!! From jgardner at jonathangardner.net Wed Jun 18 11:55:23 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Wed, 18 Jun 2008 08:55:23 -0700 (PDT) Subject: go to specific line in text file References: <1xsmb1wlk1554$.gey53bzk6vfd$.dlg@40tude.net> Message-ID: <5bff9d86-805f-49da-a90c-479a936e130d@r37g2000prm.googlegroups.com> On Jun 17, 3:10?am, Patrick David wrote: > > I am searching for a way to jump to a specific line in a text file, let's > say to line no. 9000. > Is there any method like file.seek() which leads me to a given line instead > of a given byte? > As others have said, no. But if you're wondering how other file formats do this, like BDB or PostgreSQL data files, which absolutely have to jump to the magical spot in the file where the data is, they keep an index at the beginning of the file that points to what byte the data they are looking for is in. So if it's really important to be able to do this, consider that. From evidentemente.yo at gmail.com Wed Jun 25 06:54:34 2008 From: evidentemente.yo at gmail.com (evidentemente.yo) Date: Wed, 25 Jun 2008 03:54:34 -0700 (PDT) Subject: calling a .exe from Python References: Message-ID: <13513ef3-f05c-4749-a8d8-d918abf1d928@z72g2000hsb.googlegroups.com> Thank you for the help!!!:) On 25 jun, 10:32, Nick Craig-Wood wrote: > evidentemente.yo wrote: > > ?On 24 jun, 14:32, Nick Craig-Wood wrote: > > > Probably what you want is this... > > > > from subprocess import call > > > > rc = call(["mypath/myfile.exe",arg1,arg2]) > > > > rc will contain the exit status > > > > See the subprocess module for more things you can do > > > ?Hey, thank you very much!!!:D > > > ?Would it matter if my .exe doesn't return any value? would it return > > ?like an "ok" or something??? > > Your exe will return a value (it is part of the OS) but you can ignore > it if you want. ?Just use > > call(["mypath/myfile.exe",arg1,arg2]) > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick From d3vvnull at gmail.com Thu Jun 5 07:35:39 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Thu, 5 Jun 2008 06:35:39 -0500 Subject: Squeak-like environment for Python? In-Reply-To: <4847c90a$0$6005$426a74cc@news.free.fr> References: <0001HW.C46D717900E84E0DB01AD9AF@news.individual.de> <6apod7F387g23U1@mid.uni-berlin.de> <4847c90a$0$6005$426a74cc@news.free.fr> Message-ID: <170543c70806050435u1d0a0f92tea29df7fa83af603@mail.gmail.com> Check out the Brainwave platform, which uses a new "neural" database model. It allows you to create databases to store any kind of Python object as a "neuron" and allows objects to be connected via link to create complex structures that don't require conventional tables and columns. It is a development platform that has a bundled webserver based on CherryPy, with a built-in application generator and deployer. http://www.brainwavelive.com On Thu, Jun 5, 2008 at 6:08 AM, Bruno Desthuilliers wrote: > Diez B. Roggisch a ?crit : > > Jumping Arne wrote: >> >> I've been playing with Squeak a bit and I really like the persistent >>> storage model, I also liked HyperCard and Frontier (well, the persistent >>> storage model at least). >>> >>> I wonder if there is some similar environment but based on python, I >>> would >>> like to use this environment not as a development environment but as a >>> platform for storing data etc - much like HyperCard. >>> >>> I found a few postings about such an environment: >>> >>> >>> >>> but it looks like nothing happened. >>> >>> pythoncard doesn't seem to have the persistent storage model >>> >> >> What about ZODB? You can use that to store (more or less) arbitrary >> objects. >> Maybe that can be a foundation, if you throw in >> http://nodebox.net/code/index.php/Home >> >> it might be similar to squeak (I only dimly remember what squeak as a >> whole >> is though - smalltalk & easy multimedia I remember) >> > > Mainly, Squeak is a (relatively) recent, free implementation of Smalltalk. > > > The "persistent storage model" - the 'image' storing the whole system > (code, libs, data, whatever) - is part of the Smalltalk system since it's > first conception IIRC (even if some Smalltalk implementations - like GNU > Smalltalk - are more traditionnaly file-based and have no automatic > persistence). > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Mon Jun 16 10:54:19 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 16 Jun 2008 09:54:19 -0500 Subject: PEP 372 -- Adding an ordered directory to collections In-Reply-To: <48567688.7030306@ncee.net> References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <8ec4632c-2cae-40d1-ba5d-8d88854dae52@m73g2000hsh.googlegroups.com> <48567688.7030306@ncee.net> Message-ID: <1C14ED51B41947678D719807320547FD@AWA2> :) Yes, I thought about that even as I was writing that post. But I also said, "ParseResults implements quite a bit of additional behavior that would not be required or necessarily appropriate for odict." Even if odict existed, I think I would have needed ParseResults anyway (but using an odict internally might have simplified things for me, instead of the combined list and dict that I have now). -- Paul -----Original Message----- From: Shane Geiger [mailto:sgeiger at ncee.net] Sent: Monday, June 16, 2008 9:20 AM To: Paul McGuire Cc: python-list at python.org Subject: Re: PEP 372 -- Adding an ordered directory to collections Paul, You seem to be contradicting yourself. You may have never needed an odict, yet you seem to have implemented one on your own. Maybe you needed one but did not realize it? Shane > 5. The more I think and write about this, the more struck I am at the > similarity of odict and the ParseResults class in pyparsing. For > instance, in ParseResults, there is also support for dict-style and > list-style item referencing, and I chose to restrict some cases so > that using [] notation would not be ambiguous. You might want to add > pyparsing.ParseResults as another reference of current "odicts in the > wild" (although ParseResults implements quite a bit of additional > behavior that would not be required or necessarily appropriate for > odict). > > I vote +0 on this PEP - I've never personally needed an odict, but I > can see how some of the XML and ORM coding would be simplified by one. > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From http Tue Jun 3 04:57:11 2008 From: http (Paul Rubin) Date: 03 Jun 2008 01:57:11 -0700 Subject: Code correctness, and testing strategies References: Message-ID: <7x1w3esxp4.fsf@ruckus.brouhaha.com> Duncan Booth writes: > I made the mistake at one point when I was trying to sell the concept of > TDD telling the people I was trying to persuade that by writing the tests > up front it influences the design of the code. I felt the room go cold: > they said the customer has to sign off the design before we start coding, > and once they've signed it off we can't change anything. Usually the customer signs off on a functional specification but that has nothing to do with the coding style. Jacob makes a very good point that TDD influences coding style, for example by giving a strong motivation to separate computational code from I/O. But that is independent of the external behavior that the customer cares about. From rdh at new.rr.com Wed Jun 4 17:30:19 2008 From: rdh at new.rr.com (DataSmash) Date: Wed, 4 Jun 2008 14:30:19 -0700 (PDT) Subject: readline() & seek() ??? Message-ID: <12655f64-33b1-4ab0-b6fb-294bfd2fa8c6@d45g2000hsc.googlegroups.com> Hi group, I have a text file that contains thousands of lines and each line is 256 characters long. This is my task: For each line in the file, move to the 25th character, if the character is a "T", move to the 35th character of the line and read 5 characters from there. Capture these 5 characters and write them to a new text file, each 5 characters separated by a comma. I appreciate your help! R.D. From jason.scheirer at gmail.com Fri Jun 27 17:52:07 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Fri, 27 Jun 2008 14:52:07 -0700 (PDT) Subject: "method involving two objects" is that possible in Python? References: <8c8aec73-bd5b-4dfc-b91a-b100f3b9ddfa@m73g2000hsh.googlegroups.com> Message-ID: <075efde4-4f3b-48d1-a97f-fe068a2b81fb@j1g2000prb.googlegroups.com> On Jun 27, 2:41?pm, Kurda Yon wrote: > Hi, > > I just started to learn Python. I understood how one can create a > class and define a method related with that class. According to my > understanding every call of a methods is related with a specific > object. For example, we have a method "length", than we call this > method as the following "x.length()" or "y.length()" or "z.length()", > where z, y, and z are objects of the class. > > I am wandering if it is possible to create a method which is related > not with a single object (as in the previous example) but with a pare > of objects. For example, I want to have a class for vectors, and I > want to have a methods which calculate a dot product of two vectors. > One of the possibilities is to use __mul__ and that I calculated dot > product of "x" and "y" just as "x * y". However, I am wandering if I > can declare a method in a way that allows me to calculate dot product > as "dot(x,y)". > > Thank you in advance. def dot(x, y): ... class Vector: __mul__ = dot or class Vector: def __mul__(x, y): return dot(x, y) You can refer to the function defined as dot, assuming dot(x, y) returns some vector z. The first argument (x) will be bound to self in either case in any Vector instance. From dusan.smitran at gmail.com Wed Jun 11 08:40:03 2008 From: dusan.smitran at gmail.com (dusans) Date: Wed, 11 Jun 2008 05:40:03 -0700 (PDT) Subject: Dynamic HTML from Python Script References: <484f151c$0$5009$607ed4bc@cv.net> Message-ID: <96a4f695-d0ec-435d-9db1-849acdc0f9ab@p25g2000hsf.googlegroups.com> On Jun 11, 1:58 am, asdf wrote: > I have a python script whose output i want to dynamically display > on a webpage which will be hosted using Apache. How do I do that? > > thanks def index(req): return "Page" u cant run it on lighttpd also, which is much faster then Apache :P From rhamph at gmail.com Mon Jun 9 21:03:58 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 9 Jun 2008 18:03:58 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <6e6df35e-e641-44d9-9f56-c0732306eec2@q27g2000prf.googlegroups.com> Message-ID: <13db98b5-ed2e-45ef-97ec-ad3caeeed10e@j1g2000prb.googlegroups.com> On Jun 9, 2:52 pm, Fuzzyman wrote: > On Jun 9, 9:20 pm, Rhamphoryncus wrote: > > > > > On Jun 9, 5:33 am, Antoon Pardon wrote: > > > > On 2008-06-07, Rhamphoryncus wrote: > > > > > On Jun 6, 12:44 pm, The Pythonista wrote: > > > >> It's always been my understanding that you can't forcibly kill a thread > > > >> in Python (at least not in a portable way). The best you can do is > > > >> politely ask it to die, IIRC. > > > > > Inherently, the best you can do in most languages is ask them politely > > > > to die. Otherwise you'll leave locks and various other datastructures > > > > in an inconvenient state, which is too complex to handle correctly. > > > > The exception is certain functional languages, which aren't capable of > > > > having threads and complex state in the same sense. > > > > Well it would of course depend on what is considered asking politely? > > > > If one thread could cause an exception being thrown in an other thread, > > > would this be considered a polite way to ask? Would it be considered > > > an acceptable way? > > > The exception must not be raised until a point explicitly designed as > > safe is hit. Otherwise, any function that manipulates data you'll > > still use will potentially be buggered. Consider sys.stdout: codecs, > > buffering, lots to go wrong. > > Java and .NET both have ways of killing threads. They both work by > raising a 'ThreadAbort' (or similar) exception in the target thread. > In early implementations they both suffered from a similar problem. > You could protect locks (etc) by having a finally block that would > release all resources as needed - but what happens if the thread abort > exception is raised *inside* the finally block? > > Java responded by deprecating thread aborting. .NET responded by > ensuring that a thread abort exception would never be raised inside a > finally block - if that happened the exception would only be raised > once the code has left the finally block. > > Aborting threads in .NET can be extremely useful. Politely asking a > thread to die is no good if the task the thread is executing is > extremely coarse grained - it may not be able to respond to the > request for some time. If your code is structured correctly > (performing a long running background calculation for example) then > you may *know* that you can kill it without problems, but Python has > no native API to do this. So how does .NET deal with the sys.stdout corruption? Does it? If you've carefully written your code to use only safe primitives and local state (discarded if interrupted) then yes, it could be interruptible. At this point you could specially mark that block of code as safe, leaving the vast majority of other code unsafe by default. Then again, since you're going to the trouble of carefully designing and auditing your code you could just make it cancellable like blocking I/O should be - just by polling a flag at key points (and you're CPU-bound anyway, so it's not expensive.) The only place I know of that you *need* arbitrary interruption is hitting CTRL-C in the interactive interpreter. At this point it's a debugging tool though, so the risk of weirdness is acceptable. From hdante at gmail.com Sun Jun 1 14:27:26 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Sun, 1 Jun 2008 11:27:26 -0700 (PDT) Subject: SPOJ, Problem Code: sumtrian, Reducing time taken to solve. References: Message-ID: <6ae81d02-af69-40f5-835e-87f03ead8051@k30g2000hse.googlegroups.com> On Jun 1, 10:25?am, Shriphani wrote: > Hi, > > I was trying to solve the sumtrian problem in the SPOJ problem set > (https://www.spoj.pl/problems/SUMTRIAN/) and this is the solution I > submitted:http://pastebin.ca/1035867 > > The result was, "Your solution from 2008-06-01 15:13:06 to problem > SUMTRIAN, written in Python, > has exceeded the allowed time limit." > > I suspect that the first portion of my solution which looks at the > input, figures out the number of triangles and forms a list that > contains lists containing each row of the triangle, is wrong. I am not > too sure how to optimize it. I would appreciate help. > > Thanks, > Shriphani Palakodety First, you have to write a correct algorithm. Notice that your code doesn't correctly calculates the given sample input. Later, think about optimization. From hat at se-162.se.wtb.tue.nl Wed Jun 25 07:08:30 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 25 Jun 2008 13:08:30 +0200 Subject: python -regular expression - list element References: <62e21ec1-18f3-4572-b223-1b8a5c40688c@f63g2000hsf.googlegroups.com> Message-ID: On 2008-06-25, antar2 wrote: > I am a beginner in Python and am not able to use a list element for > regular expression, substitutions. > > list1 = [ 'a', 'o' ] > list2 = ['star', 'day', 'work', 'hello'] > > Suppose that I want to substitute the vowels from list2 that are in > list1, into for example 'u'. > In my substitution, I should use the elements in list1 as a variable. I read this as: for each string in list1, search (and replace with 'u') the matching substrings of each string in list2. Since list1 contains only strings instead of regular expressions, you could use string search and replace here. This makes matters much simpler. > I thought about: > > for x in list1: > re.compile(x) re.compile() returns a compiled version of the RE x. Above you don't save that value. Ie you do something similar to 1 + 2 * 3 where the value 7 is computed but not saved (and thus immediately discarded after computing by the Python interpreter). Use something like compiled_x = re.compile(x) instead. 'compiled_x' is assigned the computed compiled version of string x now. > for y in list2: > re.compile(y) The RE module finds matches in strings, not in compiled RE expressions. Since you want to search through y, it has to be a string. > if x in y: Here you test whether the letter in x occurs in y (both x and y are not changed by the re.compile() call, since that function does not alter its arguments, and instead produces a new result that you do not save). Maybe you thought you were checking whether a RE pattern match would occur. If so, it is not useful. Testing for a match takes about the same amount of time as doing the replacement. > z = re.sub(x, 'u', y) > but this does not work Instead of "re.sub(x, 'u', y)" you should use "compiled_x.sub('u', y)" since the former repeats the computation you already did with the re.compile(x). Otherwise, the code does work, and the new string (with replacements) is saved in "z". However, since you don't save that new value, it gets lost (overwritten). You should save "z" in the original list, or (recommended) create a new list with replaced values, and replace list2 after the loop. Sincerely, Albert From mr.opus.penguin at gmail.com Fri Jun 13 17:04:06 2008 From: mr.opus.penguin at gmail.com (mr.opus.penguin at gmail.com) Date: Fri, 13 Jun 2008 14:04:06 -0700 (PDT) Subject: Python 3000 vs. Python 2.x Message-ID: <2c299cdc-adcd-4540-b09f-43b4147e10ca@y21g2000hsf.googlegroups.com> As a new comer to Python I was wondering which is the best to start learning. I've read that a number of significant features have changed between the two versions. Yet, the majority of Python programs out in the world are 2.x and it would be nice to understand those as well. Thanks for all the help. Creosote, From geonomica at gmail.com Mon Jun 30 13:35:20 2008 From: geonomica at gmail.com (gianluca) Date: Mon, 30 Jun 2008 10:35:20 -0700 (PDT) Subject: ctypes - swig - pointer References: Message-ID: <58461c91-ed11-4153-8d74-429353e4fdd1@z72g2000hsb.googlegroups.com> On 30 Giu, 18:26, Jean-Paul Calderone wrote: > On Mon, 30 Jun 2008 09:13:42 -0700 (PDT), gianluca wrote: > >I've a problem with dll function colled with python/ctypes. My > >functions (C) requred a typedef int "value_type" in tree different > >way: > >same as value_type; - mydll.foo1(value_type) > >same as *value_type; - mydll.foo2(*value_type) > >same as **value_type; - mydll.foo3(**value_type) > > >How can pass it in python. If i do that: > >rules=POINTER(value_type) > >opr=rsl.StrengthOfRules(rules,10) > >R=POINTER(rules) > > POINTER takes a class and returns a new class which represents a pointer > to input class. > > pointer takes an instance and returns a new object which represents a > pointer to that instance. > > Jean-Paul so, if I write this: p=pointer(value_type) mydll.foo1(p) could be correct but python say me: TypeError: _type_ must have storage info what does mean? thank you gima From python at rgbaz.eu Mon Jun 16 03:49:00 2008 From: python at rgbaz.eu (Python.Arno) Date: Mon, 16 Jun 2008 09:49:00 +0200 Subject: Combining music or video files? In-Reply-To: <35e3302b-ba01-49b9-ac7a-0c6cc0df5f26@l28g2000prd.googlegroups.com> References: <4855d5a5$0$11609$607ed4bc@cv.net> <35e3302b-ba01-49b9-ac7a-0c6cc0df5f26@l28g2000prd.googlegroups.com> Message-ID: <8E9702DC-1F3E-44D1-9EDC-7949C5AF4301@rgbaz.eu> On 16 jun 2008, at 05:55, Jason Scheirer wrote: > On Jun 15, 7:53 pm, John Salerno wrote: >> Before I try this and destroy my computer :) I just wanted to see if >> this would even work at all. Is it possible to read a binary file >> such >> as an mp3 or an avi, put its contents into a new file, then read >> another >> such file and append its contents to this same new file as well, >> thereby >> making, for example, a single long video instead of two smaller ones? >> >> Thanks. > > This works with basic mpeg videos, but pretty much nothing else. > You're going to need some video editing software. you can't just edit mpeg (including mp3)... mpeg is a stream. it sets a "key" frame for the first frame followed by motion vectors from the changes from that frame until the next keyframe. If you cut in the middle of the vectors the keyframe is lost and the vector frames don;t make any sense anymore. avi is not a video codec, it's a container like quicktime. so it depends... I come from a Mac background and use quicktime a lot. there are some basic editing features that quicktime can do. And Apple has a nice quicktime python module in OSX. I bet there's something for windows too... best thing to do is convert the video o a framesequence and the audio to an uncompressed format like wav or aiff then combine in quicktime or cheers, Arno From gagsl-py2 at yahoo.com.ar Fri Jun 13 05:23:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Jun 2008 06:23:17 -0300 Subject: why can i still able to reproduce the SimpleHTTPServer bug which is said fixed 3 years ago? References: <4e307e0f0806130002u6795c55ejce02b71753df33ae@mail.gmail.com> Message-ID: En Fri, 13 Jun 2008 04:02:48 -0300, Leo Jay escribi?: > http://bugs.python.org/issue1097597 > > in my python 2.5.2, i still find these code in SimpleHTTPServer.py, > is that deliberate? According to http://bugs.python.org/issue839496 it should have been corrected, but apparently the patch was only applied to the 2.4 maintenance branch, not to the trunk. Both 2.5 and 2.6 have the same problem. 3.0 doesn't have this problem but probably it was fixed independently. -- Gabriel Genellina From wizzardx at gmail.com Sun Jun 1 06:46:28 2008 From: wizzardx at gmail.com (David) Date: Sun, 1 Jun 2008 12:46:28 +0200 Subject: method-wrapper? In-Reply-To: <597ecdea-bd88-429c-8b64-03efd4fb0d93@z72g2000hsb.googlegroups.com> References: <597ecdea-bd88-429c-8b64-03efd4fb0d93@z72g2000hsb.googlegroups.com> Message-ID: <18c1e6480806010346l36a8fb37y7cc0b4b67309770f@mail.gmail.com> > What is "method-wrapper"? Google turns up hardly any hits, same with > searching python.org. > It probably means that one object (A) contains another object (B). When you call certain methods on object A, those methods call methods in B, and return B's results to A's caller. >From that docstring: A.__call__() will run B() A.__cmp__(C) will run cmp(B, C) etc. In other words python code which runs A() will be running the equivalent of A.B(), where A can do other things besides calling B() if it wants to. David. From kay.schluehr at gmx.net Tue Jun 24 12:35:11 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 24 Jun 2008 09:35:11 -0700 (PDT) Subject: Python 3000 vs Perl 6 References: <89fbe834-68b7-49e6-8136-62dee53c2f40@t54g2000hsg.googlegroups.com> <7bad9ebd-81ab-48c4-854b-05f085e9d936@27g2000hsf.googlegroups.com> Message-ID: On 24 Jun., 13:19, bearophileH... at lycos.com wrote: > If you want to see an advanced language, you may take a look at > PyMeta, that's a bit of the future of the computer science:http://washort.twistedmatrix.com/ Er, no. The future of CS is also its past i.e. EBNF ;) From svasulu2 at gmail.com Sat Jun 28 02:59:00 2008 From: svasulu2 at gmail.com (chinu) Date: Fri, 27 Jun 2008 23:59:00 -0700 (PDT) Subject: EARN 10000$ IN EVERY MONTH ONLY DOING ONLINE JOB. Message-ID: <48009582-f78b-472e-8e07-12222b7c2ad0@i18g2000prn.googlegroups.com> GET + 1000$$$ @ MANY CASH OFFERS & ENJOY!!!!! Open the Site & Click the Banners = Easy forex + Get Web Hosting-Free Domains-Dating sites etc. site name: http://earnincomeblogspotcom.blogspot.com/ From mdw at distorted.org.uk Mon Jun 23 13:57:35 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Mon, 23 Jun 2008 17:57:35 +0000 (UTC) Subject: Using Python to run SSH commands on a remote server References: <03a078c8$0$3229$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Generally speaking, what tools would I use to do this? Is there a built-in > module for it? There's paramiko (q.g.). I can't personally vouch for it, but it seems popular... It seems to depend on a separate crypto library. > Is Telnet and SSH even the same thing? No. They're very different. -- [mdw] From geoff.bache at jeppesen.com Fri Jun 27 02:50:46 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Thu, 26 Jun 2008 23:50:46 -0700 (PDT) Subject: Windows process ownership trouble References: <3fcf363f-3685-4b7b-8ba5-1ffc32e58af7@m44g2000hsc.googlegroups.com> <990516b7-f7ef-464a-97d0-fd55a0354ab4@y21g2000hsf.googlegroups.com> <33847c9a-a816-48a1-a8c9-4209db9bf0b5@e53g2000hsa.googlegroups.com> <4863D586.8030004@timgolden.me.uk> Message-ID: <33aec7a9-b241-4bdd-8975-77759b2dc8b5@z66g2000hsc.googlegroups.com> Tim, I copied your code exactly from my browser and ran it, so I don't think there was a typo. I could upgrade to Python 2.5.2 I suppose to compare and contrast, but I need to support older Python versions anyway so it's a bit academic... Your speculation about garbage collection did set me going, however, and I discovered that the following code does work on my system, so now I have a functional workaround: import os import subprocess def runProcess(): f = open ("filename", "w") try: proc = subprocess.Popen ("blah", stdout=f) except OSError: f.close () runProcess() os.remove ("filename") So it seems that some things are only being garbage collected when the function exits, but not when the except clause exits or when the exception is thrown. Geoff From dullrich at sprynet.com Wed Jun 4 13:24:33 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Wed, 04 Jun 2008 12:24:33 -0500 Subject: re References: <6anvi4F38ei08U1@mid.uni-berlin.de> Message-ID: In article <6anvi4F38ei08U1 at mid.uni-berlin.de>, "Diez B. Roggisch" wrote: > David C. Ullrich schrieb: > > Actually using regular expressions for the first > > time. Is there something that allows you to take the > > union of two character sets, or append a character to > > a character set? > > > > Say I want to replace 'disc' with 'disk', but only > > when 'disc' is a complete word (don't want to change > > 'discuss' to 'diskuss'.) The following seems almost > > right: > > > > [^a-zA-Z])disc[^a-zA-Z] > > > > The problem is that that doesn't match if 'disc' is at > > the start or end of the string. Of course I could just > > combine a few re's with |, but it seems like there should > > (or might?) be a way to simply append a \A to the first > > [^a-zA-Z] and a \Z to the second. > > Why not > > ($|[\w])disc(^|[^\w]) > > I hope \w is really the literal for whitespace - might be something > different, see the docs. Thanks, but I don't follow that at all. Whitespace is actually \s. But [\s]disc[whatever] doesn't do the job - then it won't match "(disc)", which counts as "disc appearing as a full word. Also I think you have ^ and $ backwards, and there's a ^ I don't understand. I _think_ that a correct version of what you're suggesting would be (^|[^a-zA-Z])disc($|[^a-zA-Z]) But as far as I can see that simply doesn't work. I haven't been able to use | that way, combining _parts_ of a re. That was the first thing I tried. The original works right except for not matching at the start or end of a string, the thing with the | doesn't work at all: >>> test = compile(r'(^|[^a-zA-Z])disc($|[^a-zA-Z])') >>> test.findall('') [] >>> test.findall('disc') [('', '')] >>> test.findall(' disc ') [(' ', ' ')] >>> disc = compile(r'[^a-zA-Z]disc[^a-zA-Z]') >>> disc.findall(' disc disc disc') [' disc '] >>> disc.findall(' disc disc disc') [' disc ', ' disc '] >>> test.findall(' disc disc disc') [(' ', ' '), (' ', ' ')] >>> disc.findall(' disc disc disc') [' disc ', ' disc '] >>> disc.findall(' disc disc disc ') [' disc ', ' disc ', ' disc '] > Diez -- David C. Ullrich From theller at python.net Wed Jun 18 15:32:24 2008 From: theller at python.net (Thomas Heller) Date: Wed, 18 Jun 2008 21:32:24 +0200 Subject: Calling pcre with ctypes In-Reply-To: <947df973-8bae-4364-bf76-64a9a7d4a51f@s50g2000hsb.googlegroups.com> References: <947df973-8bae-4364-bf76-64a9a7d4a51f@s50g2000hsb.googlegroups.com> Message-ID: <6bt667F3c0tlpU1@mid.individual.net> moreati schrieb: > Recently I discovered the re module doesn't support POSIX character > classes: > > Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import re >>>> r = re.compile('[:alnum:]+') >>>> print r.match('123') > None > > So I thought I'd try out pcre through ctypes, to recreate pcredemo.c > in python. The c code is at: > http://vcs.pcre.org/viewvc/code/trunk/pcredemo.c?view=markup > > Partial Python code is below > > I'm stuck, from what I can tell a c array, such as: > int ovector[OVECCOUNT]; > > translates to > ovector = ctypes.c_int * OVECOUNT > > but when I pass ovector to a function I get the traceback > $ python pcredemo.py [a-z] fred > Traceback (most recent call last): > File "pcredemo.py", line 65, in > compiled_re, None, subject, len(subject), 0, 0, ovector, OVECOUNT > ctypes.ArgumentError: argument 7: : Don't > know how to convert parameter 7 > > What is the correct way to construct and pass ovector? 'ctypes.c_int * OVECOUNT' does not create an array *instance*, it creates an array *type*, comparable to a typedef in C. You can create an array instance by calling the type, with zero or more initializers: ovector = (ctypes.c_int * OVECOUNT)(0, 1, 2, 3, ...) Thomas From roy at panix.com Wed Jun 4 08:54:06 2008 From: roy at panix.com (Roy Smith) Date: Wed, 04 Jun 2008 08:54:06 -0400 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> <873antn9il.fsf@benfinney.id.au> <6ammujF38poe2U2@mid.uni-berlin.de> <87y75llp5x.fsf@benfinney.id.au> Message-ID: In article <87y75llp5x.fsf at benfinney.id.au>, Ben Finney wrote: > By definition, "private" functions are not part of the publicly > documented behaviour of the unit. Any behaviour exhibited by some > private component is seen externally as a behaviour of some public > component. You know the difference between theory and reality? In theory, there is none... Sometimes it's useful to test internal components. Imagine this class: class ArmegeddonMachine: def pushTheButton(self): "Destroy a random city" city = self._pickCity() self._destroy(city) def _pickCity(): cities = ['New York', 'Moscow', 'Tokyo', 'Beijing', 'Mumbai'] thePoorSchmucks = random.choice(cities) return 'New York' def _destroy(self, city): missle = ICBM() missle.aim(city) missle.launch() The only externally visible interface is pushTheButton(), yet you don't really want to call that during testing. What you do want to do is test that a random city really does get picked. You can do one of two things at this point. You can say, "But, that's not part of the externally visible interface" and refuse to test it, or you can figure out a way to test it. Up to you. From Lie.1296 at gmail.com Wed Jun 11 10:32:09 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 11 Jun 2008 07:32:09 -0700 (PDT) Subject: can't assign to literal References: Message-ID: On Jun 11, 2:53?am, maehhheeyy wrote: > this is stopping my program from running properly. is there something > wrong in my code when that happens? That simply means you did something like this: 'hello' = 'another' 123 = 'kilo' [12, 'asd] = 123 Sometimes it's not that obvious (although they're obvious for a more experienced programmers): for 123 in xrange(10): pass I think you've realized what you've done. And there is a pretty obvious signal that hints that you didn't know the basic syntax of python (or at least the basic syntax of the for-loop). From fernandes.fd at gmail.com Tue Jun 3 13:34:38 2008 From: fernandes.fd at gmail.com (Filipe Fernandes) Date: Tue, 3 Jun 2008 13:34:38 -0400 Subject: parser recommendation In-Reply-To: <686de663-94d2-4e8b-b079-197793d0a8cc@2g2000hsn.googlegroups.com> References: <686de663-94d2-4e8b-b079-197793d0a8cc@2g2000hsn.googlegroups.com> Message-ID: <11397a330806031034x36a85609m7415ddd27ccd3e6b@mail.gmail.com> On Tue, Jun 3, 2008 at 10:41 AM, Paul McGuire wrote: > If you learn both, you may find that pyparsing is a good way to > quickly prototype a particular parsing problem, which you can then > convert to PLY for performance if necessary. The pyparsing prototype > will be an efficient way to work out what the grammar "kinks" are, so > that when you get around to PLY-ifying it, you already have a clear > picture of what the parser needs to do. > Thanks (both Paul and Kay) for responding. I'm still looking at Trail in EasyExtend and pyparsing is very nicely objected oriented but PLY does seems to have the speed advantage, so I'm leaning towards PLY But I do have more questions... when reading the ply.py header (in 2.5) I found the following paragraph... # The current implementation is only somewhat object-oriented. The # LR parser itself is defined in terms of an object (which allows multiple # parsers to co-exist). However, most of the variables used during table # construction are defined in terms of global variables. Users shouldn't # notice unless they are trying to define multiple parsers at the same # time using threads (in which case they should have their head examined). Now, I'm invariably going to have to use threads... I'm not exactly sure what the author is alluding to, but my guess is that to overcome this limitation I need to acquire a thread lock first before "defining/creating" a parser object before I can use it? Has anyone ran into this issue....? This would definitely be a showstopper (for PLY anyway), if I couldn't create multiple parsers because of threads. I'm not saying I need more than one, I'm just not comfortable with that limitation. I have a feeling I'm just misunderstanding since it doesn't seem to hold you back from creating multiple parsers under a single process. filipe From arslanburney at gmail.com Fri Jun 13 03:24:26 2008 From: arslanburney at gmail.com (arslanburney at gmail.com) Date: Fri, 13 Jun 2008 00:24:26 -0700 (PDT) Subject: Plotting Graphs + Bestfit lines References: <1a919a2b-6430-4e2e-a190-2e00e43a6138@25g2000hsx.googlegroups.com> <022d382b-0b7b-4757-855a-f07019791fcc@d45g2000hsc.googlegroups.com> Message-ID: <05e67e40-db9c-4d85-94c1-f0e31dd5da38@27g2000hsf.googlegroups.com> On Jun 13, 12:13?pm, Peter Otten <__pete... at web.de> wrote: > arslanbur... at gmail.com wrote: > > Umm.... Tried this out too.... Laiken heres the error that this > > gives.. > > > Traceback (most recent call last): > > ? File "D:\Questions\Gradient and C\Gnuplot\Combining Best fit and > > Plotting\combasd.py", line 3, in > > ? ? combine.show_plots([(2,3), (4,8), (5,9), (6,2)], [(1,7), (3,3), > > (4,5), (5,6)], [(1,3), (3,10), (4,8), (7,9) ] ) > > ? File "D:\Questions\Gradient and C\Gnuplot\Combining Best fit and > > Plotting\combine.py", line 54, in show_plots > > ? ? gp = combine.plot( original, expected, actual) > > NameError: global name 'combine' is not defined > > > Still confused though i get the instance part ur trying to tell me. > > Sorry, it should have been > > def show_plots(original, expected, actual): > ? ? gp = plot( original, expected, actual) > ? ? raw_input("first") > ? ? gp = bestfit(expected) > ? ? raw_input("second") > ? ? gp = bestfit(actual) > ? ? raw_input("third") > > Peter Tried that out too. No error however, best fit lines still not being made on the graph. Only the 3 plot lines show up. From george.sakkis at gmail.com Tue Jun 3 18:59:38 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 3 Jun 2008 15:59:38 -0700 (PDT) Subject: Constructor re-initialization issue References: Message-ID: <00d47094-b687-48f2-9dc0-c92994a4f70c@y38g2000hsy.googlegroups.com> On Jun 3, 6:11 pm, pythonrept... at gmail.com wrote: > Hello all, > > I have come across this issue in Python and I cannot quite understand > what is going on. > > class Param(): > def __init__(self, data={}, condition=False): > if condition: > data['class']="Advanced" > print data > > In the previous example, I expect the variable data to be re- > initialized every time I construct an object type Param. However, when > I do the following: > > Param(condition=True) > Param(condition=False) > > The second call still prints {'class': 'Advanced'} > > Shouldn't data be initialized to {} since it is the default in > __init__? Why would the state of data be preserved between two > independent instantiations? > > Any help would be greatly appreciated. > > M. This must be by far the most FAQ.. unfortunately it seems it will remain for 3.x as well: http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects From bruno.42.desthuilliers at websiteburo.invalid Fri Jun 6 10:46:08 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 06 Jun 2008 16:46:08 +0200 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: References: Message-ID: <48494d73$0$31857$426a74cc@news.free.fr> Gabriel Rossetti a ?crit : > Larry Bates wrote: >> Gabriel Rossetti wrote: >>> Hello everyone, >>> >>> I had read somewhere that it is preferred to use >>> self.__class__.attribute over ClassName.attribute to access class >>> (aka static) attributes. I had done this and it seamed to work, until >>> I subclassed a class using this technique and from there on things >>> started screwing up. I finally tracked it down to >>> self.__class__.attribute! What was happening is that the child >>> classes each over-rode the class attribute at their level, and the >>> parent's was never set, so while I was thinking that I had indeed a >>> class attribute set in the parent, it was the child's that was set, >>> and every child had it's own instance! Since it was a locking >>> mechanism, lots of fun to debug... So, I suggest never using >>> self.__class__.attribute, unless you don't mind it's children >>> overriding it, but if you want a truly top-level class attribute, use >>> ClassName.attribute everywhere! >>> >>> I wish books and tutorials mentioned this explicitly.... >>> >>> Gabriel >> >> If you define a class instance variable with the same name as the >> class attribute, how would Python be able to distinguish the two? >> That is a feature not a problem. Getter looks for instance attribute, >> if one is not found it looks for a class attribute, and upwards. This >> behavior is used by Zope to do all sorts of neat stuff. >> >> -Larry Bates >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > A class instance variable, you must mean an instance attribute no? I think that's what he meant, yes. > If > that is so, then with just self.attribute? Maybe there is a concept that > I don't know about, The concept of name resolution (aka lookup) rules in Python, perhaps ? When you do obj.attribute, attribute is first looked for in the object, then in it's class, then in the parent classes. So yes, you can get a class (or parent class) attribute directly on the instance. Note that assignment on the instance (obj.attribute = value) will alway (computed attributes or other hooks excepted) create the attribute on the target, so if you have Class.attribute set, and then do obj = Class(); obj.attribute = 42, then obj.attribute will shadow Class.attribute. > I've studied class/static attributes and instance > attributes in my OOP classes. Forget about your OOP classes, mostly if it was in fact a Java or C++ class. Python's object model is very far away from what most courses present as "OOP". > Gabriel From apardon at forel.vub.ac.be Tue Jun 10 04:03:08 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Jun 2008 08:03:08 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> <49356862-86a6-4df4-886a-cd57827c1b1e@w8g2000prd.googlegroups.com> Message-ID: On 2008-06-09, Lie wrote: >> >> That seems strange to me. The and-or simulation that was offerd in the >> FAQ allowed for about the same kind of structures as the ternary >> operator in C and was used in the standard library IIRC. >> >> So the same unreadable was already possible to write, plus that it >> could cause bugs and had to be made even more unreadable in order >> to work correctly. Considering this it I find it odd that hurting >> readability was a motivation not to have it. > > In case you didn't notice, the and-or simulation is a hack, it is not > to be used by anyone writing real code (instead of for an entry to > Obfuscated Python Code Contest) to substitute it for inline if. If > inline if is "formalized", that means the language encourages the use > of inline if, which we don't want to have. Who is we? The last poll I know about had a majority in favor of a ternary operator. -- Antoon Pardon From martin at v.loewis.de Mon Jun 2 17:01:45 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 02 Jun 2008 23:01:45 +0200 Subject: robotparser behavior on 403 (Forbidden) robot.txt files In-Reply-To: <48441f05$0$17181$742ec2ed@news.sonic.net> References: <48441f05$0$17181$742ec2ed@news.sonic.net> Message-ID: <48445fba$0$7573$9b622d9e@news.freenet.de> > I just discovered that the "robotparser" module interprets > a 403 ("Forbidden") status on a "robots.txt" file as meaning > "all access disallowed". That's unexpected behavior. That's specified in the "norobots RFC": http://www.robotstxt.org/norobots-rfc.txt - On server response indicating access restrictions (HTTP Status Code 401 or 403) a robot should regard access to the site completely restricted. So if a site returns 403, we should assume that it did so deliberately, and doesn't want to be indexed. > A major site ("http://www.aplus.net/robot.txt") has their > "robots.txt" file set up that way. You should try "http://www.aplus.net/robots.txt" instead, which can be accessed just fine. Regards, Martin From johnjsal at gmailNOSPAM.com Sun Jun 15 23:13:34 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sun, 15 Jun 2008 23:13:34 -0400 Subject: newbie question: for loop within for loop confusion In-Reply-To: References: Message-ID: <4855da63$0$11599$607ed4bc@cv.net> takayuki wrote: > inchworm > inchworm P.S. Why does 'inchworm' only print twice? Or is that not the full output? From malaclypse2 at gmail.com Wed Jun 18 11:02:32 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 18 Jun 2008 11:02:32 -0400 Subject: Hrounding error In-Reply-To: References: Message-ID: <16651e80806180802k57c2a2fdra2a006d10786d152@mail.gmail.com> On Wed, Jun 18, 2008 at 1:47 AM, wrote: >>>> 234 - 23234.2345 > -23000.234499999999 > > This is not correct by my calculations. Python floating point operations use the underlying C floating point libraries which, in turn, usually rely on the hardware's floating point implementations. This Wikipedia article talks about how those values are usually stored and manipulated: http://en.wikipedia.org/wiki/IEEE_floating-point_standard So, which IEEE double precision floating point value would you like instead? As far as I understand it, these are your two choices: 'ba490c020f76d6c0' = -23000.234499999999 'bb490c020f76d6c0' = -23000.234500000002 Alternatively, investigate the Decimal module, but keep in mind that it can have the same sorts of issues, just on different numbers. Compare, for instance: >>> (1.0/3.0) * 3.0 1.0 >>> from decimal import Decimal >>> ( Decimal('1.0')/Decimal('3.0') ) * Decimal('3.0') Decimal("0.9999999999999999999999999999") >>> -- Jerry From stefan_ml at behnel.de Fri Jun 13 08:13:42 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 13 Jun 2008 14:13:42 +0200 Subject: Functionality similar to PHP's SimpleXML? In-Reply-To: <2cff2ee3-970d-4ba0-97e5-821c65fbf0d6@d1g2000hsg.googlegroups.com> References: <2cff2ee3-970d-4ba0-97e5-821c65fbf0d6@d1g2000hsg.googlegroups.com> Message-ID: <48526476.7000108@behnel.de> Phillip B Oldham wrote: > I'm going to throw together a quick project over the weekend: a > spider. I want to scan a website for certain elements. > > I come from a PHP background, so normally I'd: > - throw together a quick REST script to handle http request/responses Use the urllib/urllib2 module in the stdlib for GET/POST with parameters or lxml for simple page requests. > - load the pages into a simplexml object and > - run an xpath over the dom to find the nodes I need to test Use lxml. http://codespeak.net/lxml/ Stefan From gherron at islandtraining.com Mon Jun 2 18:33:12 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 02 Jun 2008 15:33:12 -0700 Subject: Cast list of objects to list of strings In-Reply-To: <48546eb1-11f3-4a88-b1ac-97bd485a1823@k30g2000hse.googlegroups.com> References: <48546eb1-11f3-4a88-b1ac-97bd485a1823@k30g2000hse.googlegroups.com> Message-ID: <48447528.9030604@islandtraining.com> bukzor wrote: > I have this function: > > def write_err(obj): > from sys import stderr > stderr.write(str(obj)+"\n") > > and I'd like to rewrite it to take a variable number of objects. > Something like this: > > def write_err(*objs): > from sys import stderr > stderr.write(" ".join(objs)+"\n") > > but I lose the property that the function works on any object. No you don't. If you were happy with printing the str(...) of a single objects, why not just printout the (concatenation) of the str(...) of each of many objects? stderr.write(" ".join([str(b) for b in objs])+"\n") Gary Herron > What's > the simplest way to fix this? In essence, I need to cast a list of > objects to a list of strings. I'd like to do just "str(objs)" but that > (obviously) doesn't quite do what I need. > > -- > http://mail.python.org/mailman/listinfo/python-list > From __peter__ at web.de Thu Jun 12 09:09:53 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Jun 2008 15:09:53 +0200 Subject: using re module to find " but not " alone ... is this a BUG in re? References: Message-ID: anton wrote: > I want to replace all occourences of " by \" in a string. > > But I want to leave all occourences of \" as they are. > > The following should happen: > > this I want " while I dont want this \" > > should be transformed to: > > this I want \" while I dont want this \" > > and NOT: > > this I want \" while I dont want this \\" > > I tried even the (?<=...) construction but here I get an unbalanced > paranthesis error. > > It seems tha re is not able to do the job due to parsing/compiling > problems for this sort of strings. > > > Have you any idea?? The problem is underspecified. Should r'\\"' become r'\\\"' or remain unchanged? If the backslash is supposed to escape the following letter including another backslash -- that can't be done with regular expressions alone: # John's proposal: >>> print re.sub(r'(?>> parts = re.compile("(\\\\.)").split('no " one \\", two \\\\"') >>> parts[::2] = [p.replace('"', '\\"') for p in parts[::2]] >>> print "".join(parts) no \" one \", two \\\" Peter From dullrich at sprynet.com Sat Jun 7 09:48:13 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Sat, 07 Jun 2008 08:48:13 -0500 Subject: how to build a street with more than 1 house ? References: Message-ID: On Sat, 07 Jun 2008 00:45:07 +0200, Stef Mientki wrote: >hello, > >In the code below, I can build a large street like this: > large_street = house * 25 >but not a small street. like this: > small_street = 5 * house > >Why is this different ? Because you're multiplying on the left in one case and on the right in the other. You realize that house*5 should work, right? >And more interesting, how do I get the right results ? > >thanks, >Stef Mientki > >class type_house ( object ) : > def __init__( self, front_doors = 1 ) : > self.front_doors = front_doors > def __mul__ ( self, b ) : > return type_house ( self.front_doors * b ) The reason house*25 works is that the __mul__ method says what it should be. If you want 5*house to work you need a __rmul__. Nothing in Python automatically makes a*b the same as b*a; when it sees 5*house first it checks 5 to see whether it knows whether it knows what 5*house should be (no, 5 never heard of this house thing), then it checks house to see if it knows what 5*house should be (no, house has no __rmul__). The simplest thing is just to define __rmul__ to make multiplication commuttative: def __rmul__(self, b): """Defines what b*self should return.""" return self*b Now 5*house calls __rmul__, which returns house*5. That in turn calls __mul__, which returns what you want. And some day when you modify __mul__ (in a subclass?) you won't need to worry about making the same change to __rmul__. >house = type_house () >large_street = house * 25 >print large_street.front_doors >small_street = 5 * house >print small_street.front_doors David C. Ullrich From fetchinson at googlemail.com Thu Jun 12 14:25:54 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 12 Jun 2008 11:25:54 -0700 Subject: howto split string with both comma and semicolon delimiters In-Reply-To: <3e2540ab-1d2a-45a5-a5b6-3f7ae7a4efac@x35g2000hsb.googlegroups.com> References: <3e2540ab-1d2a-45a5-a5b6-3f7ae7a4efac@x35g2000hsb.googlegroups.com> Message-ID: > howto split string with both comma and semicolon delimiters? > > i.e. (for example) get ['a','b','c'] from string "a,b;c" > > I have tried s.split(',;') but it don't work A very pedestrian solution would be: def multisplit( s, seps ): words = [ ] word = '' for char in s: if char in seps: if word: words.append( word ) word = '' else: word += char if word: words.append( word ) return words Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From gagsl-py2 at yahoo.com.ar Fri Jun 13 03:36:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Jun 2008 04:36:17 -0300 Subject: best way to create a timer/alarm References: <17815502.post@talk.nabble.com> Message-ID: En Fri, 13 Jun 2008 02:42:53 -0300, Alexnb escribi?: > I am wondering what is the best way to create a timer, like an alarm, > once it > reaches a time, it triggers an event. I have a way of doing this but it > seems like it isn't good at all. If it helps at all I am using a Tkinter, > but that probably doesn't mean much. Actually it *is* very important - such things are done in very different ways on different GUI libraries. > The way I was doing it was using a > while loop, and just saying while current time is not = to trigger time, > do > nothing, and when it is, do event. Doing so makes your application irresponsive (frozen) until the time elapses. Use the "after" method; see -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri Jun 13 03:05:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Jun 2008 04:05:06 -0300 Subject: FPC: Exception : Unknown Run-Time error : 210 References: Message-ID: En Thu, 12 Jun 2008 12:38:34 -0300, Sa?a Bistrovi? escribi?: > FPC: Exception : Unknown Run-Time error : 210 Wrong list... you are probably looking for http://lists.freepascal.org/mailman/listinfo/fpc-pascal/ -- Gabriel Genellina From i.i at i.i Sun Jun 22 14:24:25 2008 From: i.i at i.i (Josip) Date: Sun, 22 Jun 2008 20:24:25 +0200 Subject: Storing value with limits in object References: <6tednUvC9-jDxMPVnZ2dnUVZ_hGdnZ2d@comcast.com> Message-ID: > Why not make it a function? > > function assignLimited(value, vmin, vmax): > value = max(vmin, value) > value = min(vmax, value) > return value > > > a = assignLimited(7, 0, 10) > > > Seems like it solves your problem relatively cleanly. > Note: I also removed min/max variables because they would mask the > built-in min/max functions. > > -Larry Yes, the simple solution is often the best. Still, I'm going for object oriented solution because I want the value and it's limits to be kept together as I'll have many such values with different limits. Storing all the limits in caller namespace is not really an option. From omer at no-log.org Thu Jun 19 12:10:43 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Thu, 19 Jun 2008 18:10:43 +0200 Subject: Installing Python 3.0 no probs running 2.5 at the same time? In-Reply-To: <4eb587db-ccd2-4d98-bfc0-abfda4edc4fc@i76g2000hsf.googlegroups.com> References: <4eb587db-ccd2-4d98-bfc0-abfda4edc4fc@i76g2000hsf.googlegroups.com> Message-ID: <200806191810.43661.omer@no-log.org> Le Thursday 19 June 2008 17:32:10 cirfu, vous avez ?crit?: > Can I install 3.0 without breaking 2.5? Meaning does it overwrite some > bindings or something or it just installs 3.0 in a different folder as > a completely separate program? It's OK for any version having different major/minor version numbers (so 2.4 + 2.5 is OK, but _not_ 2.4.2 + 2.4.4). Everything go in different directories, and a version specific executable is also installed (python2.5, python3.0...). The main one (python) is just a link to one of them. -- C?dric Lucantis From tedpottel at gmail.com Fri Jun 6 16:14:52 2008 From: tedpottel at gmail.com (tedpottel at gmail.com) Date: Fri, 6 Jun 2008 13:14:52 -0700 (PDT) Subject: Trying to install mysql lib for python Message-ID: <7a963eaa-2468-4d3d-bf24-f05d8bd57937@f36g2000hsa.googlegroups.com> Hi How do I install mysql db libray for python? I went to source forg and downloaded the following zip folder MySQL_python-1.2.2-py2.4-win32 I open the folder and looked inside did not see any directions. Help From dinilkarun at gmail.com Fri Jun 6 06:52:27 2008 From: dinilkarun at gmail.com (Dinil Karun) Date: Fri, 6 Jun 2008 16:22:27 +0530 Subject: Convert Word .doc to Acrobat .pdf files Message-ID: <1dc26c3a0806060352k442475ccp6716b713268c161a@mail.gmail.com> hi, I am using the below code but i am getting a error saying pyUno module not found. can u please help. Regards Dinil ------------------------X----------------------X_---------------------- I wrote a script which uses OpenOffice. It can convert and read a lot of formats. #!/usr/bin/env python #Old: !/optlocal/OpenOffice.org/program/python # (c) 2003-2006 Thomas Guettler http://www.tbz-pariv.de/ # OpenOffice1.1 comes with its own python interpreter. # This Script needs to be run with the python from OpenOffice1: # /opt/OpenOffice.org/program/python # Start the Office before connecting: # soffice "-accept=socket,host=localhost,port=2002;urp;" # # With OpenOffice2 you can use the default Python-Interpreter (at least on SuSE) # # Python Imports import os import re import sys import getopt default_path="/usr/lib/ooo-2.0/program" sys.path.insert(0, default_path) # pyUNO Imports try: import uno from com.sun.star.beans import PropertyValue except: print "This Script needs to be run with the python from OpenOffice.org" print "Example: /opt/OpenOffice.org/program/python %s" % ( os.path.basename(sys.argv[0])) print "Or you need to insert the right path at the top, where uno.py is." print "Default: %s" % default_path raise sys.exit(1) extension=None format=None def usage(): scriptname=os.path.basename(sys.argv[0]) print """Usage: %s [--extension pdf --format writer_pdf_Export] files All files or directories will be converted to HTML. You must start the office with this line before starting this script: soffice "-accept=socket,host=localhost,port=2002;urp;" If you want to export to something else, you need to use give the extension *and* the format. For a list of possible export formats see http://framework.openoffice.org/files/documents/25/897/filter_description.html or /opt/OpenOffice.org/share/registry/data/org/openoffice/Office/TypeDetection.xcu or grep -ri MYEXTENSION /usr/lib/ooo-2.0/share/registry/modules/org/openoffice/TypeDetection/ the format is Message-ID: brechmos writes: >Hi, >I have been using PHP the last while and in particular strtotime. >What I want to replicate is finding the second or fourth Monday of the >next month. In PHP with strtotime it is easy (strtotime("second >Monday", strtotime("next month"), but I can't find an easy way to do >it in Python. I have seen DateUtil, but it seems to be able to do >only the simpler parsing (could be wrong). >Any other ideas? http://code-bear.com/code/parsedatetime/ >>> import parsedatetime.parsedatetime as pdt >>> p = pdt.Calendar() >>> p.parse('next month') ((2008, 7, 1, 9, 0, 0, 1, 183, -1), 1) Eddie From Lie.1296 at gmail.com Wed Jun 18 06:47:13 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 18 Jun 2008 03:47:13 -0700 (PDT) Subject: dict order References: Message-ID: <25f4d43d-1fb7-47f9-82b6-1b82ad42e73a@j33g2000pri.googlegroups.com> On Jun 18, 4:22?pm, Robert Bossy wrote: > Hi, > > I wish to know how two dict objects are compared. By browsing the > archives I gathered that the number of items are first compared, but if > the two dict objects have the same number of items, then the comparison > algorithm was not mentioned. > > Note that I'm not trying to rely on this order. I'm building a > domain-specific language where there's a data structure similar to > python dict and I need an source of inspiration for implementing > comparisons. > > Thanks > RB Why not consider them as equal, it's simple and is basically telling people not to rely on them because one day A might be lower than B and the other day, A and B that hasn't been modified at all might switch sides without warning. Or you could just use any arbitrary way of comparison (Python Zen: In the face of ambiguity, refuse the temptation to guess.). From john.dohn.john at gmail.com Fri Jun 6 08:22:38 2008 From: john.dohn.john at gmail.com (John Dohn) Date: Sat, 7 Jun 2008 00:22:38 +1200 Subject: How to kill a thread? In-Reply-To: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> Message-ID: <608040960806060522m32c4e6abp836684b15c98aac3@mail.gmail.com> On Fri, Jun 6, 2008 at 10:30 PM, John Dohn wrote: > Hi there, > > How can I kill a threading.Thread subclass from MainThread? At the end I did: def run(self): while True: if exit_event.isSet(): # Thread exiting return try: data = q_in.get(timeout = .5) except Queue.Empty: continue # ... process data And then in the MainThread I do exit_event.set() and wait for all threads to exit. It's a pretty awkward solution but works. BTW Guys, is something like Thread.kill() planned for the future? Or is there a reason not to have it? Thanks JD -------------- next part -------------- An HTML attachment was scrubbed... URL: From Russ.Paielli at gmail.com Mon Jun 9 17:39:03 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 9 Jun 2008 14:39:03 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <4847d39d$0$7614$426a74cc@news.free.fr> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> <484cf5f6$0$15495$426a74cc@news.free.fr> <127975a3-b3d9-4799-9673-b292ec8d37e3@x19g2000prg.googlegroups.com> <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> Message-ID: <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> On Jun 9, 2:10 pm, "bruno.desthuilli... at gmail.com" wrote: > But if it takes 6 month to get the mentioned developer to release > something I can use, I'm screwed up. Fine. I've lost track of how many times I've said this now, but my suggestion for a "priv" keyword allowed for "indirect" access to private data through some name-mangling scheme. That could be your temporary fix while you are waiting for the developer to release a corrected version. And even if that option were not available, you could simply open up the relevant source file in the editor of your choice and remove the offending "priv" declaration. I completely fail to see how you are "screwed." Sorry, but when I have to keep repeating the same basic points over and over, I can't help but think I might be wasting my time. From gabriela.soares.fcup at gmail.com Wed Jun 11 09:04:35 2008 From: gabriela.soares.fcup at gmail.com (Gabriela Soares) Date: Wed, 11 Jun 2008 14:04:35 +0100 Subject: python gui In-Reply-To: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> References: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> Message-ID: <9d68e4e90806110604n29dd847ah729a02b4398a3072@mail.gmail.com> Greetings, I want to make a dynamic dashboard, something like: http://examples.adobe.com/flex3/labs/dashboard/main.html# but using python. Is it possible ? Thanks in advance. Best regards, Gabriela Soares. -------------- next part -------------- An HTML attachment was scrubbed... URL: From none at this.time Fri Jun 6 14:44:33 2008 From: none at this.time (The Pythonista) Date: Fri, 06 Jun 2008 14:44:33 -0400 Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> Message-ID: It's always been my understanding that you can't forcibly kill a thread in Python (at least not in a portable way). The best you can do is politely ask it to die, IIRC. -- code.py: A blog about life, the universe, and Python http://pythonista.wordpress.com ** Posted from http://www.teranews.com ** From johnjsal at NOSPAMgmail.com Fri Jun 27 12:09:59 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 27 Jun 2008 12:09:59 -0400 Subject: How do web templates separate content and logic? Message-ID: <486510f7$0$3007$c3e8da3@news.astraweb.com> I've been doing some research on web templates, and even though I read that they help enforce the MVC pattern, I don't really understand how they are keeping content and logic separated. Layout is easy, it's just not there as far as I can see, and CSS can be used for that. But when you have a templating system that mixes HTML and Python code, how is this helping to keep things separate? It seems to be the same issue that some people have with PHP (that it is too integrated with the HTML, rather than being separate). Of course, I suppose whether or not any of this matters depends on if you are a web designer or a programmer, but am I missing something about templates, or is it really the case that they, more or less by definition, combine content and logic? Thanks. From bsagert at gmail.com Tue Jun 10 11:56:53 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Tue, 10 Jun 2008 08:56:53 -0700 (PDT) Subject: Python doesn't understand %userprofile% Message-ID: In xp when I try os.path.getmtime("%userprofile/dir/file%") Python bites back with "cannot find the path specified" Since my script has to run on machines where the username is unspecified I need a fix. Thanks in advance. From s0suk3 at gmail.com Wed Jun 25 23:30:38 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Wed, 25 Jun 2008 20:30:38 -0700 (PDT) Subject: Working with the Windows Registry References: <49beca2a-9d6c-40a2-a7c3-bf1cf376df0a@l28g2000prd.googlegroups.com> Message-ID: On Jun 25, 9:48 pm, teh_sAbEr wrote: > Hi everybody. I'm trying to write a script that'll change desktop > wallpaper every time its run. Heres what I've gotten so far: > > #random wallpaper changer! > import _winreg > from os import walk > from os.path import exists > from random import randint > > #first grab a registry handle. > handle = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,'Control Panel > \Desktop',_winreg.KEY_SET_VALUE) > > def GenerateListOfWallpapers(): > targetDir = 'C:\Documents and Settings\Enrico Jr\My Documents\Jr > \'s Wallpapers' > fileNames = [] > filePaths = [] > if exists(targetDir): > #proceed to make the list of files > for x,y,z in walk(targetDir): > for name in z: > fileNames.append(name) > for item in fileNames: > filePaths.append(targetDir + '\\' + item) > return filePaths > > def RandomlySelectWallpaper(filePaths): > index = randint(0,len(filePaths)-1) > RandomlySelectedWallpaper = filePaths[index] > return RandomlySelectedWallpaper #it should be a string... > > #now to edit the wallpaper registry key > newWallpaper = RandomlySelectWallpaper(GenerateListOfWallpapers()) > print "Registry Handle Created." > print "Random wallpaper selected." > _winreg.SetValueEx(handle,'ConvertedWallpaper', > 0,_winreg.REG_SZ,newWallpaper) > print "New wallpaper value set." > > The problem is, every time I run it, I get an "Access Denied" error > when it tries to execute > _winreg.SetValueEx(), even though i've opened the key with the > KEY_SET_VALUE mask like it said in the help docs. Could there be > another problem or a better way to do this? Note the line #first grab a registry handle. handle = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Control Panel \Desktop', _winreg.KEY_SET_VALUE) OpenKey() takes four arguments: (1) The Registry key handle or one of the predefined constants, (2) the string containing the subkey to open, (3) the 'res' (which I don't know what is :), and the 'sam', which is the access mask (KEY_SET_VALUE, in this case). You are only passing three arguments, so the access mask is going to the 'res' argument instead of the 'sam' argument. Pass instead 0 as the res: handle = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Control Panel\Desktop', 0, _winreg.KEY_SET_VALUE) Regards, Sebastian From wuwei23 at gmail.com Thu Jun 5 20:58:19 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 5 Jun 2008 17:58:19 -0700 (PDT) Subject: Guide to organizing modules? References: <1611a070-35f9-4072-b95f-ab592820f516@c65g2000hsa.googlegroups.com> Message-ID: <5b68316f-b2d6-4cec-bb8e-c9ed55202842@v26g2000prm.googlegroups.com> On Jun 6, 10:32 am, bukzor wrote: > In summary: are there any good (or official) guidelines for how to > organize and separate python functions and classes into modules? Hey bukzor, Are you familiar with the concept of packages in Python? http://docs.python.org/tut/node8.html#SECTION008400000000000000000 That should allow you to keep all of your scriptlets as separate files while still having the advantage of keeping them in a single namespace for importing. (But if you know this already, don't mind me....) From george.sakkis at gmail.com Thu Jun 12 02:08:24 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 11 Jun 2008 23:08:24 -0700 (PDT) Subject: Producer-consumer threading problem References: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> <680969c8-dfb2-4021-b33c-790c5de2a849@27g2000hsf.googlegroups.com> Message-ID: <61046d91-2512-4cb4-b36a-1af690c5c219@c65g2000hsa.googlegroups.com> On Jun 11, 3:07 pm, Carl Banks wrote: > On Jun 10, 11:33 pm, George Sakkis wrote: > > > I pasted my current solution athttp://codepad.org/FXF2SWmg. Any > > feedback, especially if it has to do with proving or disproving its > > correctness, will be appreciated. > > It seems like you're reinventing the wheel. The Queue class does all > this, and it's been thorougly battle-tested. Synchronized queues are an extremely useful data structure in many situations. The producer/consumer paradigm however is a more general model and doesn't depend on any specific data structure. > So first of all, can you tell us why the following wouldn't work? It > might help us understand the issue you're facing (never mind the > produce and consume arguments for now--I'll cover that below). > > def iter_consumed(items): > q = Queue.Queue() > sentinel = object() > def produce_all() > for item in items: > q.put() > q.put(sentinel) > producer = threading.Thread(target=produce_all) > producer.start() > try: > while True: > item = q.get() > if item is sentinel: > return > yield item > finally: > # for robustness, notify producer to wrap things up > # left as exercise > producer.join() As it is, all this does is yield the original items, but slower, which is pretty much useless. The whole idea is to transform some inputs to some outputs. How exactly each input is mapped to an output is irrelevant at this point; this is the power of the producer/consumer model. Produce might mean "send an email to address X" and consume might mean "wait for an automated email response, parse it and return a value Y". No queue has to be involved; it *may* be involved of course, but that's an implementation detail, it shouldn't make a difference to iter_consumed(). If you replace "q.push"/"q.pop" with "produce"/"consume" respectively and make the last two parameters, you're much closer to my idea. What's left is getting rid of the sentinel, since the producer and the consumer may have been written independently, not aware of iter_consumed. E.g. for the email example, all producers and consumers (there may be more than one) must agree in advance on a "sentinel email". For a given situation that might not be a big issue, but then again, if iter_consumed() is written once without assuming a sentinel, it makes life easier for all future producers and consumers. > If you want to customize the effect of getting and putting, you can > subclass Queue and override the _get and _put methods (however, last > time I checked, the Queue class expects _put to always add an item to > the internal sequence representing the queue--not necessarily to the > top--and _get to always remove an item--not necessarily from the > bottom). Assuming that you're talking about the stdlib Queue.Queue class and not some abstract Queue interface, extending it may help for limited customization but can only get you so far. For instance the producer and the consumer may not live in the same address space, or even in the same machine. > One issue from your function. This line: > > done_remaining[1] += 1 > > is not atomic, but your code depends on it being so. No, it doesn't; it is protected by the condition object. George From bkustel at gmail.com Sun Jun 15 04:04:37 2008 From: bkustel at gmail.com (bkustel at gmail.com) Date: Sun, 15 Jun 2008 01:04:37 -0700 (PDT) Subject: marshal.dumps quadratic growth and marshal.dump not allowing file-like objects Message-ID: I'm stuck on a problem where I want to use marshal for serialization (yes, yes, I know (c)Pickle is normally recommended here). I favor marshal for speed for the types of data I use. However it seems that marshal.dumps() for large objects has a quadratic performance issue which I'm assuming is that it grows its memory buffer in constant increments. This causes a nasty slowdown for marshaling large objects. I thought I would get around this by passing a cStringIO.StringIO object to marshal.dump() instead but I quickly learned this is not supported (only true file objects are supported). Any ideas about how to get around the marshal quadratic issue? Any hope for a fix for that on the horizon? Thanks for any information. From grante at visi.com Mon Jun 23 16:12:59 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 23 Jun 2008 15:12:59 -0500 Subject: Using Python to run SSH commands on a remote server References: <03a078c8$0$3229$c3e8da3@news.astraweb.com> Message-ID: <_pSdnUkh3Z5Wnv3VnZ2dnUVZ_sninZ2d@posted.visi> On 2008-06-23, John Salerno wrote: > Generally speaking, what tools would I use to do this? In shell scripts I use expect to automate ssh stuff, so I would probably give pyexpect or pexpect a try: http://sourceforge.net/projects/pexpect/ > Is there a built-in module for it? I looked at the telnetlib > module, but the documentation wasn't really complete enough > for me to get a good idea of it. Is Telnet and SSH even the > same thing? Not even close. > Basically, I want to write a script that will automate the > process of making all .py files on my web server executable > (chmod 755, or something similar). I'd probably just write an expect script: http://expect.nist.gov/ -- Grant Edwards grante Yow! Is a tattoo real, like at a curb or a battleship? visi.com Or are we suffering in Safeway? From kyosohma at gmail.com Wed Jun 4 14:01:28 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 4 Jun 2008 11:01:28 -0700 (PDT) Subject: how to combine 2 program? References: Message-ID: On Jun 4, 8:53?am, a... at cs.its.ac.id wrote: > i am a newbe in pyhton. > i am using "Twisted Network Programming Essentials By Abe Fettig" as my > tutorial. in that tutorial, i found 2 example, IMAPDOWNLOAD.py and > requesthandler.py > > my problem is how to combine those program become one program, so that i > can input the imapdownload inputs via web? > thanks, ?Any guidance in this would be greatly appreciated... I recommend re-posting to the Twisted mailing list: http://twistedmatrix.com/trac/wiki/TwistedCommunity Mike From georgeoliverGO at gmail.com Sat Jun 28 13:25:10 2008 From: georgeoliverGO at gmail.com (George Oliver) Date: Sat, 28 Jun 2008 10:25:10 -0700 (PDT) Subject: 2D online multiplayer framework? References: <6dc6195b-b8a0-42a9-a982-3a4b70943c24@r37g2000prm.googlegroups.com> Message-ID: <49e9fbe6-26de-40f0-ae03-fb559499e450@h1g2000prh.googlegroups.com> On Jun 28, 9:04 am, Gary Herron wrote: > > Pyglet is my favorite: http://www.pyglet.org/ > > Twisted might be fine for the "online multiplayer" parts, but really if > you want a 2D/3D real-time game, start with a game framework. > > Gary Herron Thanks C?dric and Gary for the suggestions, I'm familiar with all of those. So a good workflow for a graphical online game is to make the game first and just plan for the incoming connections without knowing how they will be done exactly? My only experience with networked games is muds, where usually you do the opposite -- sockets first. From none at this.time Fri Jun 6 14:28:37 2008 From: none at this.time (The Pythonista) Date: Fri, 06 Jun 2008 14:28:37 -0400 Subject: Change in interactive interpreter? Message-ID: I remember the interactive interpreter used to define the name _ to return the value of the last expression that was evaluated. However, I tried it just today and got a NameError. Is this a change in the interpreter or is there a configuration option I need to set to enable it? Thanks! -- code.py: A blog about life, the universe, and Python http://pythonista.wordpress.com ** Posted from http://www.teranews.com ** From tew24 at spam.ac.uk Thu Jun 12 05:21:40 2008 From: tew24 at spam.ac.uk (Tom Wright) Date: Thu, 12 Jun 2008 10:21:40 +0100 Subject: matplotlib question References: <485079a0$0$11641$607ed4bc@cv.net> Message-ID: asdf wrote: > basically I need to plot a graph of data vs time. However when i use > matplotlib the hr:min tick marks come out very close together and > appear jumbled. You need to look up the matplotlib.dates package - it's covered briefly in the tutorial at http://matplotlib.sourceforge.net/tutorial.html At a guess, you want something along the lines of this... from matplotlib.dates import YearLocator, MonthLocator, WeekdayLocator, \ DayLocator, HourLocator, MinuteLocator, SecondLocator, \ DateFormatter subplot.xaxis.set_major_locator(HourLocator(range(0,24,6))) subplot.xaxis.set_major_formatter(DateFormatter("%a %H:%M")) subplot.xaxis.set_minor_locator(HourLocator(range(0,24,1))) ...but you'll probably need to look up the documentation to get the details to suit what you need. Hope that helps! -- I'm at CAMbridge, not SPAMbridge From eddieatter at gmail.com Wed Jun 11 20:21:23 2008 From: eddieatter at gmail.com (agent E 10) Date: Wed, 11 Jun 2008 17:21:23 -0700 (PDT) Subject: Brand New! References: <7f1828bf-ebe7-4111-bc59-70d125facb0a@d26g2000prg.googlegroups.com> <1208324917.7339.10.camel@paul-laptop> Message-ID: <76a2afe1-ab71-4e6c-b1db-dcf264ae6e69@g16g2000pri.googlegroups.com> On Apr 18, 12:47?pm, Nick Stinemates wrote: > On Wed, Apr 16, 2008 at 07:48:37AM +0200, Paul Scott wrote: > > > On Wed, 2008-04-16 at 02:35 -0300, Gabriel Genellina wrote: > > > I'm unsure if teaching Javascript, VBScript and Python at the same time is ? > > > a good thing, I'd think one would get a language soup and mix all the ? > > > concepts, but if it works for you, go ahead. > > > For other resources, see the beginners section in the Python wiki: ? > > >http://wiki.python.org/moin/BeginnersGuide > > > Well, as an example, I learnt Python to a decent level of competency in > > 2 days. I looked through the Dive into Python tuts, and then had a look > > at the Python GUI FAQ (Which didn't really help much, as I started with > > a GTK based GUI app). A little bit of Googling and a couple of questions > > to this list gave me everything that I needed to roll out a pretty > > decent application in 5 days. Oh, and just by the way, I am _not_ a > > Computer Scientist or anything, I am a botanist, which means that if I > > can do that, just about anyone that can read can do it. > > > Python has been long on my list of TODO's, and now, finally, it is > > there. I have immensely enjoyed it so far, and will continue to tinker > > well into the future. > > > --Paul > > I think that's wonderful! > > I think problem solving language independent. As long as you can break down what you need to do and conceptualize. You must have learned to do with with botany, so programming came natural :) > > -- > Nick Stinemates (n... at stinemates.org)http://nick.stinemates.org- Hide quoted text - > > - Show quoted text - I am using a windows computer. thanks for all the information, it was very helpful! -agent E 10 From rdabane at gmail.com Tue Jun 3 21:04:40 2008 From: rdabane at gmail.com (rdabane at gmail.com) Date: Tue, 3 Jun 2008 18:04:40 -0700 (PDT) Subject: Help need with subprocess communicate References: <0312b7e9-bffe-4360-bf3a-f5b3b26d243d@l64g2000hse.googlegroups.com> Message-ID: <530ccda9-818e-4abe-9f82-0720e27c48fd@z72g2000hsb.googlegroups.com> On Jun 3, 5:42 pm, Daniel Klein wrote: > On Tue, 3 Jun 2008 14:04:10 -0700 (PDT), rdab... at gmail.com wrote: > >I'm trying to perform following type of operation from inside a python > >script. > >1. Open an application shell (basically a tcl ) > >2. Run some commands on that shell and get outputs from each command > >3. Close the shell > > >I could do it using communicate if I concatenate all my commands > >( separated by newline ) and read all the output in the end. So > >basically I could do following sequence: > >1. command1 \n command2 \n command 3 \n > >2. Read all the output > > >But I want to perform it interactively. > >1. command1 > >2. read output > >3. command2 > >4. read output ...... > > >Following is my code: > > >from subprocess import * > >p2 = Popen('qdl_tcl',stdin=PIPE,stdout=PIPE) > >o,e = p2.communicate(input='qdl_help \n qdl_read \n > >qdl_reg_group_list ') > > >Please suggest a way to perform it interactively with killing the > >process each time I want to communicate with it. > > Use > stdin.write(command + '\n') > to 'send' data to the sub-process. > > Use > stdout.readline() > to 'receive' data from the sub-process. > > But to use this requires you open the subprocess with: > > universal_newlines = True > > It assumes that 'command' will be sent with '\n' and received data will come > in a line at a time. Your Python program needs to know what to expect; you > are in control. > > Alternatively, you can use std.write() and stdout.read() (without > universal_newlines) but this means you need to create your own IPC protocol > (like netstrings). > > Hope this helps, > > Daniel Klein Hi Daniel, Thanks for your reply.. I've done exactly as you suggested...but I'm still having problem with the read...it just gets stuck in the read ( I think because its a blocking read...) following is a simple example of problem..please try running it ... from subprocess import * p2 = Popen('python',shell=True,stdin=PIPE,stdout=PIPE,universal_newlines=True) for i in range(10): p2.stdin.write('print 10'+'\n') # Write Command o = p2.stdout.readline() # Read Command print o I appreciate all your help... Thanks, -Rahul Dabane. From kretik at yahoo.com Thu Jun 19 13:13:26 2008 From: kretik at yahoo.com (kretik) Date: Thu, 19 Jun 2008 10:13:26 -0700 Subject: Getting Python to run Python Scripts in cygwin In-Reply-To: References: Message-ID: You do have Python installed in Cygwin, right? It's an optional component, IIRC? If it is then it should have set the symlink in /usr/bin to wherever it's installed. Calvin Cheng wrote: > Hi guys, > > This may be a cygwin issue but I was hoping to get some answers here > as well if someone has fixed this problem before. > > Basically, I am able to run "python .py" python files in > command prompt. Unfortunately, I can't seem to get it to work in > cygwin. I always get an error that says: > python: can't open file '.py': [Errno 2] No such file or directory > > I have looked at my environment variables and it seems to be correct. > > Would be grateful if someone who has gotten python to work correctly > on cygwin could point me in the right direction. > > It is very cumbersome switching back-and-forth between command prompt > and cygwin just to run python scripts. > > Thank you in advance, > Calvin From deets at nospam.web.de Sun Jun 1 15:14:14 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 01 Jun 2008 21:14:14 +0200 Subject: Integrating a code generator into IDLE In-Reply-To: References: Message-ID: <6agaofF36ap0uU1@mid.uni-berlin.de> Sam Denton schrieb: > Code generators seem to be popular in Python. > (http://www.google.com/search?q=python+code-generator) Certainly not. The most of them will be used for generating bindings. Apart from that, you rareley (if ever) need to generate code. > I have one that I'd like to integrate into IDLE. Ideally, I'd like to > (1) have a new file type show up when I use the File/Open dialog, and > (2) have a function key that lets me run my generator against the file, > just like F5 lets me run my Python code; ideally, I'd like to re-purpose > the F5 key to be file-type aware. I've got a simple extension written > that uses the F6 key to "compile" my files, but two goals I've listed > seem a bit beyond me. Does anyone have any advice/pointers? Or is one > or both ideas impractical? Thanks! You might consider using eric, a python-ide written in python with the Qt-Framework. It allows plugins. Diez From joemacbusiness at yahoo.com Thu Jun 26 20:45:19 2008 From: joemacbusiness at yahoo.com (joemacbusiness at yahoo.com) Date: Thu, 26 Jun 2008 17:45:19 -0700 (PDT) Subject: Need help capturing output of re.search References: <771ef68a-d976-4f61-a3cc-7ed56fddc756@k37g2000hsf.googlegroups.com> <9757288e-0b48-46ee-8fd0-0adf36bbd710@p39g2000prm.googlegroups.com> <5fd345b7-6b32-4d45-8c55-662684adf5e9@34g2000hsf.googlegroups.com> <8e0883f9-f36d-4d62-a1a4-4cd66163a1cc@s21g2000prm.googlegroups.com> Message-ID: <9394de8d-7c81-4b86-990b-91c51dc50efc@z72g2000hsb.googlegroups.com> On Jun 26, 5:12?pm, John Machin wrote: > On Jun 27, 10:01 am, joemacbusin... at yahoo.com wrote: > > > >You may like to read this:http://www.amk.ca/python/howto/regex/ > > > This is a good resource. ?Thank you. > > Someone else pointed out that I needed to change the > > > if reCheck == "None": > > > to > > > if reCheck == None: ? # removed the "s > > "Somebody else" should indeed remain anonymous if they told you that. > Use > ? ?if reCheck is None: > or even better: > ? ?if not reCheck: > > It's not obvious from your response if you got these points: > (1) re.match, not re.search > (2) filename.startswith does your job simply and more understandably Understood. I replaced re.search with re.match (although both work) can filename.startswith be used in a conditional? ala: if filename.startswith('CC_'): processtheFile() Thanks for the great help! From workitharder at gmail.com Mon Jun 2 19:21:58 2008 From: workitharder at gmail.com (bukzor) Date: Mon, 2 Jun 2008 16:21:58 -0700 (PDT) Subject: Cast list of objects to list of strings References: <48546eb1-11f3-4a88-b1ac-97bd485a1823@k30g2000hse.googlegroups.com> <63d3d50d-0e9b-4682-b523-c2ff7d336c6a@m44g2000hsc.googlegroups.com> Message-ID: <2593e641-5dff-4f58-a4ba-b43bca07f24a@x41g2000hsb.googlegroups.com> On Jun 2, 2:56 pm, jay graves wrote: > On Jun 2, 4:02 pm, Larry Bates wrote: > > > I think what you want is: > > def write_err(*args): > > from sys import stderr > > stderr.write("\n".join([str(o) for o in args])) > > Slight nitpick. If you are using version >= 2.4 you could use a > generator expression instead of a list comprehension to avoid building > and throwing away a list. > > "\n".join(str(o) for o in args) > > http://www.python.org/dev/peps/pep-0289/ > > Very unlikely to yield a material time difference in this case but > cleaner IMO. > > ... > Jay Graves Thanks! That's exactly what I was looking for. From goldnery at gmail.com Thu Jun 12 15:04:55 2008 From: goldnery at gmail.com (Gandalf) Date: Thu, 12 Jun 2008 12:04:55 -0700 (PDT) Subject: Charset (hopefully for the last time I ask) Message-ID: now I understand my problem better so their is a good chance you manage to help me. I have a SQlite database full with ANSI Hebrew text , and program that uses WXpython Now, I use a- 'wx.TextCtrl' item to receive input from the user, and when I try to search the database he don't understand this chars. it's quite reasonable consider the fact the program set to work on UTF-8 charset, except for: 1. it doesn't work when I delete the charset too 2. when I try to use function like decode and encode it output error like this: ascii' codec can't encode characters in position 0-4: ordinal not in range(128) ascii' codec can't encode characters in position 0-2: ordinal not in range(128) 3. I don't know how to translate my DB from ANSI to UTF-8 4. when I don't use the user WX items input I can change my editor charset to ansi and it works fine Thank you all From mail at timgolden.me.uk Thu Jun 5 14:58:35 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 05 Jun 2008 19:58:35 +0100 Subject: Question regarding re module In-Reply-To: <9165ed46-4077-44a8-ae93-ceafda975f04@56g2000hsm.googlegroups.com> References: <9165ed46-4077-44a8-ae93-ceafda975f04@56g2000hsm.googlegroups.com> Message-ID: <4848375B.6030702@timgolden.me.uk> Paul McGuire wrote: > On Jun 5, 7:11 am, Tomohiro Kusumi > wrote: >>> It could be that the result overloads the __getattr__-method to delegate >>> calls to some object. Thus it's not part of the outer instance. > > Didn't I read that Py3 will support a __dir__ method so that classes > *could* report such pseudo-attributes in response to dir? It's already there in 2.6: ... class X (object): ... def __init__ (self, a, b): ... self.a = a ... self.b = b ... def __dir__ (self): ... return ['a', 'b', 'c'] ... >>> dir (X (1, 2)) ['a', 'b', 'c'] >>> TJG From teh.saber at gmail.com Thu Jun 26 05:24:08 2008 From: teh.saber at gmail.com (teh_sAbEr) Date: Thu, 26 Jun 2008 02:24:08 -0700 (PDT) Subject: Working with the Windows Registry References: <49beca2a-9d6c-40a2-a7c3-bf1cf376df0a@l28g2000prd.googlegroups.com> Message-ID: <11e16b1f-0770-4932-994e-1ac3bc8e17e4@c19g2000prf.googlegroups.com> Great! It works properly now but I have one more question, would anyone know how to get the changes to take effect immediately? Like some sort of Python way to force the desktop to reload? AFAIK the only way that'll happen is if I use the Display Properties dialog box. The Registry value is changed properly, its just I don't think the changes will take effect until I restart. From theo at van-werkhoven.nl.invalid Thu Jun 12 15:45:18 2008 From: theo at van-werkhoven.nl.invalid (Theo v. Werkhoven) Date: Thu, 12 Jun 2008 21:45:18 +0200 Subject: time.clock() or Windows bug? References: <0uep44hpn8rupgr15a135f37q346tif9v2@4ax.com> Message-ID: The carbonbased lifeform Tim Roberts inspired comp.lang.python with: > Nick Craig-Wood wrote: >> >>Hmmm, 10,000,000 cycles (40 ms @2.5GHz) is nowhere near the ~90,000 >>second jump in time.clock() output reported by the OP. I wonder if >>there could be a different cause? > > Just wild theorizing, but it's possible that they are actually getting a > negative delta, and some kind of signed/unsigned manipulation produces the > 90,000 number. Actually, in previous runs I /did/ see negative timestamps using time.clock(). Bizar. Theo -- theo at van-werkhoven.nl ICQ:277217131 SuSE Linux linuxcounter.org: 99872 Jabber:muadib at jabber.xs4all.nl AMD XP3000+ 1024MB "ik _heb_ niets tegen Microsoft, ik heb iets tegen de uitwassen *van* Microsoft" From yardennis at gmail.com Thu Jun 26 14:12:34 2008 From: yardennis at gmail.com (yardennis) Date: Thu, 26 Jun 2008 11:12:34 -0700 (PDT) Subject: python interface to Firefox and Thunderbird Message-ID: <6c5dab9f-3521-4434-8100-65ad1fe207d0@i36g2000prf.googlegroups.com> Hi, I need python moudles that can auto install python 2.5 (web install or a EXE file) auto download and install Firefox3 and Thunderbird 2 auto import from IE 6, 7 and OE 5,6 and Outlook read contacts and emails from Thunderbird store read Firefox 3 bookmarks, history, cookies and password Can anyone point to a open source solution ? If you know of any freelancer that can help me develop the module please let me know. Thanks Dennis yardennis at gmail dot com From miki.tebeka at gmail.com Mon Jun 23 01:39:05 2008 From: miki.tebeka at gmail.com (Miki) Date: Sun, 22 Jun 2008 22:39:05 -0700 (PDT) Subject: rightclick-copy in IDLE? References: <6b40b216-65b8-40da-9072-7b3249086c7c@m44g2000hsc.googlegroups.com> Message-ID: <7e57e15e-2a85-47b4-a999-e4a85c02eb39@x1g2000prh.googlegroups.com> > when i rightclick in python idle i get set breakpoint or something. > > n options i dont find a way to change to the normal copy/paste options. Under "Preferences ..." menu you'll find "Keys" tab, there you can change the keys bindings to whatever you want. HTH, -- Miki http://pythonwise.blogspot.com From d.a.abernathy at gmail.com Mon Jun 9 16:36:41 2008 From: d.a.abernathy at gmail.com (dj) Date: Mon, 9 Jun 2008 13:36:41 -0700 (PDT) Subject: time module methods give an am or pm value ? References: <2309efff-5c6b-4434-a2cd-01c3fee86fee@l42g2000hsc.googlegroups.com> Message-ID: <55eb5dc1-3040-43dd-84ab-7fbb66d0248e@d77g2000hsb.googlegroups.com> On Jun 7, 9:24 am, "Mark Tolonen" wrote: > "dj" wrote in message > > news:2309efff-5c6b-4434-a2cd-01c3fee86fee at l42g2000hsc.googlegroups.com... > > > Hello again, > > > Does anyone know which method in the time module will generate and am > > or pm ? > > If none of the method will do this for me. Can I produce the value on > > my own ? > > Any suggestions ? > >>> from time import * > >>> strftime('%I:%M:%S %p',localtime(time())) > '07:23:24 AM' > >>> strftime('%I:%M:%S %p',gmtime(time())) > > '02:23:39 PM' > > -Mark Hello Mark, Thank you very much. I finally found this function in the documentation. From roopesh.raj at gmail.com Sat Jun 28 02:48:13 2008 From: roopesh.raj at gmail.com (Roopesh) Date: Fri, 27 Jun 2008 23:48:13 -0700 (PDT) Subject: Problems with file IO in a thread, and shutil References: <38f798c9-983f-4f0c-a281-d2a89e738590@v1g2000pra.googlegroups.com> Message-ID: <3cb1b183-5a89-40a7-9ef8-484416eac779@y22g2000prd.googlegroups.com> > Maybe it's a Windows service, eg the indexing service or generating > thumbnails. Anyway, retrying after a delay would still be worth it. Yes, this thing works :-) Thanks a lot. Thanks Roopesh From Lie.1296 at gmail.com Tue Jun 10 11:20:51 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 10 Jun 2008 08:20:51 -0700 (PDT) Subject: Does the python library of Google Data API is truly free? References: <3ac654b2-61b4-44ce-8e03-75f2344d5869@s50g2000hsb.googlegroups.com> <6fb57ab1-b0d2-4b7d-93c1-b919ca0e51a0@i36g2000prf.googlegroups.com> <3a296d00-d4e0-4f03-b6b3-bef4c5d628dd@x35g2000hsb.googlegroups.com> <6b5mloF3aeui4U1@mid.uni-berlin.de> <18115776-edf7-41b8-a5e9-639847c57a6a@x41g2000hsb.googlegroups.com> Message-ID: <851da24f-1681-46ff-9df4-c12941ad4078@v26g2000prm.googlegroups.com> On Jun 10, 2:49?pm, Kless wrote: > On 9 jun, 22:46, "Diez B. Roggisch" wrote: > > > Kless schrieb: > > > > On 9 jun, 21:40, Lie wrote: > > >> Do you notice that the terms are for the SERVICE not for the SOFTWARE. > > >> The terms for the service is quite reasonable, as I see it. > > >> The software itself is governed by the Apache License 2.0, detailed > > >> here:http://www.apache.org/licenses/LICENSE-2.0 > > > > Well, it's used a free license to access to a service that is not free > > > -it's owner and too restrictive-. And it isn't nothing reasonable that > > > Google get many rights about your content, and that you have not any > > > right about the rest of the content. > > > > This goes against the free software, considering that a service is > > > software. > > > This is nonsense. If a hosting provider offers you free hosting based on > > linux - and then goes out of business or is forced to charge money - do > > you say "that's against free software?" > > I don't speak about hosting else rights about data, data that are > entered by people: > This shows you have not made any efforts to understand the difference between software and service: SOFTWARE != SERVICE. The freedom and the restriction of the software is governed by the Apache License 2.0. On the other hand, the freedom and the restriction of the service is governed by this rules, which has a pretty reasonable terms for a service. > "By submitting, posting or displaying the content you give > Google a perpetual, irrevocable, worldwide, royalty-free, and non- > exclusive license to reproduce, adapt, modify, translate, publish, > publicly perform, publicly display and distribute any Content which > you submit, post or display on or through, the Services..." You have cut an important line to support your proposition: This license is for the sole purpose of enabling Google to display, distribute and promote the Services and may be revoked for certain Services as defined in the Additional Terms of those Services. > "You agree that this license includes a right for Google to make > such Content available to other companies, organizations or > individuals with whom Google has relationships for the provision of > syndicated services..." Without this line, there is no way the service could work, since basically the service (GData) is all about making your data available to other people. > > Or if they prohibit you to host malicious, offending or otherwise > > problematic content served by the free apache - is that "against free > > software?" > > Please, don't be demagogue. > > > A service is a service. It is offered as is, under whatever conditions > > the provider likes it. > > A service or web service to follows being software. A software where > is more easy to add restrictions, in this case those restrictions goes > against the freedoms of the free software. Some companies advertise Software as a Service, in those case the Service is equivalent to the Software. In this case, the service is GData Service and the Software is the GData API. > > Offering a convenient way to access the service using a FOSS license is > > good style. But you aren't forced to use that, you can write your own. > > But that doesn't change the terms and conditions of the service itself. > > Offering access via Apache 2.0 -wich is not compatible with GPLv2- to > a non-free service is a mortal trap where people are falling. Whether Apache 2.0 is GPLv2 compatible or not is irrelevant, GPL is only one type of license, no more no less, it's not the Holy Grail of free software spirit. The fact that many other softwares use GPL license is because the license has been designed for general use and many open source groups doesn't really have the knowledge, capability, and/or time to create their own license (creating a license is not as easy as it seems), most doesn't even care what their software is licensed on and their exact terms. The use of a well-known license also made it easy for the users to know the license he's agreeing to without reading and reading and reading a license again and again and again. From maehhheeyy at gmail.com Tue Jun 10 15:53:51 2008 From: maehhheeyy at gmail.com (maehhheeyy) Date: Tue, 10 Jun 2008 12:53:51 -0700 (PDT) Subject: can't assign to literal Message-ID: this is stopping my program from running properly. is there something wrong in my code when that happens? From nospam at nospam.com Mon Jun 2 18:42:18 2008 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 03 Jun 2008 00:42:18 +0200 Subject: Checking each item in m.group()? References: <47412fe8-ba45-4f66-8064-75137c022339@m36g2000hse.googlegroups.com> Message-ID: On Mon, 2 Jun 2008 12:06:21 -0700 (PDT), Matimus wrote: >Here is a brief example. Note that this code is very insecure and >susceptible to a SQL injection attack. Hopefully these csv files are >from a trusted source. Yes they are, and this script will only run on my PC, so it doesn't need to be more secure than this. >sql = "INSERT INTO mytable (col1, col2) VALUES ('%s','%s')"%tuple( > (c, "NULL")[c == ''] for c in m.groups() > ) > I don't understand this syntax :-/ >Also, check out the csv module for parsing your csv file. Will do. Thank you. From jgardner at jonathangardner.net Thu Jun 26 19:11:41 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 26 Jun 2008 16:11:41 -0700 (PDT) Subject: ask for a RE pattern to match TABLE in html References: <6a4f17690806260653i136681bdsabe0f6bb1dfab67b@mail.gmail.com> Message-ID: <62f752f3-d840-42de-a414-0d56d15d7c5a@w4g2000prd.googlegroups.com> On Jun 26, 3:22?pm, MRAB wrote: > Try something like: > > re.compile(r'.*?
    1. the curd of milk separated from the whey and prepared in many ways as a food.
    ', re.DOTALL) So you would pick up strings like "
    foo
    "? I doubt that is what oyster wants. From sjmachin at lexicon.net Mon Jun 30 20:01:41 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 30 Jun 2008 17:01:41 -0700 (PDT) Subject: The Yield statement References: Message-ID: <33686323-25e3-4442-9667-cb098e1686d9@p39g2000prm.googlegroups.com> On Jul 1, 8:31 am, Alex Bryan wrote: > Okay, so i don't really understand the Yield thing and i know it is > useful. I've read a few things about it but it is all programming > jargon and so basically it is hard for me to understand. So can anyone > give me a description or link me to a site that has a good definition > and/or examples of it? If you could I would really appreciate it. Try this: http://www.dabeaz.com/generators/ (ignore the "tricks" word in the title) From tjreedy at udel.edu Sun Jun 15 15:01:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 15 Jun 2008 15:01:03 -0400 Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com><3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> Message-ID: wrote in message news:1257aa24-14fa-426e-8019-262984c70633 at 2g2000hsn.googlegroups.com... |> How did you determine that standard python floats are not good enough? | I have a physical system set up in which a body is supposed to | accelerate and to get very close to lightspeed, while never really |attaining it. Just a thought. You might do better if you can rearrange your equations in terms of c-v instead of v. Letting c=1, you cannot accutrately express v = .99999999999999999999 in Python, but can easily express 1-v = .00000000000000000001. And so on. tjr From bruno.desthuilliers at gmail.com Tue Jun 24 14:47:58 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Tue, 24 Jun 2008 11:47:58 -0700 (PDT) Subject: shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": References: Message-ID: On 24 juin, 20:32, cirfu wrote: > if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": > > cant i write something like: > if char in "[A-Za-z]": > Nope. But there are other solutions. Here are two: # 1 import string if char in string.letters: print "yay" # 2 import re exp = re.compile(r'[A-Za-z]') if exp.match(char): print "yay" From srhegde at gmail.com Fri Jun 27 12:26:46 2008 From: srhegde at gmail.com (python_enthu) Date: Fri, 27 Jun 2008 09:26:46 -0700 (PDT) Subject: Simple regular expression References: <47031cc4-2b5e-43b3-9338-cf4a7b4c1568@d45g2000hsc.googlegroups.com> <03a59caa$0$3254$c3e8da3@news.astraweb.com> Message-ID: On Jun 27, 11:05?am, "John Salerno" wrote: > "python_enthu" wrote in message > > news:47031cc4-2b5e-43b3-9338-cf4a7b4c1568 at d45g2000hsc.googlegroups.com... > > >I am trying this.. what is wrong in this.. > > > IDLE 1.2.2 > >>>> import re > >>>> a="my name is fname lname" > >>>> p=re.compile('name') > >>>> m=p.match (a) > >>>> print p.match(a) > > None > > ? ? ? match( string[, pos[, endpos]]) > > If zero or more characters at the beginning of string match this regular > expression, return a corresponding MatchObject instance. Return None if the > string does not match the pattern; note that this is different from a > zero-length match. > > ? ? ? search( string[, pos[, endpos]]) > > Scan through string looking for a location where this regular expression > produces a match, and return a corresponding MatchObject instance. Return > None if no position in the string matches the pattern; note that this is > different from finding a zero-length match at some point in the string. Thanks John Salerno and John Machin, I am used to perl. So I guess I am better of using re.search instead of re.match BTW, is re.search('string') equivalent to re.match ('^string') From mal at egenix.com Wed Jun 4 04:43:14 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 04 Jun 2008 10:43:14 +0200 Subject: Keep a script running in the background In-Reply-To: References: <210b7fc6-ed52-461d-8b53-455e247d7a29@e39g2000hsf.googlegroups.com> Message-ID: <484655A2.6080701@egenix.com> On 2008-06-04 01:33, Guillermo wrote: > These are the basic requirements: > > Script A must keep a dictionary in memory constantly and script B must > be able to access and update this dictionary at any time. Script B > will start and end several times, but script A would ideally keep > running until it's explicitly shut down. > > I have the feeling the way to do this is Python is by pickling the > dict, but I need the method that gives the best performance. That's > why I'd rather want to keep it in memory, since I understand pickling > involves reading from and writing to disk. > > I'm using SQLite as a database. But this dict is an especial index > that must be accessed at the highest speed possible. If you're on Unix, it's easiest to have script A implement a signal handler. Whenever it receives a signal, it rereads the pickled dict from the disk. Script B then writes a new revision of the dict and sends the signal to script A. Alternatively, you could use an on-disk dictionary like e.g. mxBeeBase: https://www.egenix.com/products/python/mxBase/mxBeeBase/ -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jun 04 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania 32 days to go :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From george.sakkis at gmail.com Mon Jun 30 13:41:17 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 30 Jun 2008 10:41:17 -0700 (PDT) Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> Message-ID: <6a8d3b30-b7d6-4f41-b491-0cfc44e46109@27g2000hsf.googlegroups.com> On Jun 30, 1:19 pm, Mike wrote: > On Jun 30, 10:57 am, Bruno Desthuilliers > 42.desthuilli... at websiteburo.invalid> wrote: > > > Some (if not most) templating systems use their own mini-language to > > handle presentation logic. > > IMHO this is the funniest (worst) part of all this 'templating' > buss :) > It reminds me the good old slogan: "Have you invented your own GUI > library yet?" > > > > > The meme "thou shall not mix domain logic with presentation" is very > > often misunderstood as "you must not have anything else than html in > > templates", which is just plain non-sense. Even declarative templating > > systems (cf Has's post) require some special (ie: non standard) stuff to > > work. > > > > Or could it just be that > > > this is a *good* way to mix HTML and Python, and there are other ways > > > which may be bad? > > > Bingo. > > Then what is so *good* about it, why embedding HTML into Python is not > good? Because _typically_ a web template consists of mostly HTML, with relatively little presentational logic and (ideally) no business logic. Now, if all one wants to do is a quick and dirty way to, say, view a log file in the browser, a separate template is probably an overkill; there's nothing wrong with something like "for line in logfile: print cgi.escape(line.strip()) + '
    '". It's a matter of relative frequencies which language is the embedded one. George From gh at ghaering.de Tue Jun 10 12:32:44 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 10 Jun 2008 18:32:44 +0200 Subject: problems with opening files due to file's path In-Reply-To: <17759531.post@talk.nabble.com> References: <17759531.post@talk.nabble.com> Message-ID: Alexnb wrote: > Okay, so what I want my program to do it open a file, a music file in > specific, and for this we will say it is an .mp3. Well, I am using the > system() command from the os class. [...] > > system("\"C:\Documents and Settings\Alex\My Documents\My > Music\Rhapsody\Bryanbros\Weezer\(2001)\04 - Island In The Sun.wma\"") > [...] Try os.startfile() instead. It should work better. -- Gerhard From mail at timgolden.me.uk Thu Jun 12 03:51:53 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 12 Jun 2008 08:51:53 +0100 Subject: How to set directory in save as combo box In-Reply-To: <01f201c8cc3f$2f6ba990$2fc513ac@pwit.com> References: <01f201c8cc3f$2f6ba990$2fc513ac@pwit.com> Message-ID: <4850D599.6020609@timgolden.me.uk> gopal mishra wrote: > In 'save as' dialog of window application, I am trying to set the path in > 'save in' combo box using python win32 programming. > How we can set the directory in the 'save in' combo box. There are several ways to display a "Save As" dialog. Can you post [a minimal version of] the code you're using so we can see what you're doing, please? TJG From lepto.python at gmail.com Thu Jun 26 06:57:40 2008 From: lepto.python at gmail.com (oyster) Date: Thu, 26 Jun 2008 18:57:40 +0800 Subject: instructions on adding external Tcl/Tk widget into Tkinter? Message-ID: <6a4f17690806260357j4bfe9140vf1084436d371a2e8@mail.gmail.com> It is so funny that the official GUI lib for python is Tkinter, but I cannot find an articles which explains indetail how can we use thounsands of Tcl/Tk widget in Tkinter. For example, I have download the dll at http://www.hwaci.com/sw/tkhtml/index.html, renamed it to tkhtml12.dll and put it in H:\python25\bin\tcl\Tkhtml1.2\ then I edited a h:\python25\bin\tcl\Tkhtml1.2\pkgIndex.tcl file: [**********pkgIndex.tcl********] if {![package vsatisfies [package provide Tcl] 8]} {return} if {[string compare $::tcl_platform(platform) windows]} {return} if {[info exists ::tcl_platform(debug)]} { package ifneeded Tkhtml 1.2.3 [list load [file join $dir Tkhtml12g.dll] Tkhtml] } else { package ifneeded Tkhtml 1.2.3 [list load [file join $dir Tkhtml12.dll] Tkhtml] } [/**********pkgIndex.tcl********] but http://tix.sourceforge.net/Tixapps/src/Python/TkHtml.py says [*********says*********] attempt to provide package Tkhtml 1.2.3 failed: package Tkhtml 0.0 provided instead [/*********says*********] From ncoghlan at gmail.com Wed Jun 4 07:14:04 2008 From: ncoghlan at gmail.com (NickC) Date: Wed, 4 Jun 2008 04:14:04 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> Message-ID: <911bd81e-1342-4870-8b7a-f706c5dea01b@a32g2000prf.googlegroups.com> On May 26, 2:49 pm, "Russ P." wrote: > I am also bothered a bit by the seeming inconsistency of the rules for > the single underscore. When used at file scope, they make the variable > or function invisible outside the module, but when used at class > scope, the "underscored" variables or functions are still fully > visible. For those who claim that the client should be left to decide > what to use, why is the client prohibited from using underscored > variables at file scope? They aren't - the only thing that won't see the underscore prefixed names is "from x import *". If you do "import x" instead, all the underscored names will be accessible as attributes of the module. From sjmachin at lexicon.net Wed Jun 4 07:45:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 4 Jun 2008 04:45:15 -0700 (PDT) Subject: Zipfile module errors References: <1bea3f60-5866-4ecb-a2a2-51f7130f03c8@y21g2000hsf.googlegroups.com> Message-ID: <8a2a1e8d-cde2-45f4-9329-407e0c2980c8@l28g2000prd.googlegroups.com> On Jun 4, 8:06 pm, jwesonga wrote: > Hi, > > I have a python script that supposed to go through a folder, pick the > zipped files, unzip them and process the data inside. I'm not sure > where i'm going wrong with this script because it all seems correct: Nothing is ever as it seems. Let's try to work backwards from the error message ... and we don't need your magnificent script, just the traceback will do for now, so: [ big snip] > > The error I keep getting is: > > Traceback (most recent call last): > File "processor3.py", line 124, in ? > unzip(infolder) > File "processor3.py", line 53, in unzip The error says that you are trying to seek 22 bytes backwards from the end of a file that you presume is a zip file, and this is deemed to be invalid. Hypotheses: (1) zipfile.py is buggy (2) your file is less than 22 bytes long. Let's park hypothesis 1 for the moment. Insert the following code before the call to zipfile.ZipFile: print "trying to unzip %r whose size is %d bytes" \ % (one, os.stat(one).st_size) and tell us your conclusions. > zfile = zipfile.ZipFile(one,'r') > File "/usr/lib/python2.4/zipfile.py", line 210, in __init__ > self._GetContents() > File "/usr/lib/python2.4/zipfile.py", line 230, in _GetContents > self._RealGetContents() > File "/usr/lib/python2.4/zipfile.py", line 240, in _RealGetContents > endrec = _EndRecData(fp) > File "/usr/lib/python2.4/zipfile.py", line 83, in _EndRecData > fpin.seek(-22, 2) # Assume no archive comment. > IOError: [Errno 22] Invalid argument P.S. Printing the contents of filelist immediately after it's been created might be a good idea. You say "pick the zipped files" but the only condition I see is a test using os.path.isdir. HTH, John From brendon at christian.net Thu Jun 19 03:05:13 2008 From: brendon at christian.net (Brendon Costa) Date: Thu, 19 Jun 2008 00:05:13 -0700 (PDT) Subject: How do i : Python Threads + KeyboardInterrupt exception References: <089f56d2-5e44-4161-b580-84881717bd05@w4g2000prd.googlegroups.com> <6cfbfaa2-293f-41d3-b544-fd47f05d0d36@j33g2000pri.googlegroups.com> Message-ID: I tested this a bit more. My windows example was incorrect. It should have used CTRL_C_EVENT. But even then, the problem is that the process will also close the console window from which it was called because of the 0. Also this requires that the process actually have a console and is not a GUI application. Is there some other method rather than a blocking "for line in fin:" that i can use for reading from a file like device that plays nicely with other threads asynchronously waking it up? Sorry for all the posts. I am giving updates as i look further into the problem. From martin at v.loewis.de Tue Jun 24 02:34:02 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Jun 2008 08:34:02 +0200 Subject: Is there any way to find out sizeof an object In-Reply-To: References: Message-ID: <4860955a$0$9759$9b622d9e@news.freenet.de> > I have written a class which has some attributes. I want to know how > do i find out the size of an instance of this class?? > class T(object): > def __init__(self, fn_name, *args, **kwds): > self.fn_name = fn_name > self.args = args > self.kwds = kwds In Python 2.6, you can use sys.getsizeof to find out how large an object is. Notice that this is a really tricky question: Assuming you have t = T(1,2,3, a="hello", b="world") then you should certainly consider the size atleast sys.getsizeof(t) + sys.getsizeof(t.__dict__) But then you also have the attribute values (i.e. the tuple resp. dict), which you might want to account for: + sys.getsizeof(t.args) + sys.getsizeof(t.dict) Now, what to do about the sizes of the various items in the dict and the tuple? One could do total = ... # from above for o in t.args: total+=sys.getsizeof(o) for k,v in t.kwds.items(): total+=sys.getsizeof(k)+sys.getsizeof(v) However, that might be accounting too much, since the at least the keys of the dict are shared across other dicts. Likewise, the integers are shared, and the string literals (as written above) would be shared if the very same T constructor is run twice. In short, "size of an instance" can't be answered without a specific instance (i.e. you can't answer it in advance for all instances), plus even for a single instance, its difficult to answer. Regards, Martin From dstromberglists at gmail.com Thu Jun 5 00:59:38 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Thu, 5 Jun 2008 04:59:38 +0000 (UTC) Subject: sed to python: replace Q References: <48180348$0$34534$742ec2ed@news.sonic.net> <4820714b$0$34544$742ec2ed@news.sonic.net> Message-ID: On Tue, 06 May 2008 14:55:07 +0000, Raymond wrote: >>Another approach is to use the split() function in "re" module. > > Ah ha, thar's the disconnect. Thanks for all the pointers, my def is > now working. Still don't understand the logic behind this design > though. I mean why would any programming language have separate search > or find functions, one for regex and and another for non-regex based > pattern matching? > > Aren't sed, awk, grep, and perl the reference implementations of search > and replace? They don't have non-regex functions, why does Python? > Wouldn't it be a lot simpler to use a flag, like grep's '-f', to change > the meaning of a search string to be literal? > > My other gripe is with the kludgy object-oriented regex functions. > Couldn't these be better implemented in-line? Why should I, as a coder, > have to 're.compile()' when all the reference languages do this at > compile time, from a much more straightforward and easy to read in-line > function... > > Raymon Hm. Are regex's first class citizens in these languages, like they are in python? And from a language design perspective, isn't it much cleaner to put regex's into just another portion of the runtime rather than dumping it into the language definition proper? It does actually make sense - to have a string method do a string thing, and to have a regex method do a regex thing. And while command line options are pretty nice when done well, there's nothing in particular stopping one from using arguments with defaults in python. I'm good with sed and grep, though I never got into awk much - perhaps a small mistake. When it came to perl, I skipped it and went directly to python, and have never regretted the decision. Python's got a much more coherent design than perl, most certainly, and more than sed as well. awk's not that bad though. And grep's nice and focused - I quite like grep's design. From lists at cheimes.de Sat Jun 14 09:32:20 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 14 Jun 2008 15:32:20 +0200 Subject: numpy: handling float('NaN') different in XP vs. Linux In-Reply-To: <17835502.post@talk.nabble.com> References: <17835502.post@talk.nabble.com> Message-ID: John [H2O] wrote: > I have a script: > > from numpy import float > OutD=[] > v=['3','43','23.4','NaN','43'] > OutD.append([float(i) for i in v[1]]) > > > On linux: > Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > [john at andLinux analysis]$ python jnk.py > [[3.0, 43.0, 23.399999999999999, nan, 43.0]] > > On XP: > Python 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > C:\analysis>C:\Python25\python.exe jnk.py > Traceback (most recent call last): > File "jnk.py", line 4, in > OutD.append([float(i) for i in v]) > ValueError: invalid literal for float(): NaN I've fixed the issue for Python 2.6 and 3.0 a while ago. Mark and I have spent a lot of time on fixing several edge cases regarding inf, nan and numerical unsound functions in Python's math und cmath module. Christian From sajmikins at gmail.com Thu Jun 19 19:10:09 2008 From: sajmikins at gmail.com (Simon Forman) Date: Thu, 19 Jun 2008 16:10:09 -0700 (PDT) Subject: Simple and safe evaluator References: <1de31143-7d8e-42e9-ae9d-8b0a0274ddc3@e53g2000hsa.googlegroups.com> Message-ID: On Jun 16, 8:32?pm, bvdp wrote: > sween... at acm.org wrote: > > On Jun 17, 8:02 am, bvdp wrote: > > >> Thanks. That was easy :) > > >>> The change to the _ast version is left as an exercise to the reader ;) > >> And I have absolutely no idea on how to do this. I can't even find the > >> _ast import file on my system. I'm assuming that the _ast definitions > >> are buried in the C part of python, but that is just a silly guess. > > >> Bob. > > > If you just need numeric expressions with a small number of functions, > > I would suggest checking the expression string first with a simple > > regular expression, then using the standard eval() to evaluate the > > result. ?This blocks the attacks mentioned above, and is simple to > > implement. ?This will not work if you want to allow string values in > > expressions though. > > > import re > > def safe_eval( expr, safe_cmds=[] ): > > ? ?toks = re.split( r'([a-zA-Z_\.]+|.)', expr ) > > ? ?bad = [t for t in toks if len(t)>1 and t not in safe_cmds] > > ? ?if not bad: > > ? ? ? ? ? ?return eval( expr ) > > Yes, this appears to be about as good (better?) an idea as any. > Certainly beats writing my own recursive decent parser for this :) > > And it is not dependent on python versions. Cool. > > I've run a few tests with your code and it appears to work just fine. > Just a matter of populating the save_cmds[] array and putting in some > error traps. Piece of cake. And should be fast as well. > > Thanks!!! > > Bob. FWIW, I got around to implementing a function that checks if a string is safe to evaluate (that it consists only of numbers, operators, and "(" and ")"). Here it is. :) import cStringIO, tokenize def evalSafe(source): ''' Return True if a source string is composed only of numbers, operators or parentheses, otherwise return False. ''' try: src = cStringIO.StringIO(source).readline src = tokenize.generate_tokens(src) src = (token for token in src if token[0] is not tokenize.NL) for token in src: ttype, tstr = token[:2] if ( tstr in "()" or ttype in (tokenize.NUMBER, tokenize.OP) and not tstr == ',' # comma is an OP. ): continue raise SyntaxError("unsafe token: %r" % tstr) except (tokenize.TokenError, SyntaxError): return False return True for s in ( '(1 2)', # Works, but isn't math.. '1001 * 99 / (73.8 ^ 88 % (88 + 23e-10 ))', # Works '1001 * 99 / (73.8 ^ 88 % (88 + 23e-10 )', # Raises TokenError due to missing close parenthesis. '(1, 2)', # Raises SyntaxError due to comma. 'a * 21', # Raises SyntaxError due to identifier. 'import sys', # Raises SyntaxError. ): print evalSafe(s), '<--', repr(s) From jeffober at gmail.com Sun Jun 22 19:10:35 2008 From: jeffober at gmail.com (Jeff) Date: Sun, 22 Jun 2008 16:10:35 -0700 (PDT) Subject: listcomprehension, add elements? References: <13452c64-ef91-49a2-bb73-7f33c088660e@d45g2000hsc.googlegroups.com> Message-ID: <324ebd7d-2024-404e-b392-5c77c43366f3@25g2000hsx.googlegroups.com> On Jun 22, 6:32?pm, cirfu wrote: > [a+b for a,b in zip(xrange(1,51), xrange(50,0,-1))] > > [51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, > 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, > 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51] > > i want to add all the elemtns a s well. can i do this all in a > listcomprehension? > > i can do this ofc: > reduce(lambda x,y:x+y,[a+b for a,b in zip(xrange(1,51), > xrange(50,0,-1))]) > > but reduce is a functional way of doing it, what is the more pythonic > way of doing this? Nothing that would be more concise than reduce. Anything you did with iteration would just mimic reduce in any case. Jeff Ober artfulcode.net From george.sakkis at gmail.com Fri Jun 20 16:54:09 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 20 Jun 2008 13:54:09 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> <8711b1fe-8256-4f6f-a3d7-f99f44eb23b0@e53g2000hsa.googlegroups.com> Message-ID: <195ccfd2-3751-44ac-af5e-22c77f8999b7@k37g2000hsf.googlegroups.com> On Jun 20, 3:44 pm, eliben wrote: > On Jun 20, 3:19 pm, George Sakkis wrote: > > > > > On Jun 20, 8:03 am, eliben wrote: > > > > On Jun 20, 9:17 am, Bruno Desthuilliers > > > 42.desthuilli... at websiteburo.invalid> wrote: > > > > eliben a ?crit :> Hello, > > > > > > In a Python program I'm writing I need to dynamically generate > > > > > functions[*] > > > > > (snip) > > > > > > [*] I know that each time a code generation question comes up people > > > > > suggest that there's a better way to achieve this, without using exec, > > > > > eval, etc. > > > > > Just to make things clear: you do know that you can dynamically build > > > > functions without exec, do you ? > > > > Yes, but the other options for doing so are significantly less > > > flexible than exec. > > > > > > But in my case, for reasons too long to fully lay out, I > > > > > really need to generate non-trivial functions with a lot of hard-coded > > > > > actions for performance. > > > > > Just out of curiousity : could you tell a bit more about your use case > > > > and what makes a simple closure not an option ? > > > > Okay. > > > > I work in the field of embedded programming, and one of the main uses > > > I have for Python (and previously Perl) is writing GUIs for > > > controlling embedded systems. The communication protocols are usually > > > ad-hoc messages (headear, footer, data, crc) built on top of serial > > > communication (RS232). > > > > The packets that arrive have a known format. For example (YAMLish > > > syntax): > > > > packet_length: 10 > > > fields: > > > - name: header > > > offset: 0 > > > length: 1 > > > - name: time_tag > > > offset: 1 > > > length: 1 > > > transform: val * 2048 > > > units: ms > > > - name: counter > > > offset: 2 > > > length: 4 > > > bytes-msb-first: true > > > - name: bitmask > > > offset: 6 > > > length: 1 > > > bit_from: 0 > > > bit_to: 5 > > > ... > > > > This is a partial capability display. Fields have defined offsets and > > > lengths, can be only several bits long, can have defined > > > transformations and units for convenient display. > > > > I have a program that should receive such packets from the serial port > > > and display their contents in tabular form. I want the user to be able > > > to specify the format of his packets in a file similar to above. > > > > Now, in previous versions of this code, written in Perl, I found out > > > that the procedure of extracting field values from packets is very > > > inefficient. I've rewritten it using a dynamically generated procedure > > > for each field, that does hard coded access to its data. For example: > > > > def get_counter(packet): > > > data = packet[2:6] > > > data.reverse() > > > return data > > > > This gave me a huge speedup, because each field now had its specific > > > function sitting in a dict that quickly extracted the field's data > > > from a given packet. > > > It's still not clear why the generic version is so slower, unless you > > extract only a few selected fields, not all of them. Can you post a > > sample of how you used to write it without exec to clarify where the > > inefficiency comes from ? > > > George > > The generic version has to make a lot of decisions at runtime, based > on the format specification. > Extract the offset from the spec, extract the length. Is it msb- > first ? Then reverse. Are specific bits required ? If so, do bit > operations. Should bits be reversed ? etc. So you are saying that for example "if do_reverse: data.reverse()" is *much* slower than "data.reverse()" ? I would expect that checking the truthness of a boolean would be negligible compared to the reverse itself. Did you try converting all checks to identity comparisons with None ? I mean replacing every "if compile_time_condition:" in a loop with compile_time_condition = compile_time_condition or None for i in some_loop: if compile_time_condition is None: ... It's hard to believe that the overhead of identity checks is comparable (let alone much higher) to the body of the loop for anything more complex than "pass". George From bearophileHUGS at lycos.com Mon Jun 16 06:24:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 16 Jun 2008 03:24:16 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> Message-ID: <08482987-b105-49cb-b8ea-0d469f6dc641@k13g2000hse.googlegroups.com> Oh, very good, better late than never. This is my pure Python version, it performs get, set and del operations too in O(1): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498195 Working with C such data structure becomes much faster, because it can use true pointers. Then another data structure that may be named SortedDict can be created, that keeps items in their natural order (instead of the insertion order). Bye, bearophile From roopesh.raj at gmail.com Thu Jun 26 03:06:03 2008 From: roopesh.raj at gmail.com (Roopesh) Date: Thu, 26 Jun 2008 00:06:03 -0700 (PDT) Subject: Problems with file IO in a thread, and shutil References: Message-ID: <38f798c9-983f-4f0c-a281-d2a89e738590@v1g2000pra.googlegroups.com> Thanks for the reply. I did testing in a clean system, were anti virus/ spyware is not installed. It still gave this problem, in say 1 out of 1000 cases. By any chance would it be possible that the Windows OS has not completed writing to the file even after file.flush() and file.close() is called? Thanks Roopesh From socyl at 987jk.com.invalid Fri Jun 6 18:04:26 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 6 Jun 2008 22:04:26 +0000 (UTC) Subject: How to send a POST request? References: Message-ID: In kj writes: >Hi. Sorry for this very clueless question, but how does one write >in Python an HTTP client that can send a POST request? The modules >I've found (e.g. urllib, urllib2), as far as I can tell, seem to >be limited to GET requests. (I could be wrong though; please >correct me if this is so.) Sorry, my mistake. I now see that urllib2 handles POSTs too. kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From fsenkel at lynx.neu.edu Thu Jun 19 16:37:47 2008 From: fsenkel at lynx.neu.edu (monkeyboy) Date: Thu, 19 Jun 2008 13:37:47 -0700 (PDT) Subject: Simple Class/Variable passing question Message-ID: <8a0cb1c6-8b54-4123-8f94-c0e0d465a1e9@e39g2000hsf.googlegroups.com> Hello, I'm new to python, and PythonCard. In the code below, I'm trying to create a member variable (self.currValue) of the class, then just pass it to a simple function (MainOutputRoutine) to increment it. I thought Python "passed by reference" all variables, but the member variable doesn't seem to be incremented. If I make the function just increment the member variable directly, without passing it in, it works fine? In the code below, "self.currValue" stays at 5, and value evaluates to 1? Any insight would be appreciated... class TestModel(model.Background): def on_initialize(self,event): self.currValue = 5 def on_startBtn_mouseClick(self, event): self.MainOutputRoutine(self.currValue) self.OutputRoutine(self.currValue) def OutputRoutine(self,value): self.components.txtBox1.text = str(value) def MainOutputRoutine(self,value): value = value + 1 From brian_vanderburg2 at yahoo.com Thu Jun 26 19:30:19 2008 From: brian_vanderburg2 at yahoo.com (Allen) Date: Thu, 26 Jun 2008 19:30:19 -0400 Subject: sqlite3 alternative option In-Reply-To: <3274f950-bfaf-4e3f-bb87-7ce205067557@m36g2000hse.googlegroups.com> References: <3274f950-bfaf-4e3f-bb87-7ce205067557@m36g2000hse.googlegroups.com> Message-ID: Gandalf wrote: > Hi every one I'm looking for a good alternative db to replace sqlite > > I'm using pySQlite3, And I tried to translate very big database from > Mysql to sqlite. > I generated through PHP a python script that insert 200,000 records > to my sqlite db and took me more then 5 hours and managed to insert > only 100,000 records. > I have almost million records so I need a better solution. > > > thank you I don't know if this will help, but using transactions dramatically speed things up. I've only played around with inserting records from large CVS files in C++, but outside of a transaction it creates an automatic transaction every time an update is made and takes forever, but if all the updates are inserted into one transaction and committed as one, it is substantially faster. Brian Vanderburg II From laurent.ploix at gmail.com Fri Jun 20 16:15:37 2008 From: laurent.ploix at gmail.com (=?ISO-8859-1?Q?m=E9choui?=) Date: Fri, 20 Jun 2008 13:15:37 -0700 (PDT) Subject: How to request data from a lazily-created tree structure ? References: <6bo3ifF3dj7dmU1@mid.uni-berlin.de> <896f8600-4183-4147-96c9-64ab5a9ad753@x41g2000hsb.googlegroups.com> <6bp68jF3cv5c7U1@mid.uni-berlin.de> <6bqq4hF3bshiiU1@mid.uni-berlin.de> Message-ID: On Jun 17, 10:54?pm, "Diez B. Roggisch" wrote: > > Do you know if there is such XPath engine that can be applied to a DOM- > > like structure ? > > No. But I toyed with the idea to write one :) > > > One way would be to take an XPath engine from an existing XML engine > > (ElementTree, or any other), and see what APIs it calls... and see if > > we cannot create a DOM-like structure that has the same API. Duck > > typing, really... > > Why can't you create a *real* DOM? > > Diez I don't know what "real" means, in fact. In python, being a "real" sg is all about having the same interface, right? May be I did not undertand what you meant. I cannot load all the data in memory before I request it, because it would take too long. If using XPath-like tools requires that I load the data in memory, I'd better create my own algorithm instead. It will be much faster. What I mean it: if I have a XPath engine that works well on a specific DOM-like structure... may be I can create my own DOM-lile structure to fool the XPath engine; so that I can use it on my own structure. From deets at nospam.web.de Wed Jun 11 17:57:05 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 11 Jun 2008 23:57:05 +0200 Subject: Strange bug doesn't occur in Pydb In-Reply-To: References: Message-ID: <6bb01lF38u72tU1@mid.uni-berlin.de> kj schrieb: > I'm running into a strange seg fault with the module cjson. The > strange part is that it does not occur when I run the code under > Emacs' Pydb. > > Here's an example: > > > import sys, cjson > > d1 = {'a': 1, 'b': 2, 'c': 3} > print sys.version > j1 = cjson.encode(d1) > print j1 # should print the string '{"a": 1, "c": 3, "b": 2}' > > The code above runs fine under Pydb, but segfaults at the call to > cjson.encode when I run it from the command line in a standard > Linux shell interaction. In the printed version strings are > identical. > > I figure this must be a bug in cjson. I'd love to find a workaround > for it, and hope that this strange difference between Pydb and the > shell command line may be a clue to that. > > Any thoughts? Are you sure you actually run the same interpreter in emacs as you do on the commandline? Diez From workitharder at gmail.com Thu Jun 5 20:32:28 2008 From: workitharder at gmail.com (bukzor) Date: Thu, 5 Jun 2008 17:32:28 -0700 (PDT) Subject: Guide to organizing modules? Message-ID: <1611a070-35f9-4072-b95f-ab592820f516@c65g2000hsa.googlegroups.com> I've been finding at work that I've written a set of functions several times, sometimes with more or less features or bugs, so I've decided to take my small, useful functions and put them in some common place. I've made a module for this, but it is quickly becoming a jumbled mess of unrelated functions. Also the one class that I've written with inheritance takes up fully 1/3 of the documentation (compared to 20 other functions). Since this is a large class I'm thinking of moving it to a separate module, but on the other hand it seems silly to have a whole module for just a single class. Also I'm worried that if I wait till later to organize it better, I'll have a lot of code where I'll need to fix-up the naming conventions. In summary: are there any good (or official) guidelines for how to organize and separate python functions and classes into modules? From bruno.42.desthuilliers at websiteburo.invalid Thu Jun 5 07:08:48 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 05 Jun 2008 13:08:48 +0200 Subject: Squeak-like environment for Python? In-Reply-To: <6apod7F387g23U1@mid.uni-berlin.de> References: <0001HW.C46D717900E84E0DB01AD9AF@news.individual.de> <6apod7F387g23U1@mid.uni-berlin.de> Message-ID: <4847c90a$0$6005$426a74cc@news.free.fr> Diez B. Roggisch a ?crit : > Jumping Arne wrote: > >> I've been playing with Squeak a bit and I really like the persistent >> storage model, I also liked HyperCard and Frontier (well, the persistent >> storage model at least). >> >> I wonder if there is some similar environment but based on python, I would >> like to use this environment not as a development environment but as a >> platform for storing data etc - much like HyperCard. >> >> I found a few postings about such an environment: >> >> >> >> but it looks like nothing happened. >> >> pythoncard doesn't seem to have the persistent storage model > > What about ZODB? You can use that to store (more or less) arbitrary objects. > Maybe that can be a foundation, if you throw in > > http://nodebox.net/code/index.php/Home > > it might be similar to squeak (I only dimly remember what squeak as a whole > is though - smalltalk & easy multimedia I remember) Mainly, Squeak is a (relatively) recent, free implementation of Smalltalk. The "persistent storage model" - the 'image' storing the whole system (code, libs, data, whatever) - is part of the Smalltalk system since it's first conception IIRC (even if some Smalltalk implementations - like GNU Smalltalk - are more traditionnaly file-based and have no automatic persistence). From tarek_enpc at yahoo.fr Thu Jun 5 06:12:13 2008 From: tarek_enpc at yahoo.fr (merzouki tarek) Date: Thu, 5 Jun 2008 10:12:13 +0000 (GMT) Subject: can you help me Message-ID: <469737.59430.qm@web26602.mail.ukl.yahoo.com>   hello please, I have this error, error C1083 Cannot open include file BaseTsd.h, invalide argument, I installed the platformSDK , but the same error , can you help me __________________________________________________ Do You Yahoo!? En finir avec le spam? Yahoo! Mail vous offre la meilleure protection possible contre les messages non sollicit?s http://mail.yahoo.fr Yahoo! Mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From patrick.m.bouffard at gmail.com Tue Jun 10 16:49:19 2008 From: patrick.m.bouffard at gmail.com (Patrick Bouffard) Date: Tue, 10 Jun 2008 13:49:19 -0700 (PDT) Subject: Determining which things in 'from package import *' are actually used References: Message-ID: <65aee7cf-eb16-46fa-b1b4-ecc4f0e5d849@x35g2000hsb.googlegroups.com> On Jun 10, 3:03?pm, Robert Kern wrote: > Patrick Bouffard wrote: > > I have a fairly large library of Python code, where 'from package import *' is > > used rather liberally, and it's not uncommon for more than one of these to > > appear in any given module. What I'd like to be able to do is to clean my code > > up a bit and turn each of the 'from package import *' statements into 'from > > package import thing_1, thing_2, ..., thing_n', where only thing_i's that are > > actually _used_ in the module are imported. In this way I hope to make my code a > > bit more understandable by future civilizations. :) (it needs all the help it > > can get!) > > > Does anyone know of a package/recipe/whatever that does something like this > > automatically, even in limited cases? Ideally it should be accomplished only by > > looking at the source, or at most, importing the module. > > I don't know of any automatic tools. I usually comment out those import > statements and use pyflakes to show me the undefined names. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > ? that is made terrible by our own mad attempt to interpret it as though it had > ? an underlying truth." > ? ?-- Umberto Eco Thanks, I didn't know about pyflakes. What you describe sounds like a great place to start, I'll give it a go. -Pat From george.sakkis at gmail.com Mon Jun 16 17:30:37 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 16 Jun 2008 14:30:37 -0700 (PDT) Subject: Simple and safe evaluator References: Message-ID: <1de31143-7d8e-42e9-ae9d-8b0a0274ddc3@e53g2000hsa.googlegroups.com> On Jun 16, 4:47 pm, bvdp wrote: > 2. I thought I'd be happy with * / + -, etc. Of course now I want to add > a few more funcs like int() and sin(). How would I do that? For the builtin eval, just populate the globals dict with the names you want to make available: import math globs = {'__builtins__' : None} # expose selected builtins for name in 'True False int float round abs divmod'.split(): globs[name] = eval(name) # expose selected math constants and functions for name in 'e pi sqrt exp log ceil floor sin cos tan'.split(): globs[name] = getattr(math,name) return eval(s, globs, {}) The change to the _ast version is left as an exercise to the reader ;) George From paddy3118 at netscape.net Wed Jun 25 15:39:26 2008 From: paddy3118 at netscape.net (Donald 'Paddy' McCarthy) Date: Wed, 25 Jun 2008 20:39:26 +0100 Subject: Question: How do I format printing in python In-Reply-To: <98d2a6fc-bcd3-44b8-bcf6-7059859683ff@c19g2000prf.googlegroups.com> References: <98d2a6fc-bcd3-44b8-bcf6-7059859683ff@c19g2000prf.googlegroups.com> Message-ID: Lie wrote: > On Jun 24, 12:12 am, joemacbusin... at yahoo.com wrote: >> Hi All, >> >> How do I format printed data in python? >> I could not find this in the Python Reference Manual:http://docs.python.org/ref/print.html >> Nor could I find it in Matloff's great tutorial:http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf >> >> For example, how do I turn this: >> >> 512 Jun 5 2004 X11r6 >> 22 Jan 17 2005 a2p >> 22 Jan 17 2005 acctcom >> 5374 Sep 15 2002 acledit >> 5664 May 13 2004 aclget >> 12020 May 13 2004 aclput >> 115734 Jun 2 2004 adb >> 46518 Jun 4 2004 admin >> 66750 Sep 16 2002 ali >> 1453 Sep 15 2002 alias >> 28150 Jun 4 2004 alog >> 15 May 12 2005 alstat >> >> into this: >> >> 512 Jun 5 2004 X11r6 >> 22 Jan 17 2005 a2p >> 22 Jan 17 2005 acctcom >> 5374 Sep 15 2002 acledit >> 5664 May 13 2004 aclget >> 12020 May 13 2004 aclput >> 115734 Jun 2 2004 adb >> 46518 Jun 4 2004 admin >> 66750 Sep 16 2002 ali >> 1453 Sep 15 2002 alias >> 28150 Jun 4 2004 alog >> 15 May 12 2005 alstat >> >> Thank you > > There is string formatting > > print formatspecifier_string % data_sequence > The format specifier is similar to the one used in C's printf, and > data sequence may be tuple or list. Dictionary may also be used for > data, but it has its own way to specify string formatting since > dictionary is unordered but "indexed" by the dict key. I have attached a prog I wrote to answer someones elses similar problem. - Paddy. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: pprinter2.py URL: From socyl at 987jk.com.invalid Fri Jun 20 08:14:22 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 20 Jun 2008 12:14:22 +0000 (UTC) Subject: Noob: finding my way around the docs... References: <4b56c745-9803-452a-a876-8f93afbea7c7@w7g2000hsa.googlegroups.com> Message-ID: In <4b56c745-9803-452a-a876-8f93afbea7c7 at w7g2000hsa.googlegroups.com> Matimus writes: >If you are in the interpreter and you type: help(foo.bar.baz) you get >the embeded documentation. >I usually go straight to the `global module index` http://docs.python.org/m= >odindex.html Thanks! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From omer at no-log.org Sun Jun 15 14:48:12 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Sun, 15 Jun 2008 20:48:12 +0200 Subject: randrange loops In-Reply-To: <6e424f2a-872d-4dd1-b28d-cf2a985895c9@j22g2000hsf.googlegroups.com> References: <6e424f2a-872d-4dd1-b28d-cf2a985895c9@j22g2000hsf.googlegroups.com> Message-ID: <200806152048.12102.omer@no-log.org> Le Sunday 15 June 2008 20:23:56 luislupe at gmail.com, vous avez ?crit?: > Hi, > > > I've created a method where the script defines twenty variables and > several of them should be random having a maximum and a minimum value. > > What I did was this: > > from random import randrange as rr, random > > self.tr2_vezes = self.rr(self.d_tr2_vezes[0],self.d_tr2_vezes[-1], > 1) # just an example, others are similar self.rr ? is it a typo or some method you defined yourself ? > > The minimum and maximum limits are never lower than -50 and higher > than 250 and are integer. > > Many times, not always, the problem is that the script just loops > forever and no value is chosen for the variable. > > What's happening here? What am I doing wrong? > as it's very unlikely to be a bug in the randrange function I'd say something is wrong with your script but we'll need more infos to help. Can you post the whole function ? -- C?dric Lucantis From miller.paul.w at gmail.com Mon Jun 2 20:42:08 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Mon, 2 Jun 2008 17:42:08 -0700 (PDT) Subject: "Faster" I/O in a script References: Message-ID: <4cf35e78-8d19-4367-9e1d-efed2b5a360c@79g2000hsk.googlegroups.com> On Jun 2, 2:08?am, "kalakouentin" wrote: > Do you know a way to actually load my data in a more > "batch-like" way so I will avoid the constant line by line reading? If your files will fit in memory, you can just do text = file.readlines() and Python will read the entire file into a list of strings named 'text,' where each item in the list corresponds to one 'line' of the file. From cdcasey at gmail.com Fri Jun 20 01:03:28 2008 From: cdcasey at gmail.com (chris) Date: Thu, 19 Jun 2008 22:03:28 -0700 (PDT) Subject: images on the web Message-ID: <2e72bd7d-9d33-43ba-8c08-ba3b39368466@z72g2000hsb.googlegroups.com> I'm creating a data plot and need to display the image to a web page. What's the best way of doing this without having to save the image to disk? I already have a mod_python script that outputs the data in tabular format, but I haven't been able to find anything on adding a generated image. From rhamph at gmail.com Wed Jun 11 20:37:45 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Wed, 11 Jun 2008 17:37:45 -0700 (PDT) Subject: Confusion with weakref, __del__ and threading References: <113f383e-9027-461b-88db-7e5331e7d361@59g2000hsb.googlegroups.com> <7ed2109d-3b88-484c-9d19-67706747c95f@v26g2000prm.googlegroups.com> <5da23b98-9434-41d4-9dd1-0a423fd387b1@26g2000hsk.googlegroups.com> Message-ID: <2a3ae0a4-144b-44ce-8e30-53b5586ccb7e@w4g2000prd.googlegroups.com> On Jun 11, 2:15 pm, George Sakkis wrote: > On Jun 11, 2:01 pm, Rhamphoryncus wrote: > > > > > On Jun 11, 10:43 am, George Sakkis wrote: > > > > On Jun 11, 1:40 am, Rhamphoryncus wrote: > > > > The trick here is that calling proxy.sleep(0.01) first gets a strong > > > > reference to the Mystery instance, then holds that strong reference > > > > until it returns. > > > > Ah, that was the missing part; I thought that anything accessed > > > through a proxy didn't create a strong reference. The good thing is > > > that it seems you can get a proxy to a bounded method and then call it > > > without creating a strong reference to 'self': > > > That's not right. Of course a bound method has a strong reference to > > self, otherwise you'd never be able to call it. There must be > > something else going on here. Try using sys.setcheckinterval(1) to > > make threads switch more often. > > I tried that and it still works; all objects die at the main thread. > Any other idea to break it ? Nothing comes to mind. However, none of this is guaranteed anyway, so you can't rely on it. __del__ might be called by any thread at any point (even when you're holding a lock, updating a datastructure.) From gagsl-py2 at yahoo.com.ar Mon Jun 16 02:33:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 16 Jun 2008 03:33:16 -0300 Subject: NoneType Error References: Message-ID: En Sun, 15 Jun 2008 05:35:18 -0300, Maryam Saeedi escribi?: > I am using a python program on a lot of different documents and for few of > them I will get NoneType error. I just want to skip those files and continue > for others, I do this without a problem for > IndexError,TypeError,ValueError,NameError : > > try: > .... > except (IndexError,TypeError,ValueError,NameError): > .... > > but when I add NoneType it gives the following error: > except (NoneType,IndexError,TypeError,ValueError,NameError): > NameError: name 'NoneType' is not defined > > and if I do not use the NoneType then it does not go through either and > stops the program when I get to such a file. Is there another name that > captures this error? NoneType is not an exception, but the type of the None object. Perhaps you're not interpreting correctly some error messages: >>> x=None >>> x() Traceback (most recent call last): File "", line 1, in TypeError: 'NoneType' object is not callable (the exception raised is a TypeError; NoneType is part of the message). It appears that you want to catch all exceptions, just use Exception for that: try: ... except Exception: ... -- Gabriel Genellina From kirk at daycos.com Mon Jun 16 15:39:28 2008 From: kirk at daycos.com (Kirk Strauser) Date: Mon, 16 Jun 2008 14:39:28 -0500 Subject: Good cross-host IPC? Message-ID: <87ve096ufj.fsf@internal.daycos.com> We've been using NetWorkSpaces (http://www.ddj.com/web-development/200001971) for IPC on programs running on several different machines. Since it uses a central, shared server for storing values, you don't have to write socket code in your various programs to pass data back and forth. For example, a program can request some work to be done by a random machine on the network like so: >>> from nws.client import NetWorkSpace >>> space = NetWorkSpace('test') >>> space.store('value', 42) >>> ws.fetch('results') 43 ...and a worker process can listen for work to do and return the results by doing: >>> from nws.client import NetWorkSpace >>> space = NetWorkSpace('test') >>> value = space.fetch('value') >>> space.store('results', value + 1) Since space.fetch() is a blocking call and the NetWorkSpaces server answers requests in the order that they're received, this is a nice way to coordinate a cluster. This is pretty spiffy and works great in practice, but it feels like we're the only people using it. Parallel Python lives in kind of the same problem space, but not all of our code is easily bent to its will. Is there another, more common way of doing this stuff? Popularity isn't the most important thing in the world, but I like the warm fuzzies of knowing that thousands of others are testing and using the same project as we are. -- Kirk Strauser The Day Companies From omer at no-log.org Sun Jun 15 10:14:03 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Sun, 15 Jun 2008 16:14:03 +0200 Subject: problem with Py_BuildValue In-Reply-To: References: Message-ID: <200806151614.03734.omer@no-log.org> Hi, > Hi, > > currently I have a problem understanding Py_BuildValue. I have this code: > > static PyObject *function(PyObject *self, PyObject *args) { > PyObject * python_return_value = NULL; > PyObject * dummy = NULL; > double * internal_list; > > > /* converting to python representation */ > for (i=0; i < limit; i++) { > dummy = Py_BuildValue("d", internal_list[i]); > if (!dummy) return NULL; > PyList_Append(python_return_value, dummy); > Py_DECREF(dummy); dummy = NULL; > } > return python_return_value > } > > This doesn't work. What I see, when invoking the function "function()" in > Python is a list of refcounts, like: [, 0x94a29e4>, ...]. However, if I change the Py_BuildValue-line to be > dummy = Py_BuildValue("i", (int)internal_list[i]); > I do get the 'right' integer return values. Point is that I really would > like to work with Python-floats afterwards. > > Any idea where a pitfall might be here? > I see nothing wrong with your code so I'd say it is somewhere else (did you snip any code between the end of the loop and the return?). I've never seen those 'refcnt' objects but a refcount of 0 sounds like you unrefed your objects one extra time by mistake. This would produce a segfault on unix, but maybe not on all platforms ? You should check the return value of PyList_Append() and if it doesn't help trace the content of your list after each iteration to see when the bad things happen (you can check the reference count of an object with obj->ob_refcnt). Finally note that in your case it would be much simpler and more efficient to use the float constructor directly: dummy = PyFloat_FromDouble(internal_list([i])) PS: always use Py_CLEAR(dummy) instead of Py_DECREF(dummy); dummy=NULL; (though it doesn't really matter in this simple case - see http://docs.python.org/api/countingRefs.html) -- C?dric Lucantis From joamag at gmail.com Sun Jun 22 16:23:14 2008 From: joamag at gmail.com (joamag) Date: Sun, 22 Jun 2008 13:23:14 -0700 (PDT) Subject: Way to unblock sys.stdin.readline() call References: <56b21108-45b4-4b9e-bda5-171c9ddc21ce@i76g2000hsf.googlegroups.com> Message-ID: <40203698-2b5d-4436-89e9-692360183d03@k37g2000hsf.googlegroups.com> On Jun 21, 11:34?pm, Terry Reedy wrote: > joamag wrote: > > Is there any possible way to unblock the sys.stdin.readline() call > > from a different thread. > > If you want the thread to do something 'else' when no input is > available, would this work? ?Put readline in a thread that puts lines in > a q=queue.Quese(). ?Then > try: > ? ? ?l=q.ge_nowait > ? ? ? > except queue.Empty > ? ? ? Yes, that would work but still I would have a thread that would block (the one with the readline call). The problem with that solution is that if I try to exit the application, while the thread is waiting in the readline call, that thread would be blocking the exit of the application. That behavior occurs even if the thread is configured in daemon mode. Do you think it?s possible to solve the readline blocking problem in any other way ? From 42flicks at gmail.com Tue Jun 10 22:29:44 2008 From: 42flicks at gmail.com (Mike) Date: Wed, 11 Jun 2008 14:29:44 +1200 Subject: Dynamic HTML from Python Script In-Reply-To: <484f3574$0$4998$607ed4bc@cv.net> References: <484f151c$0$5009$607ed4bc@cv.net> <484f21aa$1@dnews.tpgi.com.au> <484f24e9$0$5020$607ed4bc@cv.net> <484f2870$1@dnews.tpgi.com.au> <484f3574$0$4998$607ed4bc@cv.net> Message-ID: <2b54d4370806101929y643d7765pe5dc3876bb59bcde@mail.gmail.com> On Wed, Jun 11, 2008 at 2:16 PM, asdf wrote: > On Wed, 11 Jun 2008 11:20:48 +1000, Aidan wrote: > > > asdf wrote: > >>> Well, there's a few ways you could approach it. > >>> > >>> You could create a cgi program from your script - this is probably the > >>> solution you're looking for. > >>> > >>> > >> Output from the script does come up very often. There is a new output > >> every 10 secs and it's possible that the script might be run > >> indefinitely. Basically I want all that output displayed in a web > >> browser > > > > Well, in that case you could simply append the new output to a static > > file every 10 seconds, or whenever there is new output. That way, you > > just need to refresh the static file in your browser to see updates... > > Given what I understand of your situation, that's how I'd do it. > > > The problem with this is that browser would have to be refreshed manually > every 10 seconds. Unless there is a way to set this in the script itself. > > > > A constantly running CGI app is probably not the best idea, given > > timeouts and other such constraints you might run into. > > > > > >>> You could have the script run periodically and create a static html > >>> file in the webroot... this would be acceptable, maybe preferable, if > >>> the output from your script doesn't change frequently. > >>> > > -- > http://mail.python.org/mailman/listinfo/python-list > Sorry should have asked how often a user would be requesting new content. To avoid page refreshing I'd look into Django AJAX support, havn't tried it myself but will be soon. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Jun 13 03:42:55 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Jun 2008 09:42:55 +0200 Subject: Plotting Graphs + Bestfit lines References: <1a919a2b-6430-4e2e-a190-2e00e43a6138@25g2000hsx.googlegroups.com> <022d382b-0b7b-4757-855a-f07019791fcc@d45g2000hsc.googlegroups.com> <05e67e40-db9c-4d85-94c1-f0e31dd5da38@27g2000hsf.googlegroups.com> Message-ID: arslanburney at gmail.com wrote: > Tried that out too. No error however, best fit lines still not being > made on the graph. Only the 3 plot lines show up. Sorry, I don't know gnuplot, so I can't help you with any but the obvious (read: Python) errors. Peter From collinyeung at shaw.ca Thu Jun 12 00:29:56 2008 From: collinyeung at shaw.ca (Collin) Date: Thu, 12 Jun 2008 04:29:56 GMT Subject: =?windows-1256?Q?=E3=DE=D8=DA_=DD=ED=CF=ED=E6_=5B=C7=E1=E6?= =?windows-1256?Q?=E1=C7=CF=E5_=C7=E1=DE=ED=D5=D1=ED=E5=5D_=ED=E3=E4=DA?= =?windows-1256?Q?_=CF=CE=E6=E1_=D6=DA=C7=DD_=C7=E1=DE=E1=E6=C8?= In-Reply-To: References: Message-ID: <8D14k.25653$gc5.1766@pd7urf2no> a7labnt wrote: > ?????? VMware Workstation 6.0 > > http://www.antya7la.com/vb/t26858.html#post286993 > > ?????? ????? ??????? auto run ? folder option > > http://www.antya7la.com/vb/t26859.html#post286996 > > ?? ????? ???? ??? ?????? > > http://www.antya7la.com/vb/t26860.html#post286997 > > ??? ???? ?? Ftp ? 64 % + ??????? ?????? ? ????? ? ????? > > http://www.antya7la.com/vb/t26861.html#post286999 > > ???? ?? ????? ????? ?????.. ???????? > > http://www.antya7la.com/vb/t26862.html#post287000 > > ????? : ???? ????? ????? ?? ??????? - ??? ????? ?????? ?????? ! > > http://www.antya7la.com/vb/t26863.html#post287010 > > > ????? ?? ????? ??????? > > http://www.antya7la.com/vb/t27127.html#post289835 > > ??????? ??? ??? ??? ?????? ??????000????????? > > http://www.antya7la.com/vb/t27128.html#post289837 > > ????? - ???? ???????? > > http://www.antya7la.com/vb/t27129.html#post289839 > > ?? ??? ?? ?????? ???? ?????? ??? ????? ?? ???? ??????? > > http://www.antya7la.com/vb/t27130.html#post289841 > > ??? ?????? ?????? ???????? ???? ?????? > > http://www.antya7la.com/vb/t27131.html#post289843 > > ????? ????? ?? ???? > > http://www.antya7la.com/vb/t27132.html#post289845 > > ?????????? ???? ??????? ?? ??? ????? ?????? !! > > http://www.antya7la.com/vb/t27133.html#post289846 > > ????? ????? ?????? ???? > > http://www.antya7la.com/vb/t27135.html#post289851 > > ???? ?????? (?????????) ????? ???? ???? ?????? > > http://www.antya7la.com/vb/t27138.html#post289855 > > ?????? ??????? ?????? ???? ???? ?? ???? ???? ??? ?????? 5 ????? ????? > http://www.antya7la.com/vb/t27134.html#post289850 > > ???? ????? 300 ??? ???? 24 ????!!! > > http://www.antya7la.com/vb/t27139.html#post289859 > > ???? ???? ?? ?????? ??????????? ??????? ???????????? > > http://www.antya7la.com/vb/t26884.html#post289876 > > ???? ?? ????? ????? ????? ????? > > http://www.antya7la.com/vb/t26783.html#post289879 > > ????? ??? ?????? ?????? ???? ???? > > http://www.antya7la.com/vb/t26935.html#post289880 > > ??? ?????? ?? ???? ???? ?????? > > http://www.antya7la.com/vb/t26932.html#post289884 > > ????? ??? ??????!!????? ???? ?????? ????? ?????? ?? ?????? > > http://www.antya7la.com/vb/t26617.html#post289885 > > ????? ?????? ??? ??????........... > http://www.antya7la.com/vb/t26815.html#post289889 > > ?????? ??????? ? ???????? ?????? ??? !!! ?? ?????????????? > > http://www.antya7la.com/vb/t26914.html#post289893 > > ???? ????? [??????? ????????] ???? ???? ???? ?????? > > http://www.antya7la.com/vb/t26992.html#post289907 > > {{{ ??? ??? ?? ?????? ??? ???..!!}}} > > http://www.antya7la.com/vb/t26793.html#post289913 > > ??? ?????? ??? ???? > > http://www.antya7la.com/vb/t27081.html#post289912 > > ?? ?????? ??? ??????..#! > > http://www.antya7la.com/vb/t2223.html#post289911 > > ??????? ???? ??? ???????! > > http://www.antya7la.com/vb/t4378.html#post289915 > > > ????? Windows Xp ????? ????? ???!!!!! > > http://www.antya7la.com/vb/t21396.html#post242891 > > ?????? ??????? ??????? Internet Explorer 8 Beta 1 > > http://www.antya7la.com/vb/t21395.html#post242889 > > ????? Ares ?????? ?? ??? > > > http://www.antya7la.com/vb/t21394.html#post242887 > > ???? ??????? ?????? ?? ?????? KinG Fm ????? ???? ?? ?? ??????? ?? > ???????? ??? ?????, > > http://www.antya7la.com/vb/t21397.html#post242896 > > ?????? ??????? ??????? Internet Explorer 8 Beta 1 > > http://www.antya7la.com/vb/t21395.html#post242889 > > ????? ????!?? ???? ?????? ??????!????? On Speeeed, ?????? ?????? > ?????? ????????!???? > > http://www.antya7la.com/vb/t21398.html#post242898 > > The Logo Creator ?????? ???????? > > http://www.antya7la.com/vb/t21399.html#post242900 > > ?????? Driver Wizard ????? ?????? ????? ??????? > > http://www.antya7la.com/vb/t21400.html#post242913 > > > ????? ?????? ? ?????? ??? ????? ??? ??? ????? ????? ??????? ??? > ??????? ???? > > > http://www.antya7la.com/vb/t21401.html#post242914 > > ???? ??? ?????? ?? ????? ?????? ????? ???? ??! ???? ??????? > > > http://www.antya7la.com/vb/t21402.html#post242919 > > ?? ???? ???? ????? ????? ???WinXP ???? ?????? ?????? > > http://www.antya7la.com/vb/t21403.html#post242920 > > ?????? ?????? ???? ????? ?????! ????? 100% > > http://www.antya7la.com/vb/t21404.html#post242921 > > > Is this arabic spam? From frank at chagford.com Wed Jun 11 10:14:55 2008 From: frank at chagford.com (Frank Millman) Date: Wed, 11 Jun 2008 07:14:55 -0700 (PDT) Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: On Jun 11, 4:39?pm, Ethan Furman wrote: > Frank Millman wrote: > > Thanks to all for the various replies. They have all helped me to > > refine my ideas on the subject. These are my latest thoughts. > > Out of curiosity, what is the purpose of these numbers? ?Do they > represent money, measurements, or something else? I am writing a business/accounting application. The numbers represent mostly, but not exclusively, money. Examples - Multiply a selling price (scale 2) by a product quantity (scale 4) to get an invoice value (scale 2), rounded half-up. Multiply an invoice value (scale 2) by a tax rate (scale 2) to get a tax value (scale 2), rounded down. Divide a currency value (scale 2) by an exchange rate (scale 6) to get a value in a different currency (scale 2). Divide a product quantity (scale 4) by a pack size (scale 2) to get an equivalent quantity in a different pack size. In my experience, the most important thing is to be consistent when rounding. If you leave the rounding until the presentation stage, you can end up with an invoice value plus a tax amount differing from the invoice total by +/- 0.01. Therefore I always round a result to the required scale before 'freezing' it, whether in a database or just in an object instance. Frank From hniksic at xemacs.org Tue Jun 17 03:05:11 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 17 Jun 2008 09:05:11 +0200 Subject: String Concatenation O(n^2) References: <3fc761710806160941q3c1a93b5p7761fbe148718585@mail.gmail.com> <20080616170916.4714.1881297769.divmod.quotient.9773@ohm> Message-ID: <87k5gov8wo.fsf@mulj.homelinux.net> "Ian Kelly" writes: > On Mon, Jun 16, 2008 at 11:09 AM, Jean-Paul Calderone > wrote: >> It will depend what version of Python you're using and the *exact* details >> of the code in question. An optimization was introduced where, if the >> string being concatenated to is not referred to anywhere else, it will be >> re-sized in place. This means you'll probably see sub-quadratic behavior, >> but only with a version of Python where this optimization exists and only >> if the code can manage to trigger it. > > AFAICT, PyString_Concat never calls _PyString_Resize. Am I looking > in the wrong place? Take a look at ceval.c:string_concatenate. As Jean-Paul says, note that the optimization doesn't work in many circumstances. For example, change local variable to instance attribute, and it goes away. Other python implementations don't have it at all. From eric.acevedo at gmail.com Fri Jun 13 10:15:44 2008 From: eric.acevedo at gmail.com (ericdaniel) Date: Fri, 13 Jun 2008 07:15:44 -0700 (PDT) Subject: Create list from string Message-ID: Hi, I'm new to Python and I need to do the following: from this: s = "978654321" to this : ["978", "654", "321"] Any help is appreciated Thanks, Eric From malaclypse2 at gmail.com Wed Jun 11 16:42:33 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 11 Jun 2008 16:42:33 -0400 Subject: problems with opening files due to file's path In-Reply-To: <17786320.post@talk.nabble.com> References: <17759531.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> <77acc29a-fffa-44d6-b07b-6bcf8b5bdd74@h1g2000prh.googlegroups.com> <17786320.post@talk.nabble.com> Message-ID: <16651e80806111342k1d2d0b3ay9a558452f48fc2d9@mail.gmail.com> On Wed, Jun 11, 2008 at 4:16 PM, Alexnb wrote: > > I posted the underlying code, but I haven't made the GUI code because if I > can't get the underlying code right it doesn't matter, well in my eyes it > doesn't but I am probably wrong. But it will look somehting like this: What you're missing is that all of the problems you're having with escape characters *only apply to string literals inside your python source code.* If you're getting the string from the console, you don't need to escape or change anything. If you're getting the string from a Tk text box, you don't need to escape or change anything. If you're getting the string from the filesystem, you don't need to escape or change anything. The only place you have to be careful is when you type out a literal string inside your .py source code. When you do that, you need to properly escape backslashes, either by putting them in raw strings, or by doubling up your backslashes. If you haven't already, reread the section of the python tutorial about string literals: http://docs.python.org/tut/node5.html. -- Jerry From mensanator at aol.com Mon Jun 23 13:53:43 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 23 Jun 2008 10:53:43 -0700 (PDT) Subject: Question: How do I format printing in python References: <2e43cbba-bcd1-492e-97aa-bf8d2708d665@26g2000hsk.googlegroups.com> Message-ID: On Jun 23, 12:47?pm, Mensanator wrote: > On Jun 23, 12:12?pm, joemacbusin... at yahoo.com wrote: > > > > > > > Hi All, > > > How do I format printed data in python? > > I could not find this in the Python Reference Manual:http://docs.python.org/ref/print.html > > Nor could I find it in Matloff's great tutorial:http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf > > > For example, how do I turn this: > > > 512 Jun 5 2004 X11r6 > > 22 Jan 17 2005 a2p > > 22 Jan 17 2005 acctcom > > 5374 Sep 15 2002 acledit > > 5664 May 13 2004 aclget > > 12020 May 13 2004 aclput > > 115734 Jun 2 2004 adb > > 46518 Jun 4 2004 admin > > 66750 Sep 16 2002 ali > > 1453 Sep 15 2002 alias > > 28150 Jun 4 2004 alog > > 15 May 12 2005 alstat > > > into this: > > > 512 ? ? ? ?Jun ? 5 ? 2004 ? ?X11r6 > > 22 ? ? ? ? Jan ? 17 ?2005 ? ?a2p > > 22 ? ? ? ? Jan ? 17 ?2005 ? ?acctcom > > 5374 ? ? ? Sep ? 15 ?2002 ? ?acledit > > 5664 ? ? ? May ? 13 ?2004 ? ?aclget > > 12020 ? ? ?May ? 13 ?2004 ? ?aclput > > 115734 ? ? Jun ? 2 ? 2004 ? ?adb > > 46518 ? ? ?Jun ? 4 ? 2004 ? ?admin > > 66750 ? ? ?Sep ? 16 ?2002 ? ?ali > > 1453 ? ? ? Sep ? 15 ?2002 ? ?alias > > 28150 ? ? ?Jun ? 4 ? 2004 ? ?alog > > 15 ? ? ? ? May ? 12 ?2005 ? ?alstat > > > Thank you > > You could do this: > > data = ['512 Jun 5 2004 X11r6 ', \ > '22 Jan 17 2005 a2p', \ > '22 Jan 17 2005 acctcom ', \ > '5374 Sep 15 2002 acledit ', \ > '5664 May 13 2004 aclget ', \ > '12020 May 13 2004 aclput ', \ > '115734 Jun 2 2004 adb ', \ > '46518 Jun 4 2004 admin ', \ > '66750 Sep 16 2002 ali ', \ > '1453 Sep 15 2002 alias ', \ > '28150 Jun 4 2004 alog ', \ > '15 May 12 2005 alstat '] > > for i in data: > ? d = i.split() > ? print d[0].ljust(9), > ? print d[1].ljust(6), > ? print d[2].ljust(4), > ? print d[3].ljust(7), > ? print d[4].ljust(9) > > which gives you > > 512 ? ? ? Jun ? ?5 ? ?2004 ? ?X11r6 > 22 ? ? ? ?Jan ? ?17 ? 2005 ? ?a2p > 22 ? ? ? ?Jan ? ?17 ? 2005 ? ?acctcom > 5374 ? ? ?Sep ? ?15 ? 2002 ? ?acledit > 5664 ? ? ?May ? ?13 ? 2004 ? ?aclget > 12020 ? ? May ? ?13 ? 2004 ? ?aclput > 115734 ? ?Jun ? ?2 ? ?2004 ? ?adb > 46518 ? ? Jun ? ?4 ? ?2004 ? ?admin > 66750 ? ? Sep ? ?16 ? 2002 ? ?ali > 1453 ? ? ?Sep ? ?15 ? 2002 ? ?alias > 28150 ? ? Jun ? ?4 ? ?2004 ? ?alog > 15 ? ? ? ?May ? ?12 ? 2005 ? ?alstat > > or perhaps this: > > for i in data: > ? d = i.split() > ? print d[0].rjust(9), > ? print d[1].ljust(6), > ? print d[2].zfill(2).ljust(4), > ? print d[3].ljust(7), > ? print d[4].ljust(9) > > which gives this (if you want the digits in the numbers to > line up): > > ? ? ? 512 Jun ? ?05 ? 2004 ? ?X11r6 > ? ? ? ?22 Jan ? ?17 ? 2005 ? ?a2p > ? ? ? ?22 Jan ? ?17 ? 2005 ? ?acctcom > ? ? ?5374 Sep ? ?15 ? 2002 ? ?acledit > ? ? ?5664 May ? ?13 ? 2004 ? ?aclget > ? ? 12020 May ? ?13 ? 2004 ? ?aclput > ? ?115734 Jun ? ?02 ? 2004 ? ?adb > ? ? 46518 Jun ? ?04 ? 2004 ? ?admin > ? ? 66750 Sep ? ?16 ? 2002 ? ?ali > ? ? ?1453 Sep ? ?15 ? 2002 ? ?alias > ? ? 28150 Jun ? ?04 ? 2004 ? ?alog > ? ? ? ?15 May ? ?12 ? 2005 ? ?alstat In retrospect, that looks kind of clunky. If it was for my use, I'd do for i in data: d = i.split() print d[0].rjust(9), print d[1].rjust(6), print d[2].zfill(2), print d[3].ljust(7), print d[4].ljust(9) which looks like: 512 Jun 05 2004 X11r6 22 Jan 17 2005 a2p 22 Jan 17 2005 acctcom 5374 Sep 15 2002 acledit 5664 May 13 2004 aclget 12020 May 13 2004 aclput 115734 Jun 02 2004 adb 46518 Jun 04 2004 admin 66750 Sep 16 2002 ali 1453 Sep 15 2002 alias 28150 Jun 04 2004 alog 15 May 12 2005 alstat From Lie.1296 at gmail.com Sun Jun 1 14:29:29 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 1 Jun 2008 11:29:29 -0700 (PDT) Subject: How to get all the variables in a python shell References: Message-ID: <61f7681d-5cd3-4093-96f9-82f0e7383217@y38g2000hsy.googlegroups.com> lixinyi... at gmail.com wrote: > Hi! > > I'm currently working on a scientific computation software built in > python. > What I want to implement is a Matlab style command window <-> > workspace interaction. > > For example, you type 'a=1' in the command window, and you see a list > item named 'a' in the workspace. > You double click the icon of the item, and you see its value. You can > modify the value of the list item, > 1 -> 100 etc, after which if you go back to the command window and > type 'a' and press enter, you see that > varable a's value has been changed to 100. > > So my question is : if you have two DOS command windows running under > WINDOWS OS, how can you make them share the same internal variable > buffer? Or is there any easier way to implement such kind of > interaction? > > Maybe I could just build a small database to store all the values and > access them from both programs, but chances are sometimes I have to > deal with big arrays, and they will eat extra memory if I keep them in > a database. Is there anyway to access a shell's local memory buffer? > I tried to use shell.interp.locals() in wxPython, but there's too many > variables in the list which I don't actually need. > > Come on guys, give me some ideas. Thanks in advance! In all kinds of code, it's best to seperate the workers code and the UI code, in your case, you should create a backend (worker), which is a class that stands on its own, and two foreground class (UI) that is completely independent of each other but have the same interface. The backend code would have an event that is raised when it is changed to notify the UI (esp. The gui one) that it has changed since last time, possibly passing info on what have been changed. The front ends, would watch for this event as necessary (I don't think it is necessary for the command line to watch this event) and react to it as necessary like refreshing the view. The front-end window may only call functions on the backend to interact with the data being worked on (in short the backend class is opaque). This obliviate the need to share data between the two (or more) windows (UI) because all the data are contained in the backend class that the frontend can't access directly. From brendon at christian.net Fri Jun 20 01:09:38 2008 From: brendon at christian.net (Brendon Costa) Date: Thu, 19 Jun 2008 22:09:38 -0700 (PDT) Subject: How do i : Python Threads + KeyboardInterrupt exception References: <089f56d2-5e44-4161-b580-84881717bd05@w4g2000prd.googlegroups.com> <6cfbfaa2-293f-41d3-b544-fd47f05d0d36@j33g2000pri.googlegroups.com> Message-ID: <93eb3402-1dde-4ad3-b91f-d4b091048ac0@g16g2000pri.googlegroups.com> > If only the main thread can receive KeyboardInterrupt, is there any > reason why you couldn't move the functionality of the Read thread into > the main thread? It looks like it's not doing any work, just waiting > for the Proc thread to finish. > > You could start the Proc thread, do the current Read thread > functionality until the interrupt occurs, put the apporpriate message > in the queue, and then wait for the Proc thread to finish. It is already doing that. You will notice that the Proc() function is called by a threading.Thread instance so Proc() is running in a thread, but the Read() function is being called by the main thread right after this. It DOES work with the Ctrl + C, but i can find no way at all of closing down the script from within the Proc() thread. The relevant bit of code is: t = MyThread(Proc, queue, sys.stderr, None) Read(queue, sys.stdin, sys.stderr) In the end, the problem is that i am trying to multiplex IO and other operations. In UNIX i would use select with the input file descriptor and an anonymous pipe for the extra commands to achieve this without any threads, but this script needs to run primarily on a windows box and i would like to use it on UNIX too. I thought i could use threads to achieve the IO Multiplexing in python, but it seems not or at least not simply. How do people usually manage IO multiplexing (not just using sockets) cross platform in python? I only need to multiplex two sources really: * Input file or stdin * A input event queue This will have messages injected from various locations: timers, the processing thread itself, and possibly from a single GUI thread at a later point in time. Though i can foresee that at some point in the future i may also need to multiplex those two above and some sockets (For a server with a few clients). I was thinking of looking at some asynchronous IO libraries for python on Windows + UNIX, any suggestions (Must include more than just sockets)? From afanning at pbtcomm.net Wed Jun 18 23:24:36 2008 From: afanning at pbtcomm.net (George) Date: Wed, 18 Jun 2008 23:24:36 -0400 Subject: moyea flv to video converter keygen Message-ID: <000501c8d1bc$00bde180$0200000a@GEORGECOMPUTER> got error on your page -------------- next part -------------- An HTML attachment was scrubbed... URL: From mattheww at chiark.greenend.org.uk Wed Jun 18 12:50:04 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 18 Jun 2008 17:50:04 +0100 (BST) Subject: Getting Python exit code when calling Python script from Java program References: Message-ID: In article , > I tried using the sys.exit() method in my script and passed non -zero > values. However the value wasn't picked up the by Java > Process.exitValue() method - it kept picking up 0. On investigation > it turned out that the exit value being read is from python.exe > process, not from the Python script. I don't believe there is any such distinction. The exit status of python.exe is the exit status determined by the script. -M- From cashm491 at gmail.com Sat Jun 28 04:01:56 2008 From: cashm491 at gmail.com (casahm491@gmail.com) Date: Sat, 28 Jun 2008 01:01:56 -0700 (PDT) Subject: Money In Us $ No Investment Except Minimum Time Daily!!! Message-ID: <72ada42a-01bd-4c18-9a4b-22433d835889@i18g2000prn.googlegroups.com> Worth Clicking If You Mean Time = Money In Us $ No Investment Except Minimum Time Daily! You Will Reveal A Great Home Business Opportunity By Opening The Below Link. http://www.govindswamy-govindaswamy.blogspot.com You Will Be Paid 2 US DOLLARS For Each Member Joining Under You (Provided they should also work actively) To Enroll Members You Can Use google groups Or Any Other Free Ads. 100% LEGAL - 100% PROFIT - 100% GROWTH - 100% TIME EFFORT You Should Work Proactively Otherwise You Cannot Reap The Fruit. This Does'ne Make You Rich Just Clicking This. But Useful To Earn Extra Money When You Find Free Time. Hey Wait. Think Well Before You Close Or You Will Loose Your Money. http://www.govindswamy-govindaswamy.blogspot.com NOTE: This Message Is Intended To Those Who Are Interested To Earn Money Through Online. Others Please Excuse. http://alt.com/go/g900909-pmem www.govindaswamy10.blogspot.com www.kavigovindan.blogspot.com www.govindaswamy1.blogspot.com www.govindaswamy-amman.blogspot.com From tdahsu at gmail.com Sat Jun 14 19:39:37 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Sat, 14 Jun 2008 16:39:37 -0700 (PDT) Subject: os.walk Value Error? References: Message-ID: On Jun 14, 7:11?pm, Larry Bates wrote: > tda... at gmail.com wrote: > > Hi, > > > I'm using os.walk as follows: > > > (basedir, pathnames, files) = os.walk("results", topdown=True) > > > and I'm getting the error: > > > ValueError: too many values to unpack > > > From my googling, that means: > > > This is the standard message when Python tries to unpack a tuple > > into fewer variables than are in the tuple. > > > From what I can see of the examples on the python site, I'm using it > > correctly. ?I have commas in my original code, and the "results" > > directory exists and is directly under the directory from which my > > script is run. > > > I'm assuming that 12 files (the number of files in the "results" > > directory) is not too many for Python to handle! ?;-) > > > Is there any other reason I might get that error? > > os.walk is a generator so you need to make it a loop target: > > for basedir, pathnames, files in os.walk("results"): > ? ? ?# > ? ? ?# Do you work inside the loop > ? ? ?# > > -Larry Thanks! From robin at alldunn.com Wed Jun 25 15:20:20 2008 From: robin at alldunn.com (Robin Dunn) Date: Wed, 25 Jun 2008 12:20:20 -0700 Subject: ANN: wxPython 2.8.8.0 Message-ID: <48629A74.2030109@alldunn.com> Announcing ---------- The 2.8.8.0 release of wxPython is now available for download at http://wxpython.org/download.php. This release has had a number of further refinements and enhancements on the stable 2.8 source tree since the previous release. On Mac OS X 10.5 (Leopard) the Python 2.5 binaries of wxPython are able to be used with either Apple's system Python, or with the Python.org version. Source code is available, as well as binaries for Python 2.3, 2.4 and 2.5, for Windows and Mac, as well some packages for various Linux distributions. A summary of changes is listed below and also at http://wxpython.org/recentchanges.php. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit Microsoft Windows, most Linux or other Unix-like systems using GTK2, and Mac OS X 10.3+, in most cases the native widgets are used on each platform to provide a 100% native look and feel for the application. Changes in 2.8.8.0 ------------------ Added the PlateButton class from Cody Precord. Added wx.PyEvtHandler, which supports overriding the ProcessEvent method in derived classes. Instances of this class can be pushed onto the event handler chain of a window in order to hook into the event processing algorithm, and its ProcessEvent method will be called for every event sent to the window. With much help from Anthony Tuininga the code generated by the img2py tool is now cleaner, simpler and smaller. Instead of writing the data for the images as printable ascii with hex escapes it now uses base64 to encode the images into a string. In addition, instead of top-level functions for returning the image data and bitmaps, the embedded images now use a simple class with methods for returning the image as a bitmap, icon, or etc. By default in 2.8.x top-level aliases will be generated to make the code backward compatible with the old functional interface, but you can use -F to turn that off. In 2.9 and beyond the default will be to generate only the new class interface, but -f can be used to turn the old behavior back on. The PyEmbeddedImage class added for the new img2py support can also be used for image data that may be acquired from some other source at runtime, such as over the network or from a database. In this case pass False for isBase64 (unless the data actually is base64 encoded.) Any image type that wx.ImageFromStream can handle should be okay. See the wx.lib.embeddedimage module for details. Exposed the wx.GenericDatePickerCtrl to wxPython. On wxGTK and wxMac this is exactly the same as the normal date picker, but on wxMSW it allows you to avoid the native wx.DatePickerCtrl if so desired. Also fixed a bug that caused an assert if you tried to set the date to wx.DefaultDateTime even if wx.DP_ALLOWNONE was specified. Made a little hack in wx.lib.masked.TextCtrl that allows it to be wrapped around an already existing TextCtrl instead of always creating its own. This is useful for example with the wx.TextCtrl that is built-in to the customizable wx.combo.ComboCtrl, or with a textctrl that is part of an XRC layout. To use it you need to do a little trick like this:: existingTextCtrl = combo.GetTextCtrl() maskedCtrl = wx.lib.masked.TextCtrl.__new__(wx.lib.masked.TextCtrl) maskedCtrl.this = existingTextCtrl.this maskedCtrl.__init__(parent) Enhanced the Widget Inspection Tool with some new functionality. Added tools to the toolbar to expand and collapse the widget tree, which is very helpful for not getting lost in very large applications with many hundreds of widgets. Also added a toolbar tool for highlighting the currently selected widget or sizer in the live application. The tool will flash top-level windows and for all other items it will draw an outline around the item for a few seconds. Copied the sized_controls module to the wx.lib package as the first step of phasing out the wxaddons package. Added an implementation of wx.Window.SetDoubleBuffered on Windows. (GTK already has one, and Mac doesn't need one because everything is always double buffered by the system there.) Added a wrapper to wx.TopLevelWindow for MacGetTopLevelWindowRef to facilitate calling the Carbon APIs directly for things that are not supported in wx, similar to how we can use ctypes or PyWin32 with window.GetHandle() to do custom stuff on Windows. (On wxMac GetHandle returns the ControlRef, which is different than the WindowRef, hence the need for a 2nd method.) Here is an example to set the modified flag in the caption:: >>> import ctypes >>> carbon = ctypes.CDLL('/System/Library/Carbon.framework/Carbon') >>> carbon.SetWindowModified(frame.MacGetTopLevelWindowRef(), True) Added a new light-weight solution for embedding ActiveX controls in wxPython applications that uses ctypes and the comtypes package available from http://starship.python.net/crew/theller/comtypes/. Comtypes allows us to use and provide an interface with full dynamic dispatch abilities, much like PyWin32's COM interfaces but with much reduced external dependencies. See wx/lib/activex.py for more details. IMPORTANT: Be sure to get at least version 0.5 of comtypes, see the docstring in the wx.lib.activex module for details. The wx.lib.iewin, wx.lib.pdfwin, and wx.lib.flashwin modules were switched to use the new and improved activex module. The APIs provided by these modules should be mostly compatible with what was there before, except for how the COM events are handled. Instead of sending wx events it relies on you overriding methods with the same names as the COM events. You can either do it in a or derived class, or you can set an instance of some other class to be the event sink. See the ActiveX_IEHtmlWindow sample in the demo for an example. If you would rather continue to use the old version of these modules they are available in the wx.lib with "_old" added to the names. Added the wx.lib.resizewidget module. This module provides the ResizeWidget class, which reparents a given widget into a specialized panel that provides a resize handle for the widget. When the user drags the resize handle the widget is resized accordingly, and an event is sent to notify parents that they should recalculate their layout. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From casey.mcginty at gmail.com Fri Jun 27 21:47:43 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Fri, 27 Jun 2008 15:47:43 -1000 Subject: Help with Borg design Pattern In-Reply-To: References: Message-ID: On Fri, Jun 27, 2008 at 3:21 PM, Casey McGinty wrote: > Hi, > > I'm trying to implement a simple Borg or Singleton pattern for a class that > inherits from 'dict'. Can someone point out why this code does not work? > > class MyDict( dict ): > __state = {} > def __init__(self): > self.__dict__ = self.__state > > a = MyDict() > a['one'] = 1 > a['two'] = 2 > > print a > print MyDict() > > This looks like a good solution: class MyDict( dict ): def __new__(cls,*p,**k): if not '_instance' in cls.__dict__: cls._instance = dict.__new__(cls) return cls._instance -------------- next part -------------- An HTML attachment was scrubbed... URL: From fc14301589 at icqmail.com Fri Jun 13 03:24:58 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Fri, 13 Jun 2008 15:24:58 +0800 Subject: Debuggers Message-ID: <485220ca_1@news.tm.net.my> Hi, while testing my program I found some strange happening with pdb and pydb. I like pydb because let me restart the program and nicer features, but if errors pop up, then it will forget all variables (globals and locals gone). I've to go for pdb because it isn't affected by that problem, but also in some case pdb doesn't recognize a fix after a post-mortem restart. The funny thing is that it shows the line corrected, but pdb execute the one it put in memory. However, I think also python shell has such flaw. I'd like to know how to blank all current data and restart a program or re-import a corrected class sentence. Any other to try? I'm also prone to use Ipython, but I still miss some learning how to run a program within Ipython itself. So if I do: import myprogram myprogram.__main__ Will it run? And then the other arguments from CLI, how do I pass them in? -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 30 07:10:54 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 30 Jun 2008 13:10:54 +0200 Subject: Why is recursion so slow? In-Reply-To: References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> Message-ID: <4868bf3e$0$26061$426a34cc@news.free.fr> Dan Upton a ?crit : > On Sun, Jun 29, 2008 at 1:27 AM, Terry Reedy wrote: >> >> slix wrote: >>> Recursion is awesome for writing some functions, like searching trees >>> etc but wow how can it be THAT much slower for computing fibonacci- >>> numbers? >> The comparison below has nothing to do with recursion versus iteration. (It >> is a common myth.) You (as have others) are comparing an exponential, >> O(1.6**n), algorithm with a linear, O(n), algorithm. >> > > FWIW, though, it's entirely possible for a recursive algorithm with > the same asymptotic runtime to be wall-clock slower, just because of > all the extra work involved in setting up and tearing down stack > frames and executing call/return instructions. (If the function is > tail-recursive you can get around this, though I don't know exactly > how CPython is implemented and whether it optimizes that case.) By decision of the BDFL, based on the argument that it makes debugging harder, CPython doesn't optimize tail-recursive calls. From larry.bates at websafe.com` Thu Jun 5 15:36:17 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 05 Jun 2008 14:36:17 -0500 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: References: Message-ID: Gabriel Rossetti wrote: > Hello everyone, > > I had read somewhere that it is preferred to use > self.__class__.attribute over ClassName.attribute to access class (aka > static) attributes. I had done this and it seamed to work, until I > subclassed a class using this technique and from there on things started > screwing up. I finally tracked it down to self.__class__.attribute! What > was happening is that the child classes each over-rode the class > attribute at their level, and the parent's was never set, so while I was > thinking that I had indeed a class attribute set in the parent, it was > the child's that was set, and every child had it's own instance! Since > it was a locking mechanism, lots of fun to debug... So, I suggest never > using self.__class__.attribute, unless you don't mind it's children > overriding it, but if you want a truly top-level class attribute, use > ClassName.attribute everywhere! > > I wish books and tutorials mentioned this explicitly.... > > Gabriel If you define a class instance variable with the same name as the class attribute, how would Python be able to distinguish the two? That is a feature not a problem. Getter looks for instance attribute, if one is not found it looks for a class attribute, and upwards. This behavior is used by Zope to do all sorts of neat stuff. -Larry Bates From alexnbryan at gmail.com Tue Jun 10 23:07:25 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 10 Jun 2008 20:07:25 -0700 (PDT) Subject: problems with opening files due to file's path In-Reply-To: References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> Message-ID: <17769178.post@talk.nabble.com> I don't think you understand it doesn't matter how the variable gets there, the same code is run regardless, I have no problem with the GUI, but you asked, and so I told you. the code os.startfile(.... is run if there is a GUI or it is a console app. Carsten Haese-2 wrote: > > Alexnb wrote: >> Okay, I don't understand how it is too vague, but here: >> > > [snip a bunch of irrelevant examples...] >> >> Did I clarify? > > No. Earlier you wrote: > >>> On 2008-06-11, Alexnb wrote: >>>> I am using GUI, Tkinter to be exact. But regardless of how the >>>> path gets there, it needs to opened correctly. > > This implies that the file doesn't get opened correctly if the file name > is entered/chosen in the GUI. Yet, the examples you posted don't contain > any GUI code whatsoever. They merely demonstrate that you don't have a > firm grasp on how backslashes in string literals are treated. > > So, this begs the question, do you actually have any GUI code that is > failing, or are you just worried, given the problems you had with string > literals, that the GUI code you have yet to write will fail in the same > way? > > If this is the case, you should just write the GUI code and try it. It > might just work. Backslashes entered into a GUI text box are not treated > the same as backslashes in a Python string literal. > > If, on the other hand, you do have some GUI code for getting the file > name from the user, and that code is failing, then please, show us THAT > CODE and show us how it's failing. > > -- > Carsten Haese > http://informixdb.sourceforge.net > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17769178.html Sent from the Python - python-list mailing list archive at Nabble.com. From kyosohma at gmail.com Thu Jun 19 13:18:08 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 19 Jun 2008 10:18:08 -0700 (PDT) Subject: Simple wxPython SetLabel question References: <005654a8-3406-4063-8e06-d7cf567b96d6@z66g2000hsc.googlegroups.com> Message-ID: <6b412f33-55c8-42af-a25f-929e013a9be4@u6g2000prc.googlegroups.com> On Jun 19, 5:25?am, dp_pearce wrote: > Thank you very much C?dric. I thought it would be something very > straight forward. Just an FYI. There's also a wxPython specific mailing list that I highly recommend. You can learn a lot just reading other people issues and how they get them fixed. Here's the link: http://wxpython.org/maillist.php ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org From mdw at distorted.org.uk Wed Jun 18 06:26:33 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Wed, 18 Jun 2008 10:26:33 +0000 (UTC) Subject: Multiprecision arithmetic library question. References: Message-ID: Michael Press wrote: > I already compiled and installed the GNU multiprecision library > on Mac OS X, and link to it in C programs. > How do I link to the library from Python? You know that Python already supports multiprecision integer arithmetic, right? If you desperately want GMP, though, there's the gmpy module (q.g.). -- [mdw] From ubershmekel at gmail.com Wed Jun 18 02:47:56 2008 From: ubershmekel at gmail.com (Yuvgo0ogle GreeGma1l) Date: Wed, 18 Jun 2008 09:47:56 +0300 Subject: import this Message-ID: <9d153b7c0806172347w1dbc31edkcf94ff34d39e9b11@mail.gmail.com> This guy posted himself singing "import this" aka The Zen Of Python by Tim Peters... http://www.youtube.com/watch?v=kYB72Qa6F9I -- Yuv www.BasementPhilosophy.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From goldnery at gmail.com Wed Jun 25 13:47:41 2008 From: goldnery at gmail.com (Gandalf) Date: Wed, 25 Jun 2008 10:47:41 -0700 (PDT) Subject: Notice For All pyHook users Message-ID: <7e8718e7-2c75-4120-9ba3-dbd1669100f5@a1g2000hsb.googlegroups.com> If you want to compile your program the new py2exe release 0.6.8 wont work! the pyhook function will be ignored you'll have to uninstall the 0.6.8 version and to install the 0.6.6 instead it took me 2 days to find the solution. maybe some day someone will bump the same problem and find this message through google From goldnery at gmail.com Thu Jun 12 22:40:35 2008 From: goldnery at gmail.com (Gandalf) Date: Thu, 12 Jun 2008 19:40:35 -0700 (PDT) Subject: Charset (hopefully for the last time I ask) References: <9a899d5a-fb53-4fd7-8e61-89a04a35c780@d77g2000hsb.googlegroups.com> Message-ID: <1b9e3fab-f938-4e5b-9957-3e9afcd58b99@m36g2000hse.googlegroups.com> OK it did worked! I just should have been encoding to cp1255 search=cnrl.GetValue() search= search.encode("cp1255") cur.execute('select * from hebrew_words where word like ?', ['%'+search+'%']) Thank you! you are the best From google at mrabarnett.plus.com Wed Jun 25 12:05:19 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 25 Jun 2008 09:05:19 -0700 (PDT) Subject: Problems with file IO in a thread, and shutil References: Message-ID: On Jun 25, 4:11?pm, Roopesh wrote: > Hi, > > I have a multithreaded application. There are two threads, T1 and T2. > Suppose that there are two folders A, B. ?Thread T1 fetches data from > network and creates files in folder A and after creating each file, it > moves the file to folder B, using shutil.move(). > > Thread T2, takes files from folder B and processes it. > Note: Only the thread T1 has access to the files in folder A. > > psuedo code > ========= > class T1(thread): > ? ?def run(): > ? ? ?self.download() > > ? def download(): > ? ? ?data = from_network > ? ? ?filename = os.path.join ( "A", "file1") > > ? ? ?f = open ( filename, "w") > ? ? ?for d in data: > ? ? ? ? f.write ( d + "\n" ) > ? ? ?f.flush() > ? ? ?f.close() > > ? ? shutil.move(os.path.join ( "A", "file1"), ?os.path.join("B", > "file1")) > > class T2(thread): > ? run() > ? ? ? process(listdir(os.path.join("B"))) > > All the files has similar contents. But in some cases(very rare), when > thread T1 tries to move the newly created file from folder A to folder > B, an exception occurs (on shutil.move()). > > The exception is WindowsError(32, 'The process cannot access the file > because it is being used by another process'). I looked inside the > shutil.move. What I found was due to this WindowsError, the usual > os.rename() inside shutil.move() fails and the file is copied using > copy2(src, dst). Finally os.unlink() also failed. (So though copying > occurred, deleting the source file failed) > > I am not getting why this error comes. Has anyone faced similar > situation? Please help me. > > Thanks and Regards > Roopesh Do you have any anti-virus/anti-spyware software installed? (If not, why not? :-)) It might be that your anti-virus/anti-spyware software is seeing the new file appear and scanning it. If that happens just when shutil.move() attempts to move it then the move will fail. You could have your code wait for a while and then try again. From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 16 05:29:09 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 16 Jun 2008 11:29:09 +0200 Subject: NoneType Error In-Reply-To: References: Message-ID: <48563265$0$24303$426a74cc@news.free.fr> Gabriel Genellina a ?crit : > En Sun, 15 Jun 2008 05:35:18 -0300, Maryam Saeedi escribi?: (snip) > It appears that you want to catch all exceptions, just use Exception for that: > try: > ... > except Exception: > ... > Hem... That's definitively *not* an a good advice here IMHO. A catch-all may be useful near a program's 'top-level' to handle any other unhandled exception in a more user-friendly way (ie : log the error, warns whoever is in charge, try to cleanly dispose of resources / data / whatever so we don't break anything, and display a nice and visible error message to the user), but anywhere else you really want to know *exactly* which exception(s) you're expecting to handle here and let the other propagate. From sweeneym at acm.org Mon Jun 16 22:38:31 2008 From: sweeneym at acm.org (sweeneym at acm.org) Date: Mon, 16 Jun 2008 19:38:31 -0700 (PDT) Subject: Simple and safe evaluator References: <1de31143-7d8e-42e9-ae9d-8b0a0274ddc3@e53g2000hsa.googlegroups.com> Message-ID: On Jun 17, 8:02 am, bvdp wrote: > Thanks. That was easy :) > > > The change to the _ast version is left as an exercise to the reader ;) > > And I have absolutely no idea on how to do this. I can't even find the > _ast import file on my system. I'm assuming that the _ast definitions > are buried in the C part of python, but that is just a silly guess. > > Bob. If you just need numeric expressions with a small number of functions, I would suggest checking the expression string first with a simple regular expression, then using the standard eval() to evaluate the result. This blocks the attacks mentioned above, and is simple to implement. This will not work if you want to allow string values in expressions though. import re def safe_eval( expr, safe_cmds=[] ): toks = re.split( r'([a-zA-Z_\.]+|.)', expr ) bad = [t for t in toks if len(t)>1 and t not in safe_cmds] if not bad: return eval( expr ) >>> safe_eval( "abs(5*-77+33.1) + (int(405.3) * 5.7e-12)", 'int float sum abs'.split() ) 351.9000000023085 >>> safe_eval( "abs(5*-77+33.1) + (int(405.3) * 5.7e-12)" ) >>> safe_eval( "open('thesis.tex').write('')" ) >>> Mike. From cfbolz at gmx.de Thu Jun 5 19:46:52 2008 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Fri, 06 Jun 2008 01:46:52 +0200 Subject: How "solid" is PyPy? In-Reply-To: <335dcaaa-ac21-4526-91c2-d308b8693c34@e53g2000hsa.googlegroups.com> References: <335dcaaa-ac21-4526-91c2-d308b8693c34@e53g2000hsa.googlegroups.com> Message-ID: <48487AEC.5040707@gmx.de> Hi, miller.paul.w at gmail.com wrote: > I've been looking at PyPy recently, and I see it's reached version 1.0 > (and supports language version 2.4). Given that, I was wondering what > level of backwards-compatibility one can expect from future versions, > i.e. if I run code on, say, a translated stackless PyPy now, what is > the probability that it will run unmodified on PyPy 1.x, 2.x, etc.? That's hard to say. Nobody is using PyPy in any sort of production system yet, so the PyPy team is currently focused mostly on actually becoming useful. Nobody really has a clue what sort of solutions for backward compatibility we will have. Note also that the 1.0 release is sort of oldish already (but no new release has been made). Most people just use SVN head, which is quite stable. Cheers, Carl Friedrich Bolz From basti.wiesner at gmx.net Mon Jun 23 15:46:05 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Mon, 23 Jun 2008 21:46:05 +0200 Subject: Going from Tkinter to pyQT References: Message-ID: Alex Bryan : > I had a guy on this mailing list tell me that pyQT is much better than > Tkinter, and after looking into it a bit I think he is right. However, > I can't find much on it. I want to know if there are any good books or > online tutorials that would be helpful. I doubt there is one, but if > there is one on going from Tkinter to pyQT, that would be amazing. > Well if any of you guys have any tips or suggestions on any of this I > would appreciate it. There are some tutorials mentioned in the official python wiki [1]. Then there is the PyQt wiki [2], which as a section dedicated to tutorials [3]. Moreover I absolutely recommend to read the reference gui from riverbank computing [4]. At last, you should always keep the official docs at hand. They contain plenty of good tutorials and background documents about different Qt4 techniques, that are _definitely_ worth reading. Code samples and API docs are of course kept in C++, but transferring these to Python is mostly easy, the differences are not that big. So you see, there's more than enough PyQt4 stuff out there ;) But the most important thing to do at the transition from Tk to Qt4 goes first, before you start digging any Qt4 specific document: Forget everything, you learned about GUI programming with Tk. Qt4 works complety differently! ;) [1] http://wiki.python.org/moin/PyQt [2] http://www.diotavelli.net/PyQtWiki [3] http://www.diotavelli.net/PyQtWiki/Tutorials [4] http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From Lie.1296 at gmail.com Wed Jun 18 07:11:31 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 18 Jun 2008 04:11:31 -0700 (PDT) Subject: dict order References: <4804032a-adef-4973-ae21-acc4ad2dce37@z72g2000hsb.googlegroups.com> <411fc353-dd54-4bbc-a72e-ddee66408313@c58g2000hsc.googlegroups.com> Message-ID: <1a7a2dc6-4acf-473d-a51c-4715ca9c7068@c19g2000prf.googlegroups.com> On Jun 18, 5:35?pm, cokofree... at gmail.com wrote: > On Jun 18, 12:32 pm, cokofree... at gmail.com wrote: > > > > > On Jun 18, 11:22 am, Robert Bossy wrote: > > > > Hi, > > > > I wish to know how two dict objects are compared. By browsing the > > > archives I gathered that the number of items are first compared, but if > > > the two dict objects have the same number of items, then the comparison > > > algorithm was not mentioned. > > > > Note that I'm not trying to rely on this order. I'm building a > > > domain-specific language where there's a data structure similar to > > > python dict and I need an source of inspiration for implementing > > > comparisons. > > > > Thanks > > > RB > > > I'm a little confused as to what you want. Are you asking whether two > > dictionary objects have the same keys AND values, or just the Keys? > > > As dictionaries are unordered the best technique is to go through one > > dictionary and take out a key, then see if that key exists in the > > other dictionary, and if so do they share the same values. > > > # untested 2.5 > > for keys in dict_one.items(): > > ? if keys in dict_two: > > ? ? if dict_one[keys] != dict_two[keys]: > > ? ? ? # values are different > > ? else: > > ? ? # key is not present > > > This probably isn't the most efficient way, but can quickly find > > differences... > > Whoops > > for keys, values in dict_one.items(): > ? if keys in dict_two: > ? ? if values == dict_two[keys]: > > should also work... Whoops, I think I misunderstood the question. If what you're asking whether two dictionary is equal (equality comparison, rather than sorting comparison). You could do something like this: a = [...] b = [...] s = set() for bk, bv in b.iteritems(): s.add((bk, bv)) for ak, av in a.iteritems(): if not((ak, av) in s): print 'Difference Found!' From moneymakecash2 at gmail.com Mon Jun 9 17:21:15 2008 From: moneymakecash2 at gmail.com (MERLIN) Date: Mon, 9 Jun 2008 14:21:15 -0700 (PDT) Subject: CREDIT CARD Message-ID: <664371be-bdfa-46f2-9a38-b88c87673c44@z24g2000prf.googlegroups.com> ------------------------------------------------------------ http://geocities.com/fixedratecreditcard http://geocities.com/mortgagesoftware1 http://geocities.com/hostingmanagedweb http://geocities.com/compareonlinetrading http://geocities.com/helpdesksoftware From bignose+hates-spam at benfinney.id.au Fri Jun 13 20:43:32 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 14 Jun 2008 10:43:32 +1000 Subject: importing part of a module without executing the rest References: Message-ID: <87y758dex7.fsf@benfinney.id.au> krishna.000.k at gmail.com writes: > file1.py > ---------- > a = 20 > from abc import * > print "Should this be printed when 'a' is alone imported from this > module" > > file2.py > ---------- > from file1 import a > print a > > file2.py is used in a context where 'from abc import *' statement > doesn't make sense but it can make sense of (and requires) 'a'. > But it seems we can't import just a part of the module and expect the > rest to not be executed. > Executing python file2.py executes the 'from abc ...' and the print > statement following it in file1.py. That's right. That's what 'import' is documented to do. Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace ? ? to ``initialize'' a Python-coded module meansto execute the module's body. > Can't I just import 'a' into this name scope without touching the > rest of the statements in the module (file1 in this case). If so, > what the rationale behind such logic in the module 'import' > mechanism of python? The purpose of dividing code into separate modules is to have all the code in those modules executed by an 'import' statement. If you want some code to be executed under some circumstances and other code not executed, they need to be separated somehow. > Don't I have any solution other than packaging those parts in > file1.py (a = 20 and the rest of the statements) into different > modules? Let me turn that around: What are you actually trying to do, and how does that conflict with separating code that seems (from your description) conceptually separate anyway? One possible answer could be to define a module-level function. This would mean that at 'import' time, the 'def' statement is executed and the function defined, but the code inside it is not executed until you call the function at some later time. This also has the beneficial effect of defining a specific interface for using that code. Whether that's appropriate to your situation is impossible to say without knowing what you are trying to do. -- \ ?Never do anything against conscience even if the state | `\ demands it.? ?Albert Einstein | _o__) | Ben Finney From apardon at forel.vub.ac.be Mon Jun 9 07:40:54 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 9 Jun 2008 11:40:54 GMT Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> Message-ID: On 2008-06-07, David wrote: > Would it be possible for a 3rd-party threading library to an > 'interruptible' version of Queue? > > The same methods as the normal Queue, but when you call a new .kill() > method on the queue, all the threads locking on the queue get a > "QueueKilled" exception thrown. I have done something similar. The idea was that threads had to open a queue before they could access it. If the last thread who had the queue open in write mode, closed the queue, a reader trying to get an element from an empty queue would have an "EOInformation" exception raised. -- Antoon Pardon From omer at no-log.org Thu Jun 26 07:39:09 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Thu, 26 Jun 2008 13:39:09 +0200 Subject: extend getattr() In-Reply-To: <0d1da457-b026-4e38-824b-c8cbde172bf7@m36g2000hse.googlegroups.com> References: <0d1da457-b026-4e38-824b-c8cbde172bf7@m36g2000hse.googlegroups.com> Message-ID: <200806261339.09527.omer@no-log.org> Le Thursday 26 June 2008 13:06:53 Rotlaus, vous avez ?crit?: > Hello, > > lets assume i have some classes: > > class A(object): > def __init__(self): > b = B() > > class B(object): > def __init__(self): > c = C() > note you're just defining some local variables here, should be self.b = B() and self.c = C(). > class C(object): > def __init__(self): > pass > > and now i wanna do something like this: > > a=A() > c=getattr(a, 'b.c') > > I know this doesn't work, but what can i do to get this or a similar > functionality to get it work for this sample and for even more nested > classes? > You could do it manually: c = getattr(getattr(a, 'b'), 'c') or make it automatic: def get_dotted_attr (obj, dotted_attr) : for attr in dotted_attr.split('.') : obj = getattr(obj, attr) return obj a = A() print 'a.b.c = %s' % get_dotted_attr(a, 'b.c') -- C?dric Lucantis From danb_83 at yahoo.com Mon Jun 16 23:43:55 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Mon, 16 Jun 2008 20:43:55 -0700 (PDT) Subject: Does '!=' equivelent to 'is not' References: Message-ID: <6f86763c-6583-4c7c-b866-0cae21aeebaf@g16g2000pri.googlegroups.com> On Jun 16, 10:29?pm, pirata wrote: > I'm a bit confusing about whether "is not" equivelent to "!=" > > if a != b: > ? ... > > if a is not b: > ? ... > > What's the difference between "is not" and "!=" or they are the same thing? "is not" is the logical negation of the "is" operator, while "!=" is the logical negation of the "==" operator. The difference is equality versus identity. >>> a = [1, 2, 3] >>> b = [1, 2, 3] >>> a == b True >>> a is b False From alexnbryan at gmail.com Tue Jun 10 13:54:03 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 10 Jun 2008 10:54:03 -0700 (PDT) Subject: problems with opening files due to file's path In-Reply-To: References: <17759531.post@talk.nabble.com> Message-ID: <17761126.post@talk.nabble.com> Hey thanks!, both the raw and the double backslashes worked. You are a gentleman and a scholar. Mike Driscoll wrote: > > On Jun 10, 11:45 am, Alexnb wrote: >> Gerhard H?ring wrote: >> >> > Alexnb wrote: >> >> Okay, so what I want my program to do it open a file, a music file in >> >> specific, and for this we will say it is an .mp3. Well, I am using the >> >> system() command from the os class. [...] >> >> >> system("\"C:\Documents and Settings\Alex\My Documents\My >> >> Music\Rhapsody\Bryanbros\Weezer\(2001)\04 - Island In The Sun.wma\"") >> >> [...] >> >> > Try os.startfile() instead. It should work better. >> >> > -- Gerhard >> >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> No, it didn't work, but it gave me some interesting feedback when I ran >> it >> in the shell. Heres what it told me: >> >> >>> os.startfile("C:\Documents and Settings\Alex\My Documents\My >> >>> Music\Rhapsody\Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm >> >>> Yours.wma") >> >> Traceback (most recent call last): >> File "", line 1, in >> os.startfile("C:\Documents and Settings\Alex\My Documents\My >> Music\Rhapsody\Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm >> Yours.wma") >> >> WindowsError: [Error 2] The system cannot find the file specified: >> "C:\\Documents and Settings\\Alex\\My Documents\\My >> Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\x01 - I'm >> Yours.wma" >> >> See it made each backslash into two, and the one by the parenthesis and >> the >> 0 turned into an x.... >> -- >> View this message in >> context:http://www.nabble.com/problems-with-opening-files-due-to-file%27s-pat... >> Sent from the Python - python-list mailing list archive at Nabble.com. > > Yeah. You need to either double all the backslashes or make it a raw > string by adding an "r" to the beginning, like so: > > os.startfile(r'C:\path\to\my\file') > > HTH > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17761126.html Sent from the Python - python-list mailing list archive at Nabble.com. From szrRE at szromanMO.comVE Mon Jun 2 01:45:25 2008 From: szrRE at szromanMO.comVE (szr) Date: Sun, 1 Jun 2008 22:45:25 -0700 Subject: The Importance of Terminology's Quality References: <4840ab73$0$90274$14726298@news.sunsite.dk> <4841f0aa$0$90274$14726298@news.sunsite.dk> <48432b01$0$90272$14726298@news.sunsite.dk> Message-ID: Arne Vajh?j wrote: > szr wrote: >> Arne Vajh?j wrote: >>> szr wrote: >>>> Peter Duniho wrote: >>>>> On Fri, 30 May 2008 22:40:03 -0700, szr >>>>> wrote: >>>>>> Arne Vajh?j wrote: >>>>>>> Stephan Bour wrote: >>>>>>>> Lew wrote: >>>>>>>> } John Thingstad wrote: >>>>>>>> } > Perl is solidly based in the UNIX world on awk, sed, } > >>>>>>>> bash and C. I don't like the style, but many do. >>>>>>>> } >>>>>>>> } Please exclude the Java newsgroups from this discussion. >>>>>>>> >>>>>>>> Did it ever occur to you that you don't speak for entire news >>>>>>>> groups? >>>>>>> Did it occur to you that there are nothing about Java in the >>>>>>> above ? >>>>>> Looking at the original post, it doesn't appear to be about any >>>>>> specific language. >>>>> Indeed. That suggests it's probably off-topic in most, if not >>>>> all, of the newsgroups to which it was posted, inasmuch as they >>>>> exist for topics specific to a given programming language. >>>> Perhaps - comp.programming might of been a better place, but not >>>> all people who follow groups for specific languages follow a >>>> general group like that - but let me ask you something. What is it >>>> you really have against discussing topics with people of >>>> neighboring groups? Keep in mind you don't have to read anything >>>> you do not want to read. [1] >>> I very much doubt that the original thread is relevant for the Java >>> group. >>> >>> But the subthread Lew commente don was about Perl and Unix. That is >>> clearly off topic. >> >> I agree with and understand what you are saying in general, but >> still, isn't it possible that were are people in the java group (and >> others) who might of been following the thread, only to discover >> (probably not right away) that someone decided to remove the group >> they were reading the thread from? I know I would not like that, >> even if it wasn't on topic at the branch. >> >> Personally, I find it very annoying to have to switch news groups in >> order to resume a thread and weed my way down the thread to where it >> left off before it was cut off from the previous group. > > I am relative tolerant towards threads that are a bit off topic, if > the S/N ratio overall is good. Agreed. [...] If a thread, that is cross-posted, branches off on a tangent that has nothing to do with one or more groups what so ever, then yes, it makes sense to prune the 'newsgroup:' list / set follow ups, but in this case, someone made one mention or so of 'Perl', which was being used as an example, and someone (lew) moved to have the Java group removed. There was little reason to cut off the thread, when people very well may have been following it, over the utterance of one word, which was being used as an example. The bulk of the thread had to do with general programming, and suddenly writing the name of a language doesn't mean it's way off on a tangent. I hope this clears up some waters. Regards. -- szr From cfbolz at gmx.de Thu Jun 5 19:46:52 2008 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Fri, 06 Jun 2008 01:46:52 +0200 Subject: How "solid" is PyPy? In-Reply-To: <335dcaaa-ac21-4526-91c2-d308b8693c34@e53g2000hsa.googlegroups.com> References: <335dcaaa-ac21-4526-91c2-d308b8693c34@e53g2000hsa.googlegroups.com> Message-ID: <48487AEC.5040707@gmx.de> Hi, miller.paul.w at gmail.com wrote: > I've been looking at PyPy recently, and I see it's reached version 1.0 > (and supports language version 2.4). Given that, I was wondering what > level of backwards-compatibility one can expect from future versions, > i.e. if I run code on, say, a translated stackless PyPy now, what is > the probability that it will run unmodified on PyPy 1.x, 2.x, etc.? That's hard to say. Nobody is using PyPy in any sort of production system yet, so the PyPy team is currently focused mostly on actually becoming useful. Nobody really has a clue what sort of solutions for backward compatibility we will have. Note also that the 1.0 release is sort of oldish already (but no new release has been made). Most people just use SVN head, which is quite stable. Cheers, Carl Friedrich Bolz From sturlamolden at yahoo.no Wed Jun 4 10:07:44 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 4 Jun 2008 07:07:44 -0700 (PDT) Subject: How to perform a nonblocking read from a process References: <15c889d4-3e06-4ffd-a86e-10cfa87d3bc5@k37g2000hsf.googlegroups.com> <618bd3d7-1b49-48f5-84b4-e32934ce727c@g16g2000pri.googlegroups.com> Message-ID: <712e3834-2a62-4f98-ad8d-0d1bd8c73c05@z72g2000hsb.googlegroups.com> On Jun 4, 8:45 am, rdab... at gmail.com wrote: > I've to admit I'm a newbie to this kind of programming... > what if I have to run thousands of these commands...it doesn't make > sense to create > thousands of threads.. > Is there a way that above mentioned piece of code be made to worked... Are you planning on doing thousands of simultaneous asynchronous I/O calls? How many processes are you communicating with? Take a look at the twisted framwork (twistedmatrix.org) or perhaps i/o completion ports on Windows (e.g. win32file.CreateIoCompletionPort in PyWin32). But if you need that king of scalability, I suggest you start by reconsidering the design. If you are communicating with only one process, you don't need thousands of threads, just one. Keep the thread idle until you need it again. Here is a simple worker thread that allows you to do multiple, different function calls in a background thread (you can shut it down by passing None to setTask). import threading import Queue class WorkerThread(threading.Thread): def __init__(self): self.taskQueue = Queue.Queue(0) self.resQueue = Queue.Queue(0) self.setDaemon(True) def run(self): while 1: fun, args, kwarg = self.taskQueue.get() if (fun is None): break self.resQueue.put(fun(*args,**kwarg)) def setTask(self, fun, *args, **kwarg): self.taskQueue.set((fun, args, kwarg)) def getResult(self): return self.resQueue.get() def probeResult(self): return not self.resQueue.empty() Rewrite of your examples: from subprocess import * p2 = Popen('python',stdin=PIPE,stdout=PIPE,universal_newlines=True) worker = WorkerThread() for i in range(10): worker.setTask(p2.stdin.write, 'print 10'+'\n') worker.setTask(p2.stdout.readline) worker.getResult() # wait for write to finish o,e = worker.getResult() # wait for read to finish print o,e from subprocess import * p2 = Popen('python',stdin=PIPE,stdout=PIPE,universal_newlines=True) writer = WorkerThread() reader = WorkerThread() for i in range(10): writer.setTask(p2.stdin.write, 'print 10'+'\n') reader.setTask(p2.stdout.readline) o,e = reader.getResult() # wait for read to finish print o,e From chrispoliquin at gmail.com Wed Jun 18 11:12:16 2008 From: chrispoliquin at gmail.com (chrispoliquin at gmail.com) Date: Wed, 18 Jun 2008 08:12:16 -0700 (PDT) Subject: urllib (54, 'Connection reset by peer') error References: <92ecee86-ba92-4f14-b4f8-05064ef5406c@f63g2000hsf.googlegroups.com> Message-ID: Thanks for the help. The error handling worked to a certain extent but after a while the server does seem to stop responding to my requests. I have a list of about 7,000 links to pages I want to parse the HTML of (it's basically a web crawler) but after a certain number of urlretrieve() or urlopen() calls the server just stops responding. Anyone know of a way to get around this? I don't own the server so I can't make any modifications on that side. From info at egenix.com Mon Jun 16 06:12:54 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Mon, 16 Jun 2008 12:12:54 +0200 Subject: ANN: eGenix mxODBC Connect Database Interface for Python 0.9.1 (beta) Message-ID: <48563CA6.1090202@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com mxODBC Connect Database Interface for Python Version 0.9.1 (beta) Our new client-server product for connecting Python applications to relational databases - on all major platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mxODBC-Connect-0.9.1-beta.html ________________________________________________________________________ INTRODUCTION The mxODBC Connect Database Interface for Python allows users to easily connect Python applications to all major databases on the market today in a highly portable and convenient way. This makes mxODBC Connect the ideal basis for writing cross-platform database programs and utilities in Python. mxODBC Connect extends our eGenix mx Python Extension series with a new client-server based product, that removes the need to install and configure ODBC drivers on the client side. This greatly simplifies setup and configuration of database driven client applications, while at the same time making the network communication between client and database server more efficient and more secure. * About Python: Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. * About eGenix: eGenix is a consulting and software product company focused on providing professional quality services and products to Python users and developers (http://www.egenix.com/). ________________________________________________________________________ HOW IT WORKS mxODBC Connect consists of two parts: a server installation which typically runs directly on the database server and a client Python package which is installed on the client machine that runs the Python application. The server part uses our high-performance database adapter mxODBC to connect to the database server. The client package communicates with the server part over a TCP/IP network, optionally using SSL encryption, advanced authentication and access controls - a feature that many database drivers fail to deliver. By separating the client application database interface from the server and using mxODBC Connect, you gain several benefits: * high portability and flexibility * centralized configuration and administration * added security * automatic fail-over * scalability * lower costs For more information, please have a look at the product page: http://www.egenix.com/products/python/mxODBCConnect/ ________________________________________________________________________ NEWS mxODBC Connect 0.9 is a public beta release of our new mxODBC Connect product. If you would like to participate in the beta, please see our beta program page: http://www.egenix.com/products/python/mxODBCConnect/beta.html *SPECIAL OFFER* In order to make participation in the beta program more interesting for our users, we will be giving out *free discount coupons* to all participants who report back bugs in the product. ________________________________________________________________________ DOWNLOADS The download archives as well as instructions for installation and configuration of the product can be found on the product page: http://www.egenix.com/products/python/mxODBCConnect/ _______________________________________________________________________ SUPPORT Commercial support for this product is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jun 16 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania 20 days to go :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From jonrob at fedoraproject.org Sun Jun 22 07:52:11 2008 From: jonrob at fedoraproject.org (Jonathan Roberts) Date: Sun, 22 Jun 2008 12:52:11 +0100 Subject: Learning Python in a group In-Reply-To: <18c1e6480806220422x5d06c54byd23b249bb699691f@mail.gmail.com> References: <507738ef0806220343r3e9ea053neeec0baf0ccfdbe6@mail.gmail.com> <18c1e6480806220422x5d06c54byd23b249bb699691f@mail.gmail.com> Message-ID: <507738ef0806220452s74358615v44518469cf3b5f45@mail.gmail.com> > If you want people to meet with you (in person) as a mentor you should > probably ask on your local Python or Linux users group mailing list. We're not really too worried about doing it in person - mostly because the people doing it so far are all at least 1000 miles away from each other :) Best, Jon > -- > http://mail.python.org/mailman/listinfo/python-list > From tommy.nordgren at comhem.se Thu Jun 19 07:48:44 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Thu, 19 Jun 2008 13:48:44 +0200 Subject: Python-3.0b1 build fails on Linux : _gestalt In-Reply-To: <6bupftF3d2d0kU1@mid.dfncis.de> References: <6bupftF3d2d0kU1@mid.dfncis.de> Message-ID: <071F3423-3EE0-49D5-BD2F-8DCD9A764D65@comhem.se> On 19 jun 2008, at 12.07, Helmut Jarausch wrote: > Hi, > > trying to build Python-3.0b1 on my Gentoo Linux box fails with > > Failed to find the necessary bits to build these modules: > _gestalt > > Looking at setup.py it seems that module '_gestalt' > is only needed on Darwin but my build on Linux fails > nevertheless. > > Thanks for any hints, > > Helmut Jarausch > > Lehrstuhl fuer Numerische Mathematik > RWTH - Aachen University > D 52056 Aachen, Germany > -- > http://mail.python.org/mailman/listinfo/python-list Have you run the configure script? This might happen if you have copied the directory from a machine with Darwin/Mac OS X ----------------------------------- See the amazing new SF reel: Invasion of the man eating cucumbers from outer space. On congratulations for a fantastic parody, the producer replies : "What parody?" Tommy Nordgren tommy.nordgren at comhem.se From gherron at islandtraining.com Wed Jun 11 11:54:19 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 11 Jun 2008 08:54:19 -0700 Subject: How to find duplicate 3d points? In-Reply-To: References: Message-ID: <484FF52B.7080403@islandtraining.com> oprah.chopra at gmail.com wrote: > I have a large data file of upto 1 million x,y,z coordinates of > points. I want to identify which points are within 0.01 mm from each > other. I can compare the distance from each point to every other > point , but this takes 1 million * 1 million operations, or forever! > > Any quick way to do it, perhaps by inserting just the integer portion > of the coordinates into an array, and checking if the integer has > already been defined before inserting a new point? > -- > http://mail.python.org/mailman/listinfo/python-list > There is a whole field of Math/CS research on problems like this called Computational Geometry. It provides many algorithms for many geometric problems, including things like this. In particular, to categorize a list of points and find the NearestNeighbor, I'd suggest a KD-tree. I believe this would turn your problem from O(N^2) to O(N log n) or so. Happy google-ing and good luck. Gary Herron From gagsl-py2 at yahoo.com.ar Wed Jun 18 18:09:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Jun 2008 19:09:14 -0300 Subject: Getting Python exit code when calling Python script from Java program References: Message-ID: En Wed, 18 Jun 2008 08:09:58 -0300, A.T.Hofkamp escribi?: > On 2008-06-18, Quill_Patricia at emc.com wrote: >> picking up 0. On investigation it turned out that the exit value being >> read is from python.exe process, not from the Python script. Is there >> any way I can obtain the return value of a python script from a Java > > This is not what I see happening here: > > x.py: > import sys > sys.exit(138) > > % python2.4 x.py > % echo $? > 138 > > as you can see, the mechanism works at my Linux system. It works fine on Windows too, the OS she appears to be using: C:\TEMP>python x.py C:\TEMP>echo %ERRORLEVEL% 138 -- Gabriel Genellina From root at sys1.org Mon Jun 23 10:54:29 2008 From: root at sys1.org (Andreu) Date: Mon, 23 Jun 2008 16:54:29 +0200 Subject: String question References: Message-ID: Wow...about ten seconds to get a kind response .... Thanks Tim. Andrew. Tim Golden wrote: > Andreu wrote: >> I want to split a sentence and assign each word to a variable. >> In Ruby I can do it as: >> >> v1,v2,v3,v4,v5 = str1.split >> >> Which will be the Python equivalent ? Thanks. > > That would be: > > str1 = "The quick brown fox jumps" > v1, v2, v3, v4, v5 = str1.split () > > TJG From Lie.1296 at gmail.com Sun Jun 29 06:20:19 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 29 Jun 2008 03:20:19 -0700 (PDT) Subject: What is "@" used for ? References: Message-ID: On Jun 29, 3:39?pm, gops wrote: > Hi. > > I am noob in python. while reading some source code I came across , > this funny thing called @ in some function , > > def administrator(method): > ? ? @functools.wraps(method) > ? ? def wrapper(self, *args, **kwargs): > ? ? ? ? user = users.get_current_user() > ? ? ? ? if not user: > ? ? ? ? ? ? if self.request.method == "GET": > > self.redirect(users.create_login_url(self.request.uri)) > ? ? ? ? ? ? ? ? return > ? ? ? ? ? ? raise web.HTTPError(403) > ? ? ? ? elif not users.is_current_user_admin(): > ? ? ? ? ? ? raise web.HTTPError(403) > ? ? ? ? else: > ? ? ? ? ? ? return method(self, *args, **kwargs) > ? ? return wrapper > > now what is that "@" used for ? I tried to google , but it just omits > the "@" and not at all useful for me(funny!! :D) > > It will be enough if you can just tell me some link where i can look > for it.. > > Thank you in advance. :D @ is decorator. It's a syntax sugar, see this example: class A(object): @decorate def blah(self): print 'blah' is the same as: class A(object): def blah(self): print 'blah' blah = decorate(blah) Now you know the name, I guess google will help you find the rest of the explanation. From ayushi.mehra at gmail.com Mon Jun 16 01:14:30 2008 From: ayushi.mehra at gmail.com (Ayushi Mehra) Date: Sun, 15 Jun 2008 22:14:30 -0700 (PDT) Subject: Samsung SyncMaster 940 NW Monitors Message-ID: Samsung SyncMaster 940 NW Monitors inch, LCD, Colour monitor consumes 38 watts of power per hour, has digital user controls and a maximum resolution of 1280x1024 dpi. The screen is flat with anti-glare and anti-static coating. Its other features like MagicTune, MagicBright and MagicSpeed. It is a wide screen monitor with 5ms response time and a contrast ratio of 700:1. It is available in high glossy black colour. It has DVI-D input. To buy this Samsung SyncMaster 940 NW Monitors Please visit to http://www.naaptol.com/buy-online/WO-best-deals-shopping-W664O/computers_-_peripherals/monitors/samsung__syncmaster_940_nw.html From roopesh.raj at gmail.com Mon Jun 23 01:23:02 2008 From: roopesh.raj at gmail.com (Roopesh) Date: Sun, 22 Jun 2008 22:23:02 -0700 (PDT) Subject: POP3_SSL Error Message-ID: Hi, While using poplib to fetch mails from my gmail account, I am getting the following error: Exception is POP3_SSL instance has no attribute 'sslobj' Can anyone tell me what this error means. Thanks and Regards Roopesh From google at mrabarnett.plus.com Tue Jun 3 20:08:44 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 3 Jun 2008 17:08:44 -0700 (PDT) Subject: Ideas for master's thesis References: Message-ID: On Jun 3, 10:22 pm, Larry Bugbee wrote: > > I would like to do something with this language, yet > > I don't know if there are any needs/science fields, that could be used > > as a basis for a thesis. > > Personally, I'd like to see *optional* data typing added to Python > perhaps along the lines of what was done in Pyrex. You declare the > data type when you know it, or when it matters, and skip it > otherwise. Your paper could analyze its pros and cons, analyze any > potential performance gains, and recommend how to implement it. Your > professor will suggest some additional questions. > > I suspect, if the type be known and declared, the interpreter could be > streamlined and quicker, you might get asserts for free, and perhaps, > Python becomes even more self-documenting. Perhaps I've missed it, > but I haven't seen a strong analytical case made for or against > optional data typing. Your paper? > You might want to have a look at Boo at http://boo.codehaus.org/. From kyosohma at gmail.com Mon Jun 9 12:20:31 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 9 Jun 2008 11:20:31 -0500 Subject: How to get full path to script? In-Reply-To: References: Message-ID: On Mon, Jun 9, 2008 at 11:07 AM, kj wrote: > In "Mike Driscoll" writes: > >>For my compiled scripts, I usually use this variation: > >>path = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))) > > Thanks. But why the os.path.join()? (BTW, I did read the docs > before posting, but they make no sense to me; they say that > os.path.join joins "one or more path components intelligently", > but what does it mean to join *one* component?) > > Kynn > > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. > -- > http://mail.python.org/mailman/listinfo/python-list > The idea of the join method is to create the path in an OS agnostic fashion. Linux uses forward slashes and Windows uses backward slashes to join the parts. The join method does this for you so you don't have to. I think in this case, if I had my program installed to C:\Program Files\MyProgram It would put the slashes in correctly for Windows. However, there are ways to get the default program directory in Linux and then have the os.path.join create the path correctly there too. That's the idea anyway. Hopefully that isn't more confusing than what you read. Mike From dmitrey.kroshko at scipy.org Sun Jun 15 16:24:39 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sun, 15 Jun 2008 13:24:39 -0700 (PDT) Subject: ANN: OpenOpt 0.18 (numerical optimization framework) Message-ID: Greetings, We're pleased to announce: OpenOpt 0.18 (release), free (license: BSD) optimization framework (written in Python language) with connections to lots of solvers (some are C- or Fortran-written) is available for download. Changes since previous release 0.17 (March 15, 2008): * connection to glpk MILP solver (requires cvxopt v >= 1.0) * connection to NLP solver IPOPT (requires python-ipopt wrapper installation, that is currently available for Linux only, see openopt NLP webpage for more details) * major changes for NLP/NSP solver ralg * splitting non-linear constraints can benefit for some solvers * unified text output for NLP solvers * handling of maximization problems (via p.goal = 'max' or 'maximum') * some bugfixes, lots of code cleanup Newsline: http://openopt.blogspot.com/ Homepage: http://scipy.org/scipy/scikits/wiki/OpenOpt Regards, OpenOpt developers. From gagsl-py2 at yahoo.com.ar Mon Jun 2 22:11:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 02 Jun 2008 23:11:56 -0300 Subject: Continuous Timer References: <496954360805301850u4ce63746vc8fcc84ad1b72824@mail.gmail.com> Message-ID: En Fri, 30 May 2008 22:50:13 -0300, Robert Dailey escribi?: > Reading through the Python 2.5 docs, I'm seeing a Timer class in the > threading module, however I cannot find a timer object that will > continuously call a function of my choice every XXXX amount of > milliseconds. > For example, every 1000 milliseconds I want a function named Foo to be > called. This would continue to happen until I terminate the timer in my > main > thread. Thanks for the help. Use an Event object; its wait() will provide the sleep time, and when it is set() the thread knows it has to exit. import threading import time def repeat(event, every, action): while True: event.wait(every) if event.isSet(): break action() def foo(): print "I'm bored to death..." print "creating event and thread" ev = threading.Event() t1 = threading.Thread(target=repeat, args=(ev, 1.0, foo)) print "starting thread" t1.start() print "waiting for 10 seconds in main thread" time.sleep(10) print "setting event" ev.set() print "waiting for thread to finish" t1.join() print "quit" -- Gabriel Genellina From google at mrabarnett.plus.com Sun Jun 15 19:48:42 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 15 Jun 2008 16:48:42 -0700 (PDT) Subject: please critique my thread code References: <222a1935-20dd-44a0-bc42-71a25be96d30@79g2000hsk.googlegroups.com> Message-ID: On Jun 15, 2:29 pm, wins... at cs.wisc.edu wrote: > I wrote a Python program (103 lines, below) to download developer data > from SourceForge for research about social networks. > > Please critique the code and let me know how to improve it. > > An example use of the program: > > prompt> python download.py 1 240000 > > The above command downloads data for the projects with IDs between 1 > and 240000, inclusive. As it runs, it prints status messages, with a > plus sign meaning that the project ID exists. Else, it prints a minus > sign. > > Questions: > > --- Are my setup and use of threads, the queue, and "while True" loop > correct or conventional? > > --- Should the program sleep sometimes, to be nice to the SourceForge > servers, and so they don't think this is a denial-of-service attack? > > --- Someone told me that popen is not thread-safe, and to use > mechanize. I installed it and followed an example on the web site. > There wasn't a good description of it on the web site, or I didn't > find it. Could someone explain what mechanize does? > > --- How do I choose the number of threads? I am using a MacBook Pro > 2.4GHz Intel Core 2 Duo with 4 GB 667 MHz DDR2 SDRAM, running OS > 10.5.3. > > Thank you. > > Winston > [snip] String methods are quicker than regular expressions, so don't use regular expressions if string methods are perfectly adequate. For example, you can replace: error_pattern = re.compile(".*\n\n.*", re.DOTALL) ... valid_id = not error_pattern.match(text) with: error_pattern = "\n\n" ... valid_id = error_pattern not in text From tjreedy at udel.edu Sat Jun 14 14:58:18 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 14 Jun 2008 14:58:18 -0400 Subject: Was the move to Python 2.0 as big a deal? References: <4853f365$0$11601$607ed4bc@cv.net> Message-ID: "John Salerno" wrote in message news:4853f365$0$11601$607ed4bc at cv.net... | Just curious if people put up any resistance to 2.0 like some people do | for 3.0. Was it as big of a change in the language, or was the | transition smoother? 2.0 (from BeOpen) was essentially 1.6 (final CNRI version) rebranded. A bigger change was 2.2 which introduced new-style classes, the new iterator protocol, and generators. From usenet at technicalbloke.com Thu Jun 19 03:24:43 2008 From: usenet at technicalbloke.com (Roger Heathcote) Date: Thu, 19 Jun 2008 08:24:43 +0100 Subject: please critique my thread code In-Reply-To: References: <222a1935-20dd-44a0-bc42-71a25be96d30@79g2000hsk.googlegroups.com> Message-ID: <9ZWdnVMfvdwglMfVnZ2dnUVZ8q_inZ2d@bt.com> MRAB wrote: > On Jun 15, 2:29 pm, wins... at cs.wisc.edu wrote: >> I wrote a Python program (103 lines, below) to download developer data >> from SourceForge for research about social networks. >> >> Please critique the code and let me know how to improve it. >> >> An example use of the program: >> >> prompt> python download.py 1 240000 >> >> The above command downloads data for the projects with IDs between 1 >> and 240000, inclusive. As it runs, it prints status messages, with a >> plus sign meaning that the project ID exists. Else, it prints a minus >> sign. >> >> Questions: >> >> --- Are my setup and use of threads, the queue, and "while True" loop >> correct or conventional? >> >> --- Should the program sleep sometimes, to be nice to the SourceForge >> servers, and so they don't think this is a denial-of-service attack? >> >> --- Someone told me that popen is not thread-safe, and to use >> mechanize. I installed it and followed an example on the web site. >> There wasn't a good description of it on the web site, or I didn't >> find it. Could someone explain what mechanize does? >> >> --- How do I choose the number of threads? I am using a MacBook Pro >> 2.4GHz Intel Core 2 Duo with 4 GB 667 MHz DDR2 SDRAM, running OS >> 10.5.3. >> >> Thank you. >> >> Winston >> > [snip] > String methods are quicker than regular expressions, so don't use > regular expressions if string methods are perfectly adequate. For > example, you can replace: Erm, shurely the bottleneck will be bandwidth not processor/memory?* If it isn't then - yes, you run the risk of actually DOSing their servers! Your mac will run thousands of threads comfortably but your router may not handle the thousands of TCP/IP connections you throw at it very well, especially if it is a domestic model, and sure as hell sourceforge aren't going to want more than a handfull of concurrent connections from you. Typical sourceforge page ~ 30K Project pages to read = 240000 = ~6.8 Gigabytes Maybe send their sysadmin a box of chocolates if you want to grab all that in any less than a week and not get your IP blocked! :) Roger Heathcote * Of course, stylistically, MRAB is perfectly right about not wasting CPU on regexes where string methods will do, unless you are planning on making your searches more elaborate in the future. From miller.paul.w at gmail.com Mon Jun 2 04:03:05 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Mon, 2 Jun 2008 01:03:05 -0700 (PDT) Subject: Writing HTML Message-ID: <3760e9d1-d385-4e36-8ca6-e03e48ffdfbf@c58g2000hsc.googlegroups.com> I've searched the standard library docs, and, while there are a couple options for *reading* HTML from Python, I didn't notice any for *writing* it. Does anyone have any recommendations (particularly ones not listed on PyPI)? Thanks From Protectorates at gmail.com Wed Jun 4 17:02:49 2008 From: Protectorates at gmail.com (topher) Date: Wed, 4 Jun 2008 14:02:49 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> Message-ID: On Jun 4, 2:58 pm, "Russ P." wrote: > On Jun 4, 4:29 am, NickC wrote: > > > On Jun 4, 4:09 am, "Russ P." wrote: > > > > What is it about leading underscores that bothers me? To me, they are > > > like a small pebble in your shoe while you are on a hike. Yes, you can > > > live with it, and it does no harm, but you still want to get rid of it. > > > With leading underscores, you can see *at the point of dereference* > > that the code is accessing private data. With a "this is private" > > keyword you have no idea whether you're accessing private or public > > data, because the two namespaces get conflated together. > > That is true. But with the "priv" keyword you'll discover quickly > enough that you are trying to access private data (as soon as you run > the program). And even if a "priv" keyword is added, you are still > free to use the leading underscore convention if you wish. > > The idea of being able to discern properties of an object by its name > alone is something that is not normally done in programming in > general. Yes, of course you should choose identifiers to be > descriptive of what they represent in the real world, but you don't > use names like "intCount," "floatWeight," or "MyClassMyObject" would > you? Why not? That would tell you the type of the object at the "point > of dereferencing," wouldn't it? Sounds familiar. http://en.wikipedia.org/wiki/Hungarian_notation From deveeshree02 at gmail.com Mon Jun 9 11:29:10 2008 From: deveeshree02 at gmail.com (deveeshree) Date: Mon, 9 Jun 2008 08:29:10 -0700 (PDT) Subject: ANYONE CAN POST ANY TOPIC!! UPLOAD & EDIT FILES, INVITE FRIENDS!!! Message-ID: ANYONE CAN POST ANY TOPIC!! UPLOAD & EDIT FILES, INVITE FRIENDS!!! Welcoming you to ENJOY my Group ?ENJOY?. Please Click this Link: http://groups.google.com/group/enjoy00 From fuzzyman at gmail.com Tue Jun 10 17:41:28 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Tue, 10 Jun 2008 14:41:28 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <6e6df35e-e641-44d9-9f56-c0732306eec2@q27g2000prf.googlegroups.com> <13db98b5-ed2e-45ef-97ec-ad3caeeed10e@j1g2000prb.googlegroups.com> Message-ID: <074caf4a-de1e-4290-b688-30148786952c@z72g2000hsb.googlegroups.com> On Jun 10, 2:03?am, Rhamphoryncus wrote: > On Jun 9, 2:52 pm, Fuzzyman wrote: > > > > > On Jun 9, 9:20 pm, Rhamphoryncus wrote: > > > > On Jun 9, 5:33 am, Antoon Pardon wrote: > > > > > On 2008-06-07, Rhamphoryncus wrote: > > > > > > On Jun 6, 12:44 pm, The Pythonista wrote: > > > > >> It's always been my understanding that you can't forcibly kill a thread > > > > >> in Python (at least not in a portable way). ?The best you can do is > > > > >> politely ask it to die, IIRC. > > > > > > Inherently, the best you can do in most languages is ask them politely > > > > > to die. ?Otherwise you'll leave locks and various other datastructures > > > > > in an inconvenient state, which is too complex to handle correctly. > > > > > The exception is certain functional languages, which aren't capable of > > > > > having threads and complex state in the same sense. > > > > > Well it would of course depend on what is considered asking politely? > > > > > If one thread could cause an exception being thrown in an other thread, > > > > would this be considered a polite way to ask? Would it be considered > > > > an acceptable way? > > > > The exception must not be raised until a point explicitly designed as > > > safe is hit. ?Otherwise, any function that manipulates data you'll > > > still use will potentially be buggered. ?Consider sys.stdout: codecs, > > > buffering, lots to go wrong. > > > Java and .NET both have ways of killing threads. They both work by > > raising a 'ThreadAbort' (or similar) exception in the target thread. > > In early implementations they both suffered from a similar problem. > > You could protect locks (etc) by having a finally block that would > > release all resources as needed - but what happens if the thread abort > > exception is raised *inside* the finally block? > > > Java responded by deprecating thread aborting. .NET responded by > > ensuring that a thread abort exception would never be raised inside a > > finally block - if that happened the exception would only be raised > > once the code has left the finally block. > > > Aborting threads in .NET can be extremely useful. Politely asking a > > thread to die is no good if the task the thread is executing is > > extremely coarse grained - it may not be able to respond to the > > request for some time. If your code is structured correctly > > (performing a long running background calculation for example) then > > you may *know* that you can kill it without problems, but Python has > > no native API to do this. > > So how does .NET deal with the sys.stdout corruption? ?Does it? > That has never been an issue for us. > If you've carefully written your code to use only safe primitives and > local state (discarded if interrupted) then yes, it could be > interruptible. ?At this point you could specially mark that block of > code as safe, leaving the vast majority of other code unsafe by > default. ?Then again, since you're going to the trouble of carefully > designing and auditing your code you could just make it cancellable > like blocking I/O should be - just by polling a flag at key points > (and you're CPU-bound anyway, so it's not expensive.) > > The only place I know of that you *need* arbitrary interruption is > hitting CTRL-C in the interactive interpreter. ?At this point it's a > debugging tool though, so the risk of weirdness is acceptable. We use background threads for long running calculations that we know are safe to abort. Resources that need protecting we do with finally blocks which the thread abort honours. The calculation is 'coarse grained' (it can call into .NET APIs that can take a relatively long time to return) - so polling for exit wouldn't work anyway. We also run user code and can't expect their code to poll for exit conditions. This system works fine for us. We had fun syncing results back when the calculation terminates (race conditions if a new one needs to start just as the old one ends) - but that is the fun of threads in the first place and nothing to do with how we terminate calculations early. Michael Foord http://www.ironpythoninaction.com/ From john.dohn.john at gmail.com Fri Jun 6 06:30:12 2008 From: john.dohn.john at gmail.com (John Dohn) Date: Fri, 6 Jun 2008 22:30:12 +1200 Subject: How to kill a thread? Message-ID: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> Hi there, How can I kill a threading.Thread subclass from MainThread? My threads are waiting for data in Queue.get() method: class MyThread(threading.Thread): def run(self): while True: data = queue.get() # <- here it waits most of the time ... process data >From the main thread I start several working threads: thr = MyThread() thr.start() ... feed the queue and at the end for each thread I'd like to do something like thr.kill() or thr.stop() or thr.destroy() or ... you got the point. I can't figure out how. Is there a way to do it? Thanks! JD -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at gmail.com Tue Jun 3 15:03:38 2008 From: cwitts at gmail.com (Chris) Date: Tue, 3 Jun 2008 12:03:38 -0700 (PDT) Subject: New variable? References: <18105511-7ae1-45e9-8c43-f34c1c4f5aeb@c58g2000hsc.googlegroups.com> Message-ID: <0dabbe7c-5754-4b2a-ae69-e92939fa682b@r66g2000hsg.googlegroups.com> On Jun 3, 8:40?pm, tmallen wrote: > What's the proper way to instantiate a new variable? x = ""? You don't need to pre-declare your variables. Just assign them as you need them and they will take the correct type. From grante at visi.com Sat Jun 14 21:59:32 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 14 Jun 2008 20:59:32 -0500 Subject: Creating a TCP/IP connection on already-networked computers References: <4853f269$0$11615$607ed4bc@cv.net> <4854123f$0$5017$607ed4bc@cv.net> <485413d0$0$4997$607ed4bc@cv.net> <485425b2$0$11631$607ed4bc@cv.net> <4854730e$0$11637$607ed4bc@cv.net> Message-ID: On 2008-06-15, John Salerno wrote: > Grant Edwards wrote: > >> If the two computers are in no way connected via any type of >> network, then the two programs won't be able to talk to each >> other. >> >> The programs can't create a network, they can only use one that >> already exists. > > But isn't that the point of the program, to create a network between the > two computers? No. For the two programs to work, the network must already exist and be properly configured. In this seinse, a "network" is a mechanism which programs can use to establish connections with each other. > Isn't that what the host and port are used for, to open a > connection? Yes, but a connection and a network aren't the same. When you pick up the phone and dial it, a connection between your phone and the phone your calling is set up. You dialing the phone isn't creating a telephone phone network -- it's using the existing telephone network to create a connection. In the case of the telephones, the "network" is the wires, the central office switches (and associated software), and the interconnecting trunks. In your house, the "network" is the wires and router and cable modem and network cards (and the associated configuration data). Your "home network" may or may not have a connection to the outside world. > (Just to clarify, when I say "in no way connected", I don't > mean not connected to the internet in general. I know they > need access to the internet for any kind of networking program > to work at all.) No, the two computers don't need to be connected to the internet in general. You could set up a network that consists entirely of those two computers and nothing else. Applications on those two computers could still communication with each other. -- Grant Edwards grante Yow! Why don't you at ever enter and CONTESTS, visi.com Marvin?? Don't you know your own ZIPCODE? From celoserpa at gmail.com Mon Jun 9 14:32:00 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Mon, 9 Jun 2008 15:32:00 -0300 Subject: Using ElementTree as backend for a chat web application issues Message-ID: <1e5bcefd0806091132p78f42109t1edb5e5acfaadb43@mail.gmail.com> Hello list, I've built a chat with a front-end Ajax client and backend usign ElementTree to persist the data. The problem is that the xml structure I use to persist some of the global configuration of the application usually gets corrupted, for example, let's say the structure is something like: In some circunstances I could not yet discover (it seems random) when I edit/save the structure, the structure gets corrupted, elementree seems to get lost in its internal "cursor", usually something like this happens: id="3"/> Pretty strange, and it drives the whole application unusable. I don't know if the concurrent nature of the application (multiple users using the client at almost the same time and sending data to the server which in turn must save the data to the same global.xml file) has something to do with it - I don't know if ElementTree is suitable for this kind of thing. How to hanlde this concurrent issue? My code seems to work ok, as when the XML doesn't get corrupted, all the features of the chat work nicely. I can show the code here, but it is too big and I don't have a clue where this problem would be sitted. It is simple, it just uses the parse method of elementree to read the xml and the write method to write, nothing fancy. If someone could "smell" what could be the cause of this problem and tell me, I would be grateful. -------------- next part -------------- An HTML attachment was scrubbed... URL: From torriem at gmail.com Sat Jun 21 19:20:02 2008 From: torriem at gmail.com (Michael Torrie) Date: Sat, 21 Jun 2008 17:20:02 -0600 Subject: Fast and easy GUI prototyping with Python In-Reply-To: References: <9c349bf0-ef63-4463-bd4e-cdbe331b58c3@z66g2000hsc.googlegroups.com> Message-ID: <485D8CA2.9030804@gmail.com> erokar at gmail.com wrote: > 2) The Qt vs. .NET API. I have no experience with Qt's API and a > rudimentary experience with the .NET API (seems powerfull but also big > and complex). Qt's API is very very good. Easy to use and extremely powerful. Note that in Python a number of Qt's APIs are not used in favor of Python native apis for things like file and socket I/O, IPC, Threads, and so forth. Additionally, PyQT does allow you the flexibility to move to other platforms. That need may not exist for you now, but it never makes sense to me to needlessly lock yourself down. As far as GUI design goes, Qt and SWF would be on par, likely. It's a bit of a misnomer to be comparing Qt to the .NET API. In IronPython you can of course leverage all the class libraries in the CLR, but most python programmers prefer to use python native libraries wherever possible. If you follow that, then it's SWF that compares to Qt. I've not used VS 2008's SWF gui designer, but of all the designers I've seen so far, Qt's Designer is the best I've ever used. I don't ever use code generation (GUIs should be created from the XML definitions), so integration with an IDE is not a concern for me. One issue about Qt is licensing, which could completely kill it for you. Although technically PyQt would insulate you from this issue to a point, TrollTech will not license Qt for your use in a non-GPL project if you began developing the project using the GPL version of Qt. From ng at invalid.fr Wed Jun 25 07:34:06 2008 From: ng at invalid.fr (Nicolas Girard) Date: 25 Jun 2008 11:34:06 GMT Subject: Wrapping a method twice Message-ID: <48622d2e$0$6051$9a6e19ea@unlimited.newshosting.com> Hi all, given the following code: --- def append(method,bottom): def wrapped(*args, **kwargs): res = method(*args, **kwargs) return bottom(res,*args, **kwargs) setattr(method.im_class,method.__name__,wrapped) def prepend(method,top): def wrapped(*args, **kwargs): top(*args, **kwargs) return method(*args, **kwargs) setattr(method.im_class,method.__name__,wrapped) def test(): class C: def f(self): print "f" def pre(self): print "pre" def post(res,self): print "post" prepend(C.f,pre) append(C.f,post) C().f() --- how comes that test() only outputs: pre f rather than what I expected: pre f post Thanks very much in advance, cheers, Nicolas From alexnbryan at gmail.com Tue Jun 24 00:13:45 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Mon, 23 Jun 2008 23:13:45 -0500 Subject: Sending information to a website Message-ID: Okay, so what I want to do is connect to dictionary.com and send the website a word, and later receive the definition. But for now, I want to focus on sending the word. A good guy from this mailing list said I should look into the code and then figure out what the word you want to be defined is called by the website. In other words, what is the name of the word the user inputs. Okay, so using the firebug extension I got the code that the search field on the website uses. here is that code.
    > > > The construct [abc] does not match a whole word but only one char, so ? > > [^table] means "any char which is not t, a, b, l or e". > > > Anyway the inside table word won't match your pattern, as there are '<' > > and '>' in it, and these chars have to be escaped when used as simple text. > > So this should work: > > > re.compile(r'.*
    ') > > ? ? ? ? ? ? ? ? ? ? ^ this is to avoid matching a tag name starting with > > ? ? ? ? ? ? ? ? ? ? table > > (like ) > > Doesn't work - for example it matches '
    ' > (and in fact if the html contains any number of tables it's going > to match the string starting at the start of the first table and > ending at the end of the last one.) > Try something like: re.compile(r'.*?', re.DOTALL) From wizzardx at gmail.com Sun Jun 8 09:20:01 2008 From: wizzardx at gmail.com (David) Date: Sun, 8 Jun 2008 15:20:01 +0200 Subject: Code correctness, and testing strategies In-Reply-To: <87hcc4jk4l.fsf@benfinney.id.au> References: <18c1e6480805240534k1da68fc8rfbace233f0de6e40@mail.gmail.com> <87hcc4jk4l.fsf@benfinney.id.au> Message-ID: <18c1e6480806080620v6ce0f416tece28a9f18722593@mail.gmail.com> Thanks for your informative reply. On Sun, Jun 8, 2008 at 12:28 PM, Ben Finney wrote: > David writes: > [...] > >> My problem is that I haven't run the app once yet during development >> :-/ > > That might be an artifact of doing bottom-up implementation > exclusively, leading to a system with working parts that are only > integrated into a whole late in the process. > I did do it in a mostly top-down way, but didn't stop the BDD process to actually run the app :-) It sounds like what you are suggesting is something like this: 1) Following BDD, get a skeleton app working Then, your BDD process gets a few extra steps: Old steps: 1) Write a test which fails for [new feature] 2) Write code for [new feature] to pass the test 3) Refactor if needed New steps: 4) Run the app like an end-user, and see that it works for the [new feature] 5) Write an automated test which does (4), and verifies the [new feature] is working correctly Does this mean that you leave out the formal 'integration' and 'systems' testing steps? By actually running the app you are doing those things more or less. Could you also leave out the unit tests, and just write automated acceptance tests? I guess that would have problems if you wanted to re-use code in other apps. Or, if acceptance tests break then it's harder to see which code is causing the problem. Also, if you had to implement a few "user stories" to get your app into a skeleton state, do you need to go back and write all the missing acceptance tests? I have a few problems understanding how to write automated acceptance tests. Perhaps you can reply with a few URLs where I can read more about this :-) 1) services If your app starts, and keeps running indefinitely, then how do you write acceptance tests for it? Does your acceptance tests need to interact with it from the outside, by manipulating databases, system time, restarting the service, etc? I presume also that acceptance tests need to treat your app as a black box, so they can only check your apps output (log files, database changes, etc), and not the state of objects etc directly. 2) User interfaces How do you write an acceptance test for user interfaces? For unit tests you can mock wx or gtk, but for the 'real' app, that has to be harder. Would you use specialised testing frameworks that understand X events or use accessibility/dcop/etc interaction? 3) Hard-to-reproduce cases. How do you write acceptance tests for hard-to-reproduce cases where you had to use mock objects for your unit tests? ... In cases like the above, would you instead: - Have a doc with instructions for yourself/testers/qa to manually check features that can't be automatically tested - Use 'top-down' integration tests, where you mock parts of the system so that that features can be automatically tested. - Some combination of the above [...] >> Is it worth the time to write integration tests for small apps, or >> should I leave that for larger apps? > > There is a threshold below which setting up automated build > infrastructure is too much overhead for the value of the system being > tested. There is no 'build' process (yet), since the app is 100% Python. But I will be making a Debian installer a bit later. My current 'build' setup is something like this: 1) Make an app (usually C++, shell-script, Python, or mixed) 2) Debianise it (add a debian subdirectory, with control files so Debian build tools know how to build binaries from my source, and how they should be installed & uninstalled). 3) When there are new versions, manually test the new version, build a binary debian installer (usually in a Debian Stable chroot with debian tools), on my Debian Unstable dev box, and upload the deb file (and updated Debian repo listing files) to a 'development' or 'unstable' branch on our internal Debian mirror. 4) Install the new app on a Debian Stable testing box, run it, and manually check that the new logic works 5) Move the new version to our Debian repo's live release, from where it will be installed into production. If I adopt BDD, my updated plan was to use it during app development and maintenance, but not for later testing. Do you suggest that after building a .deb in the chroot, the app should also be automatically installed under a chroot & acceptance tests run on my dev machine? Or should I package the acceptance tests along with the app, so that they can be (manually) run on test servers before going into production? Or do both? I've considered setting up a centralised build server at work, but currently I'm the only dev which actually builds & packages software, so it wouldn't be very useful. We do have other devs (PHP mostly), but they don't even use version control :-/. When they have new versions (on their shared PHP dev & testing servers), I copy it into my version control, confirm the changed files with them, build an installer, and upload onto our mirror, so it can be installed onto other boxes. David. From paddy3118 at googlemail.com Thu Jun 19 23:39:36 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 19 Jun 2008 20:39:36 -0700 (PDT) Subject: Pattern Matching Over Python Lists References: <21a9c996-75ff-4f7c-b7e9-c94247f65674@c58g2000hsc.googlegroups.com> <87ej6w6ql6.fsf@internal.daycos.com> <61ea5c70-4352-4d2f-a0ef-62eb76ba933a@m36g2000hse.googlegroups.com> <0796be8f-647c-4d19-86e5-e2472fb2daa3@34g2000hsh.googlegroups.com> Message-ID: On Jun 20, 1:44?am, Chris wrote: > Thanks for your help. Those weren't quite what I was looking for, but > I ended up figuring it out on my own. Turns out you can actually > search nested Python lists using simple regular expressions. Strange? How do you match nested '[' ... ']' brackets? - Paddy. From dullrich at sprynet.com Thu Jun 26 14:26:55 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 26 Jun 2008 13:26:55 -0500 Subject: ask for a RE pattern to match TABLE in html References: <6a4f17690806260653i136681bdsabe0f6bb1dfab67b@mail.gmail.com> Message-ID: In article , C?dric Lucantis wrote: > Le Thursday 26 June 2008 15:53:06 oyster, vous avez ?crit?: > > that is, there is no TABLE tag between a TABLE, for example > > something with out table tag
    > > what is the RE pattern? thanks > > > > the following is not right > > [^table]*? > > The construct [abc] does not match a whole word but only one char, so > [^table] means "any char which is not t, a, b, l or e". > > Anyway the inside table word won't match your pattern, as there are '<' > and '>' in it, and these chars have to be escaped when used as simple text. > So this should work: > > re.compile(r'.*') > ^ this is to avoid matching a tag name starting with > table > (like ) Doesn't work - for example it matches '
    ' (and in fact if the html contains any number of tables it's going to match the string starting at the start of the first table and ending at the end of the last one.) -- David C. Ullrich From wizzardx at gmail.com Sun Jun 22 06:14:55 2008 From: wizzardx at gmail.com (David) Date: Sun, 22 Jun 2008 12:14:55 +0200 Subject: Storing value with limits in object In-Reply-To: References: Message-ID: <18c1e6480806220314i1e0af4cel7c7cbc1acad49b09@mail.gmail.com> On Sun, Jun 22, 2008 at 11:44 AM, Josip wrote: > I'm trying to limit a value stored by object (either int or float): > > class Limited(object): > def __init__(self, value, min, max): > self.min, self.max = min, max > self.n = value > def set_n(self,value): > if value < self.min: # boundary check > self.n = self.min > if value > self.max: > self.n = self.max > else: > self.n = value > n = property(lambda self : self._value, set_n) > > This works, except I would like the class to behave like built-in types, so > I can use it like this: > > a = Limited(7, 0, 10) > b = math.sin(a) > > So that object itself returns it's value (which is stored in a.n). Is this > possible? > Not with normal vars, because = is a rebinding operator in Python, rather than assignment. You can do (close to) the above with object properties. David. From fuzzyman at gmail.com Thu Jun 5 09:26:54 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Thu, 5 Jun 2008 06:26:54 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> Message-ID: On Jun 3, 6:54 pm, sturlamolden wrote: > On May 24, 3:41 pm, Sh4wn wrote: > > > first, python is one of my fav languages, and i'll definitely keep > > developing with it. But, there's 1 one thing what I -really- miss: > > data hiding. I know member vars are private when you prefix them with > > 2 underscores, but I hate prefixing my vars, I'd rather add a keyword > > before it. > > Python has no data hiding because C++ has (void *). > > Python underscores does some name mangling, but does not attempt any > data hiding. > > Python and C has about the same approach to data hiding. It is well > tried, and works equally well in both languages: > > # this is mine, keep your filthy paws off!!! > > Irresponsible programmers should not be allowed near a computer > anyway. If you use data hiding to protect your code from yourself, > what you really need is some time off to reconsider your career. So, you are stating that no API programmer using Python *ever* has a valid or genuine reason for wanting (even if he can't have it) genuine 'hiding' of internal state or members from consumers of his (or her...) API? Michael Foord http://www.ironpythoninaction.com/ From eliben at gmail.com Mon Jun 9 07:06:54 2008 From: eliben at gmail.com (eliben) Date: Mon, 9 Jun 2008 04:06:54 -0700 (PDT) Subject: Access to CAN-Bus References: <484cd469$0$28520$3b214f66@aconews.univie.ac.at> Message-ID: On Jun 9, 8:57 am, Thin Myrna wrote: > I'd like to access some drive hardware via CAN bus from Python under Linux > (sending rec'ing PDOs). Googling around I couldn't find a Python package, > but people who said that they are doing this, though. I guess they are > using their home brewn software. > > Any pointer to > - such software (anyone willing to share his experience?) > - how to write such software? > > Under Windows, I guess, I could use some COM or ctypes functionality to > access the hardware vendor's hardware. What if I wanted to access such > hardware from Linux? Is there a package that allows that in a vendor (who > doesn't support Linux) independent way? > > Many thanks in advance > Thin I don't think this can be done in a vendor independent way, because as far as I know there is no standard for CAN drivers. It all depends on the card you have and what its maker supplies. It usually works as follows: the car maker supplies a DLL file with some examples of calling it from C or Visual Basic (for Windows systems). Maybe the DLL is downloadable from the company's website. You can easily ruse this DLL from Python, with the excellent 'ctypes' module. I've had some dealings with DLLs from various scripting languages, and I can tell you with confidence that nothing comes close to the ease of use and functionality of ctypes. From koblas at gmail.com Thu Jun 5 11:44:18 2008 From: koblas at gmail.com (koblas) Date: Thu, 5 Jun 2008 08:44:18 -0700 (PDT) Subject: Import removing first module component References: <75481b47-87ec-4a84-8063-7abbdb286d62@u6g2000prc.googlegroups.com> Message-ID: On Jun 4, 2:48?pm, "David C. Ullrich" wrote: > In article > <75481b47-87ec-4a84-8063-7abbdb286... at u6g2000prc.googlegroups.com>, > > ?koblas wrote: > > Have the following line: > > ? ? ? ? import notewave.runner.LMTP > > > Yeilding the following error: > > ? ? ? ? ImportError: No module named runner.LMTP > > > For the life of me I don't understand why the first component > > "notewave" is being stripped off, when the import is happening. > > Does notewave contain a _module_ named runner.LMTP ? > Probably not, since the error message says there's no > such module. > > > Thanks, > > -- > David C. Ullrich The following exist: .../notewave/runner/LMTP.py inside of LMTP.py there is: class LMTPRunner(Runner) : Another person pointed out that I should check on the __init__.py and make sure lmtp is defined in the __all__ block. I didn't have an __init__.py at that level of the tree, which must have been causing problems, but clearly I don't understand the full inheritance of __init__.py and sub-directories. From bruno.desthuilliers at gmail.com Thu Jun 5 15:44:43 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Thu, 5 Jun 2008 12:44:43 -0700 (PDT) Subject: ClassName.attribute vs self.__class__.attribute References: Message-ID: <25e0de62-4c63-4545-8684-69a410639807@i76g2000hsf.googlegroups.com> On 5 juin, 17:40, Gabriel Rossetti wrote: > Hello everyone, > > I had read somewhere that it is preferred to use > self.__class__.attribute over ClassName.attribute to access class (aka > static) attributes. It's even prefered to use self.attribute, unless you know you have both an instance and a class attribute by the same name (but then if you need to know which one you're accessing then you have a serious design problem). > I had done this and it seamed to work, until I > subclassed a class using this technique and from there on things started > screwing up. I finally tracked it down to self.__class__.attribute! What > was happening is that the child classes each over-rode the class > attribute at their level, Which is why it's prefered to access the attribute from the class (or more simply from the instance which will get them from the class) - a subclass may have extremly good reasons to have it's own instance of the attribute. > and the parent's was never set, This is another problem. > so while I was > thinking that I had indeed a class attribute set in the parent, it was > the child's that was set, and every child had it's own instance! Since > it was a locking mechanism, lots of fun to debug... I can well believe it, and you do have my whole sympathy. > So, I suggest never > using self.__class__.attribute, unless you don't mind it's children > overriding it, but if you want a truly top-level class attribute, use > ClassName.attribute everywhere! I would not have expressed it that way. My own experience is that, most of the time, you do know when it's ok for the subclasses to have their own instance of the attribute and when it's not, so in the (very rare) cases it's not ok you use __name_mangling. Now I'd say that *unknowingly* overriding an attribute of your own base class when you didn't expect it to happen is mostly a sign that there's something you don't (didn't ?) quite get wrt/ lookup / assignment / namespace etc rules in Python. > I wish books and tutorials mentioned this explicitly.... Possibly. OTHO, if you understand Python's lookup (name resolution) rules, the difference between MyBaseClass.attrib and self.__class__.attrib should be obvious. But this surely could be a good example in a tutorial !-) From patrick.m.bouffard at gmail.com Tue Jun 10 10:04:24 2008 From: patrick.m.bouffard at gmail.com (Patrick Bouffard) Date: Tue, 10 Jun 2008 14:04:24 +0000 (UTC) Subject: Determining which things in 'from package import *' are actually used Message-ID: I have a fairly large library of Python code, where 'from package import *' is used rather liberally, and it's not uncommon for more than one of these to appear in any given module. What I'd like to be able to do is to clean my code up a bit and turn each of the 'from package import *' statements into 'from package import thing_1, thing_2, ..., thing_n', where only thing_i's that are actually _used_ in the module are imported. In this way I hope to make my code a bit more understandable by future civilizations. :) (it needs all the help it can get!) Does anyone know of a package/recipe/whatever that does something like this automatically, even in limited cases? Ideally it should be accomplished only by looking at the source, or at most, importing the module. TIA, -Pat From maric at aristote.info Mon Jun 30 18:21:28 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 1 Jul 2008 00:21:28 +0200 Subject: List Performance In-Reply-To: References: <42358e0b-a351-4862-8f6a-1938eedeff6c@s21g2000prm.googlegroups.com> <200806301609.56831.maric@aristote.info> Message-ID: <200807010021.29250.maric@aristote.info> Le Monday 30 June 2008 22:21:35 Terry Reedy, vous avez ?crit?: > > Well, as I posted few days ago, one could envisage, as a pure python > > optimization for dealing with long list, to replace an algorithm with a > > lot of append by something like this : > > > > mark = object() > > > > datas = [ mark ] * expected_size > > datas = [None] * expected_size > has been a standard idiom since before object() existed ;-) > and works fine *unless* one wants to add None explicitly > and have that be different from 'unused'. Yes, in fact I used a marker because it I thought of it primarily as outbound for the list (like \0 for strings in C), but it doesnt' matter what is the object you put in the list, if you know at every moment its size. A subclass of list will indeed have to override most of the methods of its parent (not just some as I assumed before), using extend for reallocation with some sort of iterator with size, as it work in my previous example with xrange, something like that : >>>[31]: class iter_with_len(object) : def __init__(self, size, obj=None) : self.size = size self.obj = obj def __len__(self) : return self.size def __iter__(self) : return itertools.repeat(self.obj, len(self)) ....: ....: -- _____________ Maric Michaud From veeramanierd at gmail.com Sat Jun 14 03:55:35 2008 From: veeramanierd at gmail.com (pink) Date: Sat, 14 Jun 2008 00:55:35 -0700 (PDT) Subject: ######THEY DO DIFFERENT THINGS TO GET HERE######### Message-ID: <18acafd3-185e-4afd-b264-5f08e08fc5d2@q27g2000prf.googlegroups.com> Hi girls and friends...... earn more money in my site its really very different you want like it.... see it ..... www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com From info at egenix.com Wed Jun 18 12:27:17 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Wed, 18 Jun 2008 18:27:17 +0200 Subject: ANN: eGenix mx Base Distribution 3.1.0 Message-ID: <48593765.4080206@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com mx Base Distribution Version 3.1.0 Open Source Python extensions providing important and useful services for Python programmers. This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mx-Base-Distribution-3.1.0-GA.html ________________________________________________________________________ ABOUT The eGenix.com mx Base Distribution for Python is a collection of professional quality software tools which enhance Python's usability in many important areas such as fast text searching, date/time processing and high speed data types. The tools have a proven record of being portable across many Unix and Windows platforms. You can write applications which use the tools on Windows and then run them on Unix platforms without change due to the consistent platform independent interfaces. Contents of the distribution: * mxDateTime - Date/Time Library for Python * mxTextTools - Fast Text Parsing and Processing Tools for Python * mxProxy - Object Access Control for Python * mxBeeBase - On-disk B+Tree Based Database Kit for Python * mxURL - Flexible URL Data-Type for Python * mxUID - Fast Universal Identifiers for Python * mxStack - Fast and Memory-Efficient Stack Type for Python * mxQueue - Fast and Memory-Efficient Queue Type for Python * mxTools - Fast Everyday Helpers for Python All available packages have proven their stability and usefulness in many mission critical applications and various commercial settings all around the world. * About Python: Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. * About eGenix: eGenix is a consulting and software product company focused on providing professional quality services and products to Python users and developers (http://www.egenix.com/). ________________________________________________________________________ NEWS The 3.1.0 release of the eGenix mx Base Distribution has a number of enhancements over the previous version 3.0.0. Apart from a few minor bug fixes, it provides a few new features: Some highlights: * mxTools now has a new mx.Tools.dlopen() function which allow loading shared libraries explicitly and from a specific path. This allows working around problems with not being able to dynamically set LD_LIBRARY_PATH on Unix platforms. * mxTools can be configured to expose a new API called mx.Tools.setproctitle() which allows setting the process title on Unix platforms. * mxBeeBase comes with a new on-disk dictionary version called BeeFixedLengthStringDict, which allows using keys with embedded \0 characters. * mxSetup, our Python distutils extension, can now build prebuilt archives that no longer require the "... build --skip ..." command to skip the build process. The uninstall command now also works for prebuilt archives and the bdist_prebuilt command has been enhanced to be able to build pure Python distributions as well. * mxSetup now also works together with setuptools to e.g. build and install the packages as eggs. Run setup.py with --use-setuptools to enable this support. For a more detailed description of changes, please see the respective package documentation on our web-site. As always, we are providing pre-compiled versions of the package for the most popular Python platforms. For all others, you can compile the package from source using "python setup.py install". ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the packages can be found on the eGenix mx Base Distribution page: http://www.egenix.com/products/python/mxBase/ ________________________________________________________________________ LICENSE The eGenix mx Base package is distributed under the eGenix.com Public License 1.1.0 which is a CNRI Python License style Open Source license. You can use the package in both commercial and non-commercial settings without fee or charge. The package comes with full source code ________________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jun 18 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania 18 days to go :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From larry.bates at websafe.com` Sat Jun 14 10:36:48 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 14 Jun 2008 09:36:48 -0500 Subject: Platform independent code? In-Reply-To: References: Message-ID: saneman wrote: > I have read that Python is a platform independent language. But on this > page: > > http://docs.python.org/tut/node4.html#SECTION004220000000000000000 > > it seems that making a python script executable is platform dependant: > > 2.2.2 Executable Python Scripts > On BSD'ish Unix systems, Python scripts can be made directly executable, > like shell scripts, by putting the line > > > #! /usr/bin/env python > (assuming that the interpreter is on the user's PATH) at the beginning of > the script and giving the file an executable mode. The "#!" must be the > first two characters of the file. On some platforms, this first line must > end with a Unix-style line ending ("\n"), not a Mac OS ("\r") or Windows > ("\r\n") line ending. Note that the hash, or pound, character, "#", is used > to start a comment in Python. > > The script can be given an executable mode, or permission, using the chmod > command: > > > $ chmod +x myscript.py > > > > Are there any guidelines (API'S) that gurantees that the python code will be > platform independent? > > Generally you have to stay away from platform "dependent" constructs. Esamples: 1) Use os.path methods everywhere in your code so you won't need to worry about os.path.sep (slash or backslash). 2) Use lowest common denominator when naming files to make your scripts work cross platform. 3) Stay away from os-specific calls/interfaces when possible. Manipulating file permissions, etc is always os-specific. 4) Use config files instead of relying on registry in Windows. 5) Stay away from code that depends on 32/64 bit objects or endian-ness of storage (struct objects). This is machine specific not OS specific but still counts. 6) If you have GUI, use something like wxWindows which provides cross platform GUI support. 7) Be careful using non-Python libraries (C-libraries) should be done with care to make sure that the library is available for all target operating systems. 8) using os.system or the subsystem module must be done with much care and probably won't be cross platform compatible. Hope the suggestions help. -Larry From bedouglas at earthlink.net Fri Jun 13 17:09:17 2008 From: bedouglas at earthlink.net (bruce) Date: Fri, 13 Jun 2008 14:09:17 -0700 Subject: python screen scraping/parsing In-Reply-To: Message-ID: <20dc01c8cd99$be86e120$0301a8c0@tmesa.com> Hi Paul... Thanks for the reply. Came to the same conclusion a few minutes before I saw your email. Another question: tr=d.xpath(foo) gets me an array of nodes. is there a way for me to then iterate through the node tr[x] to see if a child node exists??? "d" is a document object, while "tr" would be a node object?, or would i convert the "tr[x]" to a string, and then feed that into the libxml2dom.parseString()... thanks -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of Paul Boddie Sent: Friday, June 13, 2008 12:49 PM To: python-list at python.org Subject: Re: python screen scraping/parsing On 13 Jun, 20:10, "bruce" wrote: > > url ="http://www.pricegrabber.com/rating_summary.php/page=1" [...] > tr = > "/html/body/div[@id='pgSiteContainer']/div[@id='pgPageContent']/table[2]/tbo > dy/tr[4]" > > tr_=d.xpath(tr) [...] > my issue appears to be related to the last "tbody", or tbody/tr[4]... > > if i leave off the tbody, i can display data, as the tr_ is an array with > data... Yes, I can confirm this. > with the "tbody" it appears that the tr_ array is not defined, or it has no > data... however, i can use the DOM tool with firefox to observe the fact > that the "tbody" is there... Yes, but the DOM tool in Firefox probably inserts virtual nodes for its own purposes. Remember that it has to do a lot of other stuff like implement CSS rendering and DOM event models. You can confirm that there really is no tbody by printing the result of this... d.xpath("/html/body/div[@id='pgSiteContainer']/ div[@id='pgPageContent']/table[2]")[0].toString() This should fetch the second table in a single element list and then obviously give you the only element of that list. You'll see that the raw HTML doesn't have any tbody tags at all. Paul -- http://mail.python.org/mailman/listinfo/python-list From stdenton at sbcglobal.net Sun Jun 1 11:40:09 2008 From: stdenton at sbcglobal.net (Sam Denton) Date: Sun, 01 Jun 2008 10:40:09 -0500 Subject: Integrating a code generator into IDLE Message-ID: Code generators seem to be popular in Python. (http://www.google.com/search?q=python+code-generator) I have one that I'd like to integrate into IDLE. Ideally, I'd like to (1) have a new file type show up when I use the File/Open dialog, and (2) have a function key that lets me run my generator against the file, just like F5 lets me run my Python code; ideally, I'd like to re-purpose the F5 key to be file-type aware. I've got a simple extension written that uses the F6 key to "compile" my files, but two goals I've listed seem a bit beyond me. Does anyone have any advice/pointers? Or is one or both ideas impractical? Thanks! From theo at van-werkhoven.nl.invalid Sun Jun 8 16:57:00 2008 From: theo at van-werkhoven.nl.invalid (Theo v. Werkhoven) Date: Sun, 8 Jun 2008 22:57:00 +0200 Subject: time.clock() or Windows bug? References: Message-ID: The carbonbased lifeform Nick Craig-Wood inspired comp.lang.python with: > Theo v. Werkhoven wrote: >> Output: >> Sample 1, at 0.0 seconds from start; Output power is: 8.967 dBm > [snip] >> Sample 17, at 105.7 seconds from start; Output power is: 9.147 dBm >> Sample 18, at 112.4 seconds from start; Output power is: 9.284 dBm >> Sample 19, at 119.0 seconds from start; Output power is: 9.013 dBm >> Sample 20, at 125.6 seconds from start; Output power is: 8.952 dBm >> Sample 21, at 91852.8 seconds from start; Output power is: 9.102 dBm >> Sample 22, at 91862.7 seconds from start; Output power is: 9.289 dBm >> Sample 23, at 145.4 seconds from start; Output power is: 9.245 dBm >> Sample 24, at 152.0 seconds from start; Output power is: 8.936 dBm > [snip] >> But look at the timestamps of samples 21, 22 and 43. >> What is causing this? >> I've replaced the time.clock() with time.time(), and that seems to >> solve the problem, but I would like to know if it's something I >> misunderstand or if it's a problem with the platform (Windows Server >> 2003) or the time.clock() function. > > time.clock() uses QueryPerformanceCounter under windows. There are > some known problems with that (eg with Dual core AMD processors). > > See http://msdn.microsoft.com/en-us/library/ms644904.aspx > > And in particular > > On a multiprocessor computer, it should not matter which processor > is called. However, you can get different results on different > processors due to bugs in the basic input/output system (BIOS) or > the hardware abstraction layer (HAL). To specify processor > affinity for a thread, use the SetThreadAffinityMask function. Alright, that explains that then. > I would have said time.time is what you want to use anyway though > because under unix time.clock() returns the elapsed CPU time which is > not what you want at all! You're right, using fuctions that do not work cross platform isn't smart. Cheers for the explanation Nick Theo -- theo at van-werkhoven.nl ICQ:277217131 SuSE Linux linuxcounter.org: 99872 Jabber:muadib at jabber.xs4all.nl AMD XP3000+ 1024MB "ik _heb_ niets tegen Microsoft, ik heb iets tegen de uitwassen *van* Microsoft" From brian_vanderburg2 at yahoo.com Wed Jun 18 02:53:15 2008 From: brian_vanderburg2 at yahoo.com (Allen) Date: Wed, 18 Jun 2008 02:53:15 -0400 Subject: Ternary operator alternative in Ptyhon In-Reply-To: References: Message-ID: kretik wrote: > I'm sure this is a popular one, but after Googling for a while I > couldn't figure out how to pull this off. > > Let's say I have this initializer on a class: > > def __init__(self, **params): > > I'd like to short-circuit the assignment of class field values passed in > this dictionary to something like this: > > self.SomeField = \ > params.has_key("mykey") ? params["mykey"] : None) > > Obviously I know this is not actual Python syntax, but what would be the > equivalent? I'm trying to avoid this, basically: > > if params.has_key("mykey"): > self.SomeField = params["mykey"] > else: > self.SomeField = None > > This is not a big deal of course, but I guess my main goal is to try and > figure out of I'm not missing something more esoteric in the language > that lets me do this. > > Thanks in advance. The syntax is a bit different, but: result = (true_value if condition else false_value) is how it is in Pytthon: self.SomeField = (params['mykey'] if params.has_key('mykey') else None) Brian Vanderburg II From rtiago at gmail.com Sat Jun 21 14:16:40 2008 From: rtiago at gmail.com (Ricardo Tiago) Date: Sat, 21 Jun 2008 20:16:40 +0200 Subject: SSL Message-ID: <8ed7d4b30806211116o7561f720j8c3c9f16eb1433c2@mail.gmail.com> Hi, Is it possible to access a https site using a certificate and keeping the session alive like it happens in the browsers? I'm doing a command line app that needs to access a https site to retrieve information but using the httplib, each time i make a request it asks for the pem pass phrase. Thanks, Ricardo -------------- next part -------------- An HTML attachment was scrubbed... URL: From yxs035 at gmail.com Mon Jun 30 05:10:48 2008 From: yxs035 at gmail.com (yxs035 at gmail.com) Date: Mon, 30 Jun 2008 02:10:48 -0700 (PDT) Subject: Jaeger LeCoultre Master Control 1000 Hours - Jaeger LeCoultre Watches Message-ID: Jaeger LeCoultre Master Control 1000 Hours - Jaeger LeCoultre Watches Luxury Gift : http://www.luxury-gift.org Jaeger LeCoultre Watches : http://www.luxury-gift.org/Watches/jaeger-lecoultre-watches.html Jaeger LeCoultre Master Control 1000 Hours : http://www.luxury-gift.org/Watches/Jaeger-LeCoultre-Master-Control-1000-Hours.html Jaeger LeCoultre Master Control 1000 Hours series contain the following items, each item is the perfect marriage of function and design. Jaeger LeCoultre Master Control 1000 Hours are finely copied, you don't need to worry about the quality. We believe that no matter what you're looking for in a watch, our Jaeger LeCoultre Master Control 1000 Hours will exceed your expectations. Explore the World of Brand Watches & Handbags It is a well-known fact that a watch you wear not just serves as a faithful time keeping device,but is also associated with your social status.style and evenframe of mind.If you intend tomake a wise choice as for purchasing awatch just right for you,devote your attention to awide range of high quality brand watches . Jaeger LeCoultre Master Control 1000 Hours All Products : Jaeger LeCoultre Master Geographic 142.240.927SB, Jaeger LeCoultre Master Geographic 142.81.20 (q1428120), Jaeger LeCoultre Master Grande Memovox 146.34.4a (q146344a), Jaeger LeCoultre Master Grande Memovox 146.64.8A (q146648A) 95%, Jaeger LeCoultre Master Memovox 144.24.70 (q1442470), Jaeger LeCoultre Master Memovox 144.24.20 (q1442420), Jaeger LeCoultre Master Eight Days 160.24.20 (q1602420), Jaeger LeCoultre Master Eight Days 160.84.20 (q1608420), Jaeger LeCoultre Master Geographic 142.84.70 (q1428470), Jaeger LeCoultre Master Geographic 142.84.20 (q1428420), Jaeger LeCoultre Master Perpetual 149.34.4A (q149344a) USED 99%, Jaeger LeCoultre Master Reserve de Marche 148.84.04 (q1488404), Jaeger LeCoultre Master Reserve de Marche 148.24.01 (q1482401), Jaeger LeCoultre Master Reserve de Marche 148.84.03 (q1488403), Jaeger LeCoultre Master Reveil 141.24.20 (q1412420), Jaeger LeCoultre Master Tourbillon 165.24.20 (q1652420), Jaeger LeCoultre Master Tourbillon 165.84.20 (q1658420), Jaeger LeCoultre Master Tourbillon 165.81.20 (q1658120), Jaeger LeCoultre Master Tourbillon 165.64.50 (q1656450), Jaeger LeCoultre Master Ultra Thin 145.35.70, Jaeger LeCoultre Master Ultra Thin 145.85.04 (q1458504), Jaeger LeCoultre Master Ultra Thin 145.64.80 (q1456480), Jaeger LeCoultre Master Ultra Thin 145.84.04 (q1458404), Jaeger LeCoultre Master Ultra Thin 145.24.04 (q1452404), Jaeger LeCoultre Master Ultra Thin 145.25.04 (q1452504), Jaeger LeCoultre Master Ultra Thin 145.85.70 (q1458570), Jaeger LeCoultre Master Control 1000 Hours WebSite Link : http://www.luxury-gift.org/Watches/Jaeger-LeCoultre-Master-Control-1000-Hours.html From duncan.booth at invalid.invalid Fri Jun 20 03:31:19 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Jun 2008 07:31:19 GMT Subject: advanced listcomprehenions? References: Message-ID: Terry Reedy wrote: >> [['Fizz', 'Buzz', 'FizzBuzz', str(i)][62/(pow(i, 4, 15) + 1)%4] for i >> in xrange(1, 101)] > > These make the lookup table variable, so it has to be recalculated for > each i. > So what? Mark Wooding was posting about mathematical elegance and came up with that really neat pow() call. If runtime came into it then one of the previous solutions or (as Mark already said) a straightforward sometable[i% 15] is going beat something like this hands-down. This is coding for fun not profit. -- Duncan Booth http://kupuguy.blogspot.com From kyosohma at gmail.com Wed Jun 18 08:52:39 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 18 Jun 2008 05:52:39 -0700 (PDT) Subject: Google Module? References: <1cbf2da8-4e64-4d15-9617-bdbb42648057@f36g2000hsa.googlegroups.com> Message-ID: <453cc218-9721-4802-8ccf-b296feae9a9e@p25g2000hsf.googlegroups.com> On Jun 18, 2:54?am, JulianMontez wrote: > Just started learning Python and wanted to make a program that would > retrieve files that were indexed by Google. These files can be > filtered by their extensions, nothing too difficult. :) > > I wanted to know if there was a module that would allow me to access > the API easily within Python. I don't think that pyGoogle works > anymore (supposedly the SOAP API was discontinued). > > Thanks in advance! You're probably looking for the gdata module: http://code.google.com/p/gdata-python-client/ It hooks into most of Google's APIs. Mike From aweraw at gmail.com Fri Jun 13 05:34:04 2008 From: aweraw at gmail.com (Aidan) Date: Fri, 13 Jun 2008 19:34:04 +1000 Subject: boolian logic In-Reply-To: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> References: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> Message-ID: marc wyburn wrote: > HI all, I'm a bit stuck with how to work out boolian logic. > > I'd like to say if A is not equal to B, C or D: > do something. > > I've tried > > if not var == A or B or C: > and various permutations but can't seem to get my head around it. I'm > pretty sure I need to know what is calulated first i.e the not or the > 'OR/AND's > > thanks, Marc. You mean like a ternary operation? >>> True and 1 or 0 1 >>> False and 1 or 0 0 This of course depends on the 'true' result also being true.. it fails if it is false... if that's not what you mean, then maybe this is what you want if not var==A or not var==B or not var==C: # do something From n.emami at gmail.com Fri Jun 13 03:37:44 2008 From: n.emami at gmail.com (Nader) Date: Fri, 13 Jun 2008 00:37:44 -0700 (PDT) Subject: Checking list by using of exception Message-ID: <3bdcc52d-2432-4b28-8188-bf7c811859d1@d45g2000hsc.googlegroups.com> Hello, I read some files name from a directory and then I put these name in a list. I will check whether it is empty or not, and I would do it with an exception. With if statement it is very simple: If list_of_files != "" : # this can be if list_of_files != []: get the files elas: there is no file But with exception, I can write something as: try: list_of_files != [] get the files except ValueError: Print " there is no file" What can the first statement be inside 'try' if I don't want to use if statement? Maybe my understandig of exception is enough to got it. Would somebody explain me about this? Regards, Nader try and except in a dircMaybe this quetion will be simple enough for you. From asmodai at in-nomine.org Mon Jun 16 10:05:01 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 16 Jun 2008 16:05:01 +0200 Subject: Who is using python-ldap with Python 1.5.x and 2.0-2.2? In-Reply-To: <6h7ii5-l9m.ln1@nb2.stroeder.com> References: <6h7ii5-l9m.ln1@nb2.stroeder.com> Message-ID: <20080616140501.GC64377@nexus.in-nomine.org> -On [20080616 15:55], Michael Str?der (michael at stroeder.com) wrote: >I'd like to hear from the Python community whether support for Python >version prior to 2.3 is still needed in python-ldap. Please tell me >which Python version you're using and why it'd be important for you to >have python-ldap updates still supporting it. Not that I use python-ldap at work, but our lowest Python version is 2.3 and we're working towards making 2.5 the default. Hopefully that helps you for versions used. :) -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B But the time has come when all good things shall pass... From jamitwidme at gmail.com Thu Jun 26 10:41:27 2008 From: jamitwidme at gmail.com (jamitwidme at gmail.com) Date: Thu, 26 Jun 2008 07:41:27 -0700 (PDT) Subject: ConfigParser: Can I read(ConfigParser.get()) a configuration file and use it to call a funciton? Message-ID: <34b51593-d787-4f12-9cc2-473d3832ff0d@k37g2000hsf.googlegroups.com> Hello. I am a novice programmer and have a question I have a configuration file(configuration.cfg) I read this from reading.py using ConfigParser When I use ConfigParser.get() function, it returns a string. I want to call a function that has the same name as the string from the configuration file. configuration.cfg --------------------------------------- [1234] title: abcd function: efgh --------------------------------------- reading.py -------------------------------------------------------- import ConfigParser def efgh(): print 'blah' config = ConfigParser.ConfigParser() config.read('configuration.cfg') fcn = config.get('1234','function') type(fcn) print fcn -------------------------------------------------------- efgh Is there any way to call efgh() ? One way I know is using if statement if fcn == 'efgh': efgh() But I am going to have many functions to call, so I want to avoid this. Thank you for your help From maxm at mxm.dk Wed Jun 4 09:11:53 2008 From: maxm at mxm.dk (Max M) Date: Wed, 04 Jun 2008 15:11:53 +0200 Subject: Handling some isolated iso-8859-1 characters In-Reply-To: References: Message-ID: Daniel Mahoney skrev: > The interesting patch is the string that reads "=?iso-8859-1?Q?Ana=EFs?=". > An HTML rendering of what this string should look would be "Anaïs". There is a mention of email headers and unicode in the end of this article: http://mxm-mad-science.blogspot.com/2008/03/python-unicode-lessons-from-school-of.html -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From giuott at gmail.com Mon Jun 23 00:58:25 2008 From: giuott at gmail.com (Giuseppe Ottaviano) Date: Sun, 22 Jun 2008 21:58:25 -0700 Subject: Bind compiled code to name? In-Reply-To: <485EB8F5.4080503@v.loewis.de> References: <485e9aea$0$637$9b622d9e@news.freenet.de> <485EB8F5.4080503@v.loewis.de> Message-ID: <380957DB-676C-498E-AE57-D14E67E0AB68@gmail.com> > class D:pass > d = D() > exec source_code in d.__dict__ > print d.some_name > > Notice that this will also give you d.__builtins__, which you might > want to del afterwards. If you want to mimic an import you can also do this: import types D = types.ModuleType('D') exec source_code in D.__dict__ print D.some_name This way D is a module (don't know if there are real differences with the class approach, though) From socyl at 987jk.com.invalid Sun Jun 8 13:03:52 2008 From: socyl at 987jk.com.invalid (kj) Date: Sun, 8 Jun 2008 17:03:52 +0000 (UTC) Subject: How to get full path to script? Message-ID: How can a script know its absolute path? (__file__ only gives the path it was used to invoke the script.) Basically, I'm looking for the Python equivalent of Perl's FindBin. The point of all this is to make the scripts location the reference point for the location of other files, as part of a self-contained distribution. TIA! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From kyosohma at gmail.com Mon Jun 2 16:28:12 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 2 Jun 2008 13:28:12 -0700 (PDT) Subject: platypus in page header References: Message-ID: <90b1c701-a316-4577-8bf8-fddfa12e4ee8@d77g2000hsb.googlegroups.com> On Jun 2, 1:16?pm, Laszlo Nagy wrote: > Is it possible to use platypus in page header and footer? I need to > create a document with long paragraphs but also I need to put tables and > images in page header and multi line info in page footer with alignment etc. > > Thanks, > > ? ?Laszlo From looking at the docs, it sounds like you could do that, if you create your flowables correctly. You should probably ask over on the reportlab user's list though. Those guys would almost certainly know: http://two.pairlist.net/mailman/listinfo/reportlab-users Mike From ks.mathiesen at gmail.com Mon Jun 23 06:28:50 2008 From: ks.mathiesen at gmail.com (Knut Saua Mathiesen) Date: Mon, 23 Jun 2008 12:28:50 +0200 Subject: Sending arrays of a structure as an argument via ctypes Message-ID: <97a99e230806230328x761454a3i49a850c386db283a@mail.gmail.com> Hi there. I am reprogrammed my astar* path finding algorithm in C to make it quicker. I am now trying to make python use this C extension, however I keep getting "Segmentation fault". Some of the C stuff: typedef struct Point { int x; int y; } Point; typedef struct Node { Point pos; int cost; int g; int obstacle; struct Node* parent; } Node; void astar(Node map[], Point from, Point to) { (...) } main () { (...) Node map[maptotal]; (...) astar(map, createPoint(0,0), createPoint(50,50)); } Now I am by no means a C programmer, this is basicly the first "bigger than hello-world" program, but I have got it working in C. What I am now trying to do is to make the map using python, and send it to my astar C function using ctypes. Basicly I've rewritten my structures in python: class Point(Structure): _fields_ = [("x", c_int), ("y", c_int)] def __repr__(self): return "" % (self.x, self.y) class Node(Structure): def __repr__(self): return "" % (self.pos.x, self.pos.y) Node._fields_ = [('pos', Point), ('cost', c_int), ('g', c_int), ('obstacle', c_int), ('parent',POINTER(Node))] And after that, this is how I am trying to call it: self.astar = astarlib.astar self.astar.argtypes = [Node * self.maptotal, Point, Point] self.astar.restype = None self.nodes = (Node * self.maptotal)() for i in range(self.mapwidth): for i2 in range(self.mapheight): self.nodes[i2 * self.mapwidth + i] = Node(Point(i, i2)) self.astar(self.nodes, Point(5,6), Point(6,6)) When I call the self.astar function it segfaults. And what I think I've done wrong is the self.nodes part, but I can't find any good documentation on it. Any help? :p From lucaberto at libero.it Fri Jun 6 06:01:24 2008 From: lucaberto at libero.it (luca72) Date: Fri, 6 Jun 2008 03:01:24 -0700 (PDT) Subject: import cherrypy2 References: <0853b1cc-33bb-416e-9b2e-0fa146ede1c1@79g2000hsk.googlegroups.com> <7c00f301-5d49-4f49-98fd-d0f5e72aa135@c65g2000hsa.googlegroups.com> Message-ID: <85a8b572-3a54-43c4-bc7c-d554888697d5@m45g2000hsb.googlegroups.com> No i haven't install lino but if frmp the python of this computer i make import cherrypy2 i import it without problem this is the python path: luca72 at linux-z0ta:~> python Python 2.5.1 (r251:54863, Jan 10 2008, 18:00:49) [GCC 4.2.1 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import cherrypy2 >>> import sys >>> sys.path ['', '/usr/lib64/python2.5/site-packages/setuptools-0.6c7-py2.5.egg', '/usr/lib64/python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg', '/ usr/lib64/python2.5/site-packages/TurboKid-1.0.4-py2.5.egg', '/usr/ lib64/python2.5/site-packages/TurboJson-1.1.2-py2.5.egg', '/usr/lib64/ python2.5/site-packages/TurboCheetah-1.0-py2.5.egg', '/usr/lib64/ python2.5/site-packages/simplejson-1.8.1-py2.5-linux-x86_64.egg', '/ usr/lib64/python2.5/site-packages/RuleDispatch-0.5a0.dev_r2306-py2.5- linux-x86_64.egg', '/usr/lib64/python2.5/site-packages/ PasteScript-1.6.2-py2.5.egg', '/usr/lib64/python2.5/site-packages/ FormEncode-1.0.1-py2.5.egg', '/usr/lib64/python2.5/site-packages/ DecoratorTools-1.7-py2.5.egg', '/usr/lib64/python2.5/site-packages/ configobj-4.5.2-py2.5.egg', '/usr/lib64/python2.5/site-packages/ CherryPy-2.3.0-py2.5.egg', '/usr/lib64/python2.5/site-packages/ kid-0.9.6-py2.5.egg', '/usr/lib64/python2.5/site-packages/ Cheetah-2.0.1-py2.5-linux-x86_64.egg', '/usr/lib64/python2.5/site- packages/PyProtocols-1.0a0dev_r2302-py2.5-linux-x86_64.egg', '/usr/ lib64/python2.5/site-packages/PasteDeploy-1.3.1-py2.5.egg', '/usr/ lib64/python2.5/site-packages/Paste-1.6-py2.5.egg', '/usr/local/lib64/ python2.5/site-packages/pagedemo1-1.0-py2.5.egg', '/usr/lib/ python25.zip', '/usr/lib64/python2.5', '/usr/lib64/python2.5/plat- linux2', '/usr/lib64/python2.5/lib-tk', '/usr/lib64/python2.5/lib- dynload', '/usr/lib64/python2.5/site-packages', '/usr/lib64/python2.5/ site-packages/Numeric', '/usr/lib64/python2.5/site-packages/PIL', '/ usr/lib64/python2.5/site-packages/gtk-2.0', '/usr/lib64/python2.5/site- packages/wx-2.8-gtk2-unicode', '/usr/local/lib64/python2.5/site- packages'] >>> Regards Luca From zookog at gmail.com Thu Jun 26 12:56:00 2008 From: zookog at gmail.com (zooko) Date: Thu, 26 Jun 2008 09:56:00 -0700 (PDT) Subject: Is there any way to find out sizeof an object References: <2338ccaf-d653-403a-9630-c06e7df98184@m73g2000hsh.googlegroups.com> Message-ID: Here are a few little tools that I developed to do this kind of thing: http://allmydata.org/trac/pyutil/browser/pyutil/pyutil/memutil.py Regards, Zooko From geoff.bache at jeppesen.com Thu Jun 26 11:52:58 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Thu, 26 Jun 2008 08:52:58 -0700 (PDT) Subject: Windows process ownership trouble References: <3fcf363f-3685-4b7b-8ba5-1ffc32e58af7@m44g2000hsc.googlegroups.com> <990516b7-f7ef-464a-97d0-fd55a0354ab4@y21g2000hsf.googlegroups.com> Message-ID: <33847c9a-a816-48a1-a8c9-4209db9bf0b5@e53g2000hsa.googlegroups.com> Tim, Unfortunately my previous message was premature, it seems your workaround doesn't work either on my system (Windows XP, Python 2.5.1) I get the following printed out Traceback (most recent call last): File "C:\TextTest\processown.py", line 12, in os.remove ("filename") WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'filename' close failed: [Errno 9] Bad file descriptor Any ideas? Geoff From Robert.Bossy at jouy.inra.fr Wed Jun 18 11:42:50 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 18 Jun 2008 17:42:50 +0200 Subject: Looking for lots of words in lots of files In-Reply-To: <48592C15.1020402@jouy.inra.fr> References: <48592C15.1020402@jouy.inra.fr> Message-ID: <48592CFA.4090701@jouy.inra.fr> I forgot to mention another way: put one thousand monkeys to work on it. ;) RB Robert Bossy wrote: > brad wrote: >> Just wondering if anyone has ever solved this efficiently... not >> looking for specific solutions tho... just ideas. >> >> I have one thousand words and one thousand files. I need to read the >> files to see if some of the words are in the files. I can stop >> reading a file once I find 10 of the words in it. It's easy for me to >> do this with a few dozen words, but a thousand words is too large for >> an RE and too inefficient to loop, etc. Any suggestions? > The quick answer would be: > grep -F -f WORDLIST FILE1 FILE2 ... FILE1000 > where WORDLIST is a file containing the thousand words, one per line. > > The more interesting answers would be to use either a suffix tree or > an Aho-Corasick graph. > > - The suffix tree is a representation of the target string (your > files) that allows to search quickly for a word. Your problem would > then be solved by 1) building a suffix tree for your files, and 2) > search for each word sequentially in the suffix tree. > > - The Aho-Corasick graph is a representation of the query word list > that allows fast scanning of the words on a target string. Your > problem would then be solved by 1) building an Aho-Corasick graph for > the list of words, and 2) scan sequentially each file. > > The preference for using either one or the other depends on some > details of your problems: the expected size of target files, the rate > of overlaps between words in your list (are there common prefixes), > will you repeat the operation with another word list or another set of > files, etc. Personally, I'd lean towards Aho-Corasick, it is a matter > of taste; the kind of applications that comes to my mind makes it more > practical. > > Btw, the `grep -F -f` combo builds an Aho-Corasick graph. Also you can > find modules for building both data structures in the python package > index. > > Cheers, > RB > -- > http://mail.python.org/mailman/listinfo/python-list > From igouy2 at yahoo.com Mon Jun 2 23:57:29 2008 From: igouy2 at yahoo.com (Isaac Gouy) Date: Mon, 2 Jun 2008 20:57:29 -0700 (PDT) Subject: libgtop gtop.proc_time(pid) examples? Message-ID: <88c63066-97f0-42c6-a7a0-c72e67f6ef9f@27g2000hsf.googlegroups.com> Please show an example of using the Python libgtop wrapper to get process time information, or say where such examples can be found. From ToshiBoy at gmail.com Sat Jun 28 00:30:25 2008 From: ToshiBoy at gmail.com (ToshiBoy) Date: Fri, 27 Jun 2008 21:30:25 -0700 (PDT) Subject: this is simple... Message-ID: I am a newbie... and the first to admit it... but this has me stuffed: I have two lists A and B that are both defined as range(1,27) I want to find the entries that are valid for A = BxB so here is my code: A = range(1,27) B = range(1,27) for b in B: if b*b in A: print b else: B.remove(b) I get, as expected 1,4,9,16,25 printed out being the only members of B where the condition is true, but when I print B I get: [1, 2, 3, 4, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25] 1 to 5 is correct, but why doesn't the remove method remove 7 and above? What am I doing wrong here? From jonrob at fedoraproject.org Sun Jun 22 13:02:20 2008 From: jonrob at fedoraproject.org (Jonathan Roberts) Date: Sun, 22 Jun 2008 18:02:20 +0100 Subject: Learning Python in a group In-Reply-To: <18c1e6480806220511s5117aef4gb4ec93bceb44a0ac@mail.gmail.com> References: <507738ef0806220343r3e9ea053neeec0baf0ccfdbe6@mail.gmail.com> <18c1e6480806220422x5d06c54byd23b249bb699691f@mail.gmail.com> <507738ef0806220452s74358615v44518469cf3b5f45@mail.gmail.com> <18c1e6480806220511s5117aef4gb4ec93bceb44a0ac@mail.gmail.com> Message-ID: <507738ef0806221002x6ebc0c90k621c891f711e44ca@mail.gmail.com> > I'm sure that many (myself included) would be happy to help out, but > due to timezone differences, working hours, etc you may only get > responses up to 24 hours (or more) later. Awesome, heh I'm sure we'll have questions for the list in good time :) > > What needs does your (non-face-to-face) group have that would not be > met by posting questions to the Python Tutor list? > > http://mail.python.org/mailman/listinfo/tutor > > Perhaps you and your co-learners can sign up to that list, and > coordinate with that list's users to use your wiki, messaging > services, etc? Actually, I hadn't seen that list before but I've just signed up for it and it sounds really interesting! The big difference really is that I'd like to try and build something a little more personal, where we have a group of people who can contact each other in real time and have regular meeting times as well as being able to find each other in between meetings too. I think this kind of consistent relationship is probably quite conducive to learning, and I think others would probably agree :) > Personally I learned Python from the Python docs (starting with the > tutorial), practice, and Google. Dive Into Python is good too. Yeah, I think we're definitely going to be making use of these resources, and then just using each other as support as we wade through the material and inevitably get stuck in places! Thanks for your help :) Best, Jon From basti.wiesner at gmx.net Mon Jun 9 16:06:23 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Mon, 09 Jun 2008 22:06:23 +0200 Subject: Web Crawler - Python or Perl? References: <484D7329.6060107@behnel.de> <1a91e16d-ccfc-487a-80fc-4d9992455eb9@p25g2000hsf.googlegroups.com> Message-ID: subeen at Montag 09 Juni 2008 20:21: > On Jun 10, 12:15 am, Stefan Behnel wrote: >> subeen wrote: >> > can use urllib2 module and/or beautiful soup for developing crawler >> >> Not if you care about a) speed and/or b) memory efficiency. >> >> http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/ >> >> Stefan > > ya, beautiful soup is slower. so it's better to use urllib2 for > fetching data and regular expressions for parsing data. BeautifulSoup is implemented on regular expressions. I doubt, that you can achieve a great performance gain by using plain regular expressions, and even if, this gain is certainly not worth the effort. Parsing markup with regular expressions is hard, and the result will most likely not be as fast and as memory-efficient as lxml.html. I personally am absolutely happy with lxml.html. It's fast, memory efficient, yet powerful and easy to use. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From hrnilesh.cyntel at gmail.com Thu Jun 19 23:19:49 2008 From: hrnilesh.cyntel at gmail.com (careerbirds) Date: Thu, 19 Jun 2008 20:19:49 -0700 (PDT) Subject: =?windows-1252?Q?20=2D6=2D2008_=96walkin=2CIT_FRESHER=2CIT_EXP_OPENINGS?= Message-ID: <27f56e0a-1c5b-4b47-9b34-bba427fc21ec@u6g2000prc.googlegroups.com> 20-6-2008 ?walkin,IT FRESHER,IT EXP OPENINGS http://www.hotjobseeker.com/ * Oracle Apps Techno Functional Consultant http://www.hotjobseeker.com/ * J2EE TECHNICAL ASSOCIATES AT PROKARMA AT HYDERABAD http://www.hotjobseeker.com/ * BEA-Weblogic-Application Server Admin http://www.hotjobseeker.com/ * Datastage Developer -ASAP Infosystems Pvt Ltd http://www.hotjobseeker.com/ * Cognos Developer -ASAP Infosystems Pvt Ltd http://www.hotjobseeker.com/ * Javascript expert $1600-2600/month, ASP.NET, work remotely at home http://www.hotjobseeker.com/ * Web Developer -Digital Pixel Inc. http://www.hotjobseeker.com/ * My SQL DBA with valid B1 visa (4+ yrs exp) http://www.hotjobseeker.com/ * AS400 Professionals http://www.hotjobseeker.com/ * Sr Cognos Professionals http://www.hotjobseeker.com/ * EAI Developer / EAI Sr.Java Developer - 3 Years to 7 Years http://www.hotjobseeker.com/ * Oracle,PL/SQL Developers/Consultant http://www.hotjobseeker.com/ * Sr. PHP Programmers - Immediate Openings http://www.hotjobseeker.com/ * Oracle Apps -Functional -SCM/HRMS/Financials-Onsite Oppurtunities http://www.hotjobseeker.com/ * Urgent Opening- Sybase Developers http://www.hotjobseeker.com/ * Sr. SEO/SEO Executive http://www.hotjobseeker.com/ * Designers Required at Harbinger Group Pune http://www.hotjobseeker.com/ * Software Developer - Java/J2EE http://www.hotjobseeker.com/ * TECH SUPPORT EXECUTIVE http://www.hotjobseeker.com/ * HR Trainee / HR Coordinator http://www.hotjobseeker.com/ * Customer Support Executive http://www.hotjobseeker.com/ * help desk executive -InKnowTech Private Limited http://www.hotjobseeker.com/ * Sales & Service Engineer (Electronic) http://www.hotjobseeker.com/ * Web Content Writer/Developer http://www.hotjobseeker.com/ * VBA Developer -US Headquartered http://www.hotjobseeker.com/ * RECRUITMENT EXECUTIVES/ RECRUITERS http://www.hotjobseeker.com/ * Application Software Engg/Php developer http://www.hotjobseeker.com/ * Tele Calling Executive -Insync http://www.hotjobseeker.com/ * Operations Support Executive -NETCRADLE INDIA http://www.hotjobseeker.com/ * (0-1 Years) Walk-In @ "AMBARA SOFTWARE" : CSR : On 25-30 May 2008, Male Candidates Only http://www.hotjobseeker.com/ * (FRESHERS & EXPERIENCED) Walk-In @ "TIMESJOBS" : ITES Job Fair : On 24, 25 May 2008 http://www.hotjobseeker.com/ * Walk-In @ "PCS TECHNOLOGY" : Server Support : Chennai : On 24, 26 May 2008 http://www.hotjobseeker.com/ * Walk-In @ "TCS" : Multiple Skills : Kochi / Pune / Hyderabad / Chennai : On 24, 25 May 2008 http://www.hotjobseeker.com/ * (FRESHERS) Walk-In @ "NATIONAL INSTRUMENTS" : On 6, 7 Jun 2008, BE / B.Tech : Last Date - 4 Jun 2008 http://www.hotjobseeker.com/ * (FRESHERS) Walk-In @ "LIONBRIDGE TECHNOLOGIES" : From Monday to Friday http://www.hotjobseeker.com/ * Artech Infosystems Walk-in for Freshers: Weekdays http://www.hotjobseeker.com/ NOTE FROM ADMIN: http://www.hotjobseeker.com/ http://finance.groups.yahoo.com/group/hotjobseeker/ $Some of these requirements may not suit your eligibility criteria , Do not delete this mail straight way. It may help few of your friends or classmates who are struggling to find more opportunities. Kindly forward this mail to them. We want you to join this revolution by helping fellow job seekers. Please forward this mail to other groups, Orkut friends,face book friends,yahoo mailing list,google talk members, College groups etc... http://finance.groups.yahoo.com/group/hotjobseeker/ All of our sections are updated daily with mails .Apply to all eligible requirements as soon as possible. This mail is neither spam nor unsolicited. You received this message because you are a member of http://www.hotjobseeker.com from the World's Biggest Job Group. please send this mail to your mailing list http://finance.groups.yahoo.com/group/hotjobseeker/ From omer at no-log.org Mon Jun 30 10:06:42 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Mon, 30 Jun 2008 16:06:42 +0200 Subject: List Performance In-Reply-To: <2eydnaP-saOZQfXVnZ2dnUVZ_qvinZ2d@comcast.com> References: <42358e0b-a351-4862-8f6a-1938eedeff6c@s21g2000prm.googlegroups.com> <2eydnaP-saOZQfXVnZ2dnUVZ_qvinZ2d@comcast.com> Message-ID: <200806301606.42499.omer@no-log.org> Le Monday 30 June 2008 15:13:30 Larry Bates, vous avez ?crit?: > Peter Otten wrote: > > Ampedesign wrote: > >> If I happen to have a list that contains over 50,000 items, will the > >> size of the list severely impact the performance of appending to the > >> list? > > > > No. > > > > $ python -m timeit -n20000 -s"items = []" "items.append(42)" > > 20000 loops, best of 3: 0.554 usec per loop > > $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" > > 20000 loops, best of 3: 0.529 usec per loop > > > > http://wiki.python.org/moin/TimeComplexity > > > > Peter > > Peter, > > So its actually faster to append to a long list than an empty one? That > certainly would not have been intuitively obvious now would it? > That test only demonstrates that it's faster to append to a 1 million items list than an empty one (and this on a particular platform with a particular python version). Different sizes may give different result. I guess this is because of some internal optimisations (items are probably allocated by chunks, so sometimes append() involves a realloc, sometimes not). So the only thing you should remember is that list.append() has a complexity of O(1), and thus should be considered a constant time operation for any length. Just be aware of the note: [1] = These operations rely on the "Amortized" part of "Amortized Worst Case". Individual actions may take surprisingly long, depending on the history of the container. Also note that 50000 items is a lot for a human being, not for a modern computer. -- C?dric Lucantis From geonomica at gmail.com Mon Jun 30 12:13:42 2008 From: geonomica at gmail.com (gianluca) Date: Mon, 30 Jun 2008 09:13:42 -0700 (PDT) Subject: ctypes - swig - pointer Message-ID: I've a problem with dll function colled with python/ctypes. My functions (C) requred a typedef int "value_type" in tree different way: same as value_type; - mydll.foo1(value_type) same as *value_type; - mydll.foo2(*value_type) same as **value_type; - mydll.foo3(**value_type) How can pass it in python. If i do that: rules=POINTER(value_type) opr=rsl.StrengthOfRules(rules,10) R=POINTER(rules) I've this exception: Traceback (most recent call last): File "C:\temp\cRSL.py", line 49, in opr=rsl.StrengthOfRules(rules,10) #/* Creates a table of rules strengths. */ ArgumentError: argument 1: : Don't know how to convert parameter 1 I've tried with swig (cpointer.i) olso but the library don't work correctly and rules look empty. I need help. Could anybody give mi it? gima From grante at visi.com Sat Jun 14 17:47:58 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 14 Jun 2008 16:47:58 -0500 Subject: Making wxPython a standard module? References: <6bidd7F3bg8usU1@mid.uni-berlin.de> <87fxrfx0h0.fsf@physik.rwth-aachen.de> Message-ID: On 2008-06-14, Paul McNett

    wrote: > Grant Edwards wrote: >> On 2008-06-14, Torsten Bronger wrote: >> >>>> I've never used any of the designers, but I agree 100% that >>>> wxPython code is nasty ugly. wxPython has a very un-Pythonic >>>> API that's is, IMO, difficult to use. >>> I know that such requests may start a never-ending thread but >>> I'd really like to know what you mean with this. >> >> [...] >> >> Well, if we want this thread to be never ending, I'd better put >> a little dramatic hyperbole into my answer, so here goes... ;) > > (blatant self-promotion warning: I'm one of the founders of Dabo, and it > sounds like you may like to take a look at it, given your comments below) Yes! Dabo was the other one I was trying to remember. The last time I looked Dabo appeared to be catching on better than wax was. > But in the end, wxPython is the best GUI toolkit for Python, > by far, I've been using it for 9 years. :) I can pretty much always make it work, and the result looks native to Windows users and "native enough" to Linux users... -- Grant Edwards grante Yow! I'm rated PG-34!! at visi.com From tdahsu at gmail.com Fri Jun 6 14:22:07 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Fri, 6 Jun 2008 11:22:07 -0700 (PDT) Subject: File-writing not working in Windows? References: <80a7b951-591b-41a2-b76c-f97d75db0dad@25g2000hsx.googlegroups.com> <08442be2-13c0-44fc-add4-4907c1202f96@r66g2000hsg.googlegroups.com> Message-ID: <300fece5-da15-4323-9b3a-f49b90d9c74b@34g2000hsh.googlegroups.com> On Jun 6, 11:35?am, jay graves wrote: > On Jun 6, 10:18 am, tda... at gmail.com wrote: > > > > This code works PERFECTLY in Linux. ?Where I have a match in the file > > I'm processing, it gets cut out from the start of the match until the > > end of the match, and written to the temporary file in tempdir. > > It does not work in Windows. ?It does not create or write to the > > temporary file AT ALL. ?It creates the tempdir directory with no > > problem. > > In general, I don't use string concatenation when building paths. > Especially on scripts that are meant to run on multiple platforms. > > > Here's the kicker: it works perfectly in Windows if Windows is running > > in VMware on a Linux host! ?(I assume that that's because VMware is > > passing some call to the host.) > > probably a red herring. > > > Can anyone tell me what it is that I'm missing which would prevent the > > file from being created on Windows natively? > > Get rid of the 'posix' check and use os.path.join to create > 'tempfileName' and see if it works. > > HTH. > ... > Jay Graves Jay, Thank you for your answer. I have researched os.path.join. I have changed the code to read as follows: if (self.checkbox25.GetValue() == False): initialFileName = self.Info[x][0] + "_tmp_" + fileName + ".txt" tempfileName = os.path.join("proctemp", initialFileName) else: initialFileName = self.Info[x][0] + "_xyz.txt" tempfileName = os.path.join("proctemp", initialFileName) this still works in Linux; it does not work in Windows. I am thinking that the "g.open(tempFileName, 'a')" command is the issue. Is there anything different about opening a file in Windows? Does Windows understand "append", or would I have to do control checks for seeing if the file is created and then appending? From mensanator at aol.com Fri Jun 6 13:50:25 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 6 Jun 2008 10:50:25 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> Message-ID: On Jun 6, 1:44?am, "Terry Reedy" wrote: > "Mensanator" wrote in message > > news:bbd90051-36be-4378-9a27-2a47a5471d12 at a1g2000hsb.googlegroups.com... > | On Jun 5, 10:42?pm, John Salerno wrote: > | > Is it possible to write a list comprehension for this so as to produce > a > | > list of two-item tuples? > | > > | > base_scores = range(8, 19) > | > score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] > | > print zip(base_scores, score_costs) > | > > | > I can't think of how the structure of the list comprehension would work > | > in this case, because it seems to require iteration over two separate > | > sequences to produce each item in the tuple. > > Which is exactly the purpose of zip, or its specialization enumerate! Aren't you overlooking the fact that zip() truncates the output to the shorter length iterable? And since the OP foolishly hardcoded his range bounds, zip(base_scores,score_cost) will silently return the wrong answer if the base_count list grows. Surely enumerate() wasn't added to Python with no intention of ever being used. > > | > zip seems to work fine anyway, but my immediate instinct was to try a > | > list comprehension (until I couldn't figure out how!). And I wasn't > sure > | > if list comps were capable of doing everything a zip could do. > | > | base_scores = range(8, 19) > | score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] > | print zip(base_scores, score_costs) > | > | s = [(i+8,j) for i,j in enumerate( [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3])] > | print s > | > | ##>>> > | ##[(8, 0), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, > | 2), (16, 2), (17, 3), (18, 3)] > | ##[(8, 0), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, > | 2), (16, 2), (17, 3), (18, 3)] > | ##>>> > > Of course, enumerate(iterable) is just a facade over zip(itertools.count(), > iterable) But if all I'm using itertools for is the count() function, why would I go to the trouble of importing it when I can simply use enumerate()? Is it a couple orders of magnitude faster? From frank at chagford.com Mon Jun 9 10:21:28 2008 From: frank at chagford.com (Frank Millman) Date: Mon, 9 Jun 2008 07:21:28 -0700 (PDT) Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> <41de7980-749a-4f46-add1-12010b6e95d9@b1g2000hsg.googlegroups.com> Message-ID: <8f9b0c13-9b90-4352-acbc-ec15a9e2f8bc@f63g2000hsf.googlegroups.com> On Jun 9, 4:06?pm, Frank Millman wrote: > > Thanks for the reply, Mel. I don't quite understand what you mean. As so often happens, after I sent my reply I re-read your post and I think I understand what you are getting at. One problem with my approach is that I am truncating the result down to the desired scale factor every time I create a new instance. This could result in a loss of precision if I chain a series of instances together in a calculation. I think that what you are suggesting avoids this problem. I will read your message again carefully. I think it will lead to a rethink of my approach. Thanks again Frank P.S. Despite my earlier reply to Paul, I have not abandoned the idea of using my Number class as opposed to the standard Decimal class. I did a simple test of creating two instances and adding them together, using both methods, and timing them. Decimal came out 6 times slower than Number. Is that important? Don't know, but it might be. From 42flicks at gmail.com Tue Jun 10 22:14:25 2008 From: 42flicks at gmail.com (Mike) Date: Wed, 11 Jun 2008 14:14:25 +1200 Subject: Dynamic HTML from Python Script In-Reply-To: References: <484f151c$0$5009$607ed4bc@cv.net> Message-ID: <2b54d4370806101914i4af29d96mcb0807e8342cd892@mail.gmail.com> Web.py also springs to mind, I'd say it's worth looking at. Well, in that case you could simply append the new output to a static file > every 10 seconds, or whenever there is new output. That way, you just need > to refresh the static file in your browser to see updates... Given what I > understand of your situation, that's how I'd do it. >From your requirements this sounds like the best solution. At least while you investigate further. -------------- next part -------------- An HTML attachment was scrubbed... URL: From qgallet at gmail.com Thu Jun 5 10:02:16 2008 From: qgallet at gmail.com (Quentin Gallet-Gilles) Date: Thu, 5 Jun 2008 16:02:16 +0200 Subject: No subject In-Reply-To: <000c01c8c712$347dd660$1300a8c0@Home> References: <000c01c8c712$347dd660$1300a8c0@Home> Message-ID: <8b943f2b0806050702n6bd5480dj7a1a9c5a9993a678@mail.gmail.com> I don't want to spoil the fun, so I'll just say that "range" is the key here. Quentin On Thu, Jun 5, 2008 at 3:43 PM, garywood wrote: > Hi there. So I have a challenge in the Python book I am using (python > programming for the absolute beginner) that tells me to improve an ask_number() > function, so that it can be called with a step value, and I havn't > been able to find out yet what's meant by a step value, but i'll keep > looking of course. I'd just be grateful if someone could illimunate > this for me. > > > def ask_number(question, low, high): > """Ask for a number within a range.""" > response = None > while response not in range(low, high): > response = int(raw_input(question)) > return response > > Thanks in advance. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eliben at gmail.com Mon Jun 23 00:28:26 2008 From: eliben at gmail.com (eliben) Date: Sun, 22 Jun 2008 21:28:26 -0700 (PDT) Subject: Pattern Matching Over Python Lists References: <21a9c996-75ff-4f7c-b7e9-c94247f65674@c58g2000hsc.googlegroups.com> <87ej6w6ql6.fsf@internal.daycos.com> <61ea5c70-4352-4d2f-a0ef-62eb76ba933a@m36g2000hse.googlegroups.com> <6e31e7ef-3eea-4edc-88bc-471e78dbb46c@i76g2000hsf.googlegroups.com> <1379d69a-af3f-4e06-8bd4-b85e0213399a@g16g2000pri.googlegroups.com> <111101c1-d096-481a-94a5-5af1844b8e55@t54g2000hsg.googlegroups.com> Message-ID: <34de545e-05a1-4a57-8f73-dc27a813c3e7@m44g2000hsc.googlegroups.com> > Fair enough. To help you understand the method I used, I'll give you > this hint. It's true that regex on works on strings. However, is there > any way to convert arbitrarily complex data structures to string > representations? You don't need to be an experienced Python user to > answer to this ;) As Paddy noted before, your solution has a problem, Regexes can't match nested parenthesis, so I think your method will have a problem with nested lists, unless your actual inputs are much simpler than the general case. Eli From kib2 at free.fr Mon Jun 23 13:35:28 2008 From: kib2 at free.fr (kib2) Date: Mon, 23 Jun 2008 19:35:28 +0200 Subject: Going from Tkinter to pyQT In-Reply-To: References: Message-ID: <485fdf24$0$1305$426a74cc@news.free.fr> Alex Bryan a ?crit : > I had a guy on this mailing list tell me that pyQT is much better than > Tkinter, and after looking into it a bit I think he is right. However, I > can't find much on it. I want to know if there are any good books or > online tutorials that would be helpful. I doubt there is one, but if > there is one on going from Tkinter to pyQT, that would be amazing. Well > if any of you guys have any tips or suggestions on any of this I would > appreciate it. Hi Alex, Check Mark Summerfield's book on PyQt4 : http://www.qtrac.eu/pyqtbook.html Other links : http://www.rkblog.rk.edu.pl/w/p/python/ From danb_83 at yahoo.com Thu Jun 19 23:26:17 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Thu, 19 Jun 2008 20:26:17 -0700 (PDT) Subject: At long last... References: Message-ID: On Jun 19, 9:24?pm, Carl Banks wrote: > On Jun 19, 10:17 pm, Terry Reedy wrote: > > > Carl Banks wrote: > > > Tuples will have an index method in Python 2.6. > > > > I promise I won't indiscriminately use tuples for homogenous data. > > > Honest. ?Scout's honor. ?Cross my heart. > > > Use them as you want. ?This change came about because .index was > > included in the 3.0 Sequence ABC (abstract base class) and tuple was > > included as a sequence, so .... something had to give. ?The result was > > tuple getting the full suite of immutable sequence methods. ?And then > > there was no good reason to not backport ;-). > > The last time I needed index on a tuple was in fact for partially non- > homogenous data. ?I forget why, but I needed to treat arguments after > a certain value different from the front arguments. ?So I wanted to do > something like: > > def something(*args): > ? ? firstspecial = args.index(0) > > 'Cept I couldn't. Why didn't you just use a list inside the tuple? From gagsl-py2 at yahoo.com.ar Tue Jun 3 21:46:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 03 Jun 2008 22:46:06 -0300 Subject: printf in python References: <261cbf38-6f0d-4525-9b4a-11ddbb910b66@d45g2000hsc.googlegroups.com> <183dfd01-68a5-4ae8-a04a-c3689d77003e@m3g2000hsc.googlegroups.com> <0f7b7836-ed92-4a02-9eba-4ff7fe4a94cd@m36g2000hse.googlegroups.com> Message-ID: En Tue, 03 Jun 2008 10:28:57 -0300, gianluca escribi?: >> > > On Mon, 2 Jun 2008 00:32:33 -0700 (PDT), gianluca >> >> > > declaimed the following in comp.lang.python: >> >> > > > Hy, I've a problem with may python library generated with swig >> from C >> > > > code. I works and I can access all function but a sim?ple >> function >> > > > that print a string don't work's. >> > > > The function is like this: >> > > > int PrintTEST() >> > > > { >> > > > printf("TEST "); >> > > > return 1; >> > > > } > > I know!! I'm bore!! But I need help indeed!! > I'm looking inside lib_wrap.c generated by swig. In the wrap function > there is no printf function. If is this the problem how can I do to > resolve it? Generated swig code is... uhm, ugly at least, and rather undebuggable. I'd try to avoid it. Another alternative is Cython: I've not actually used it myself, but I've seen good reports from it. If your library is written in C (not C++), you may use directly ctypes from inside Python. -- Gabriel Genellina From fc14301589 at icqmail.com Sun Jun 15 05:45:12 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Sun, 15 Jun 2008 17:45:12 +0800 Subject: Hard to understand 'eval' References: <485381e7_2@news.tm.net.my> Message-ID: <4854e4a7_2@news.tm.net.my> On 06:34, domenica 15 giugno 2008 Dennis Lee Bieber wrote: >> for nn in stn_items: > I already see a syntax error when viewing that in Agent... A missing > indent level under the "for" The program don't complain wrong indentation, I mostly sure a wrong copy-paste error. Error doesn't come up there. > . You also don't need the continue if you change the second if into elif. > My mistake, I thought that was improving the loop. is it an if....elif....elif probing only the first matching case and drop the remaining checks? > And what type of structure is "cfl"? You got close, that's a dictionary of dictionaries and I'm trying to updating it. > wonder what this mysterious _append() function is supposed to be doing; Append() is a conventional name regarding a file logging. There would be an option to set a quota of bytes size. > Huh... I presume you mean to convert from a text decimal it isn't so, the function look at the string to see if ending by K or M, which means Kbytes or Mbytes. It'll return the decimal conversion. If the value is set as boolean value, then it will do appending to the log when it True or stop appending when there's a quota. def _append(c, v): RE_BYTE= re.compile(r'^[\d]+(k|m)?$',re.I) # any number of digit followed by 0 or 1 (k or m), case insensitive chkbool(v) if isinstance(v,bool): c['append']= v return c if RE_BYTE.match(value): k= 1024; M= k * k; v= int(value[:-1]) if value[-1:] == 'k': v= v * k if value[-1:] == 'm': v= v * m c['append']= v return c All the code could be download at my web site ;) But this here it's a bit new concept. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From alexnbryan at gmail.com Sun Jun 29 16:04:04 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sun, 29 Jun 2008 13:04:04 -0700 (PDT) Subject: using urllib2 In-Reply-To: <18184170.post@talk.nabble.com> References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> <25d97d35-6d28-43ef-9e54-d8ae7a03bc8f@b1g2000hsg.googlegroups.com> <27fbd1c7-6735-4fb0-9758-726b2fd8b86e@m3g2000hsc.googlegroups.com> <18184087.post@talk.nabble.com> <18184170.post@talk.nabble.com> Message-ID: <18184788.post@talk.nabble.com> Okay, now I ran in it the shell, and this is what happened: >>> for tabs in soup.findAll('table', {'class': 'luna-Ent'}): ... tabs.findAll('td')[-1].contents[-1].string ... u' ' u' ' u' ' u' ' u' ' u'not complex or compound; single. ' u' ' u' ' u' ' u' ' u' ' u'inconsequential or rudimentary. ' u'unlearned; ignorant. ' u' ' u'unsophisticated; naive; credulous. ' u' ' u'not mixed. ' u' ' u'not mixed. ' u' ' u' ' u' ' u' ' u'). ' u' ' u'(of a lens) having two optical surfaces only. ' u'an ignorant, foolish, or gullible person. ' u'something simple, unmixed, or uncompounded. ' u'cords for controlling the warp threads in forming the shed on draw-looms. ' u'a person of humble origins; commoner. ' u' ' >>> However, the definitions are there. I printed the actual soup and they were there in the format they always were in. So what is the deal!?! >>> soup.findAll('table', {'class': 'luna-Ent'}) [
    1.easy to understand, deal with, use, etc.: a simple matter; simple tools.
    See there is the first one in the shell, I mean it is there, but the for loop can't find it. I am wondering, because the above soup.findAll('table'..etc. makes it a list. Do you think that has anything to do with the problem? Alexnb wrote: > > Actually after looking at this, the code is preactically the same, except > the definitions. So what COULD be going wrong here? > > Also, I ran the program and decided to print the whole list of definitions > straight off BeautifulSoup, and I got an interesting result: > > What word would you like to define: simple > [u' ', u' ', u' ', u' ', u' ', u'not complex or compound; single. > > those are the first 5 definitions. and later on, it does the same thing. > it only sees a space, any ideas? > > Alexnb wrote: >> >> Okay, so i've hit a new snag and can't seem to figure out what is wrong. >> What is happening is the first 4 definitions of the word "simple" don't >> show up. The html is basicly the same, with the exception of noun turning >> into adj. Ill paste the html of the word cheese, and then the one for >> simple, and the code I am using to do the work. >> >> line of html for the 2nd def of cheese: >> >>
    2.> valign="top">a definite mass of this substance, often in the shape of a >> wheel or cylinder.
    >> >> line of html for the 2nd def of simple: >> >>
    2.> valign="top">not elaborate or artificial; plain: a simple style. >>
    >> >> code: >> >> import urllib >> from BeautifulSoup import BeautifulSoup >> >> >> def get_defs(term): >> soup = >> BeautifulSoup(urllib.urlopen('http://dictionary.reference.com/search?q=%s' >> % term)) >> >> for tabs in soup.findAll('table', {'class': 'luna-Ent'}): >> yield tabs.findAll('td')[-1].contents[-1].string >> >> word = raw_input("What word would you like to define: ") >> >> mainList = list(get_defs(word)) >> >> n=0 >> q = 1 >> >> for x in mainList: >> print str(q)+". "+str(mainList[n]) >> q=q+1 >> n=n+1 >> >> Now, I don't think it is the italics because one of the definitions that >> worked had them in it in the same format. Any Ideas??! >> >> >> Jeff McNeil-2 wrote: >>> >>> On Jun 29, 12:50?pm, Alexnb wrote: >>>> No I figured it out. I guess I never knew that you aren't supposed to >>>> split a >>>> url like "http://www.goo\ >>>> gle.com" But I did and it gave me all those errors. Anyway, I had a >>>> question. On the original code you had this for loop: >>>> >>>> for tabs in soup.findAll('table', {'class': 'luna-Ent'}): >>>> ? ? ? ? yield tabs.findAll('td')[-1].contents[-1].string >>>> >>>> I hate to be a pain, but I was looking at the BeautifulSoup docs, and >>>> found >>>> the findAll thing. But I want to know why you put "for tabs," also why >>>> you >>>> need the "'table', {'class': 'luna-Ent'}):" Like why the curly braces >>>> and >>>> whatnot? >>>> >>>> Jeff McNeil-2 wrote: >>>> >>>> > On Jun 27, 10:26?pm, Alexnb wrote: >>>> >> Okay, so I copied your code(and just so you know I am on a mac right >>>> now >>>> >> and >>>> >> i am using pydev in eclipse), and I got these errors, any idea what >>>> is >>>> >> up? >>>> >>>> >> Traceback (most recent call last): >>>> >> ? File >>>> >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", >>>> >> line 14, in >>>> >> ? ? print list(get_defs("cheese")) >>>> >> ? File >>>> >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", >>>> >> line 9, in get_defs >>>> >> ? ? dictionary.reference.com/search?q=%s' % term)) >>>> >> ? File >>>> >> >>>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >>>> lib.py", >>>> >> line 82, in urlopen >>>> >> ? ? return opener.open(url) >>>> >> ? File >>>> >> >>>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >>>> lib.py", >>>> >> line 190, in open >>>> >> ? ? return getattr(self, name)(url) >>>> >> ? File >>>> >> >>>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/url >>>> lib.py", >>>> >> line 325, in open_http >>>> >> ? ? h.endheaders() >>>> >> ? File >>>> >> >>>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >>>> plib.py", >>>> >> line 856, in endheaders >>>> >> ? ? self._send_output() >>>> >> ? File >>>> >> >>>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >>>> plib.py", >>>> >> line 728, in _send_output >>>> >> ? ? self.send(msg) >>>> >> ? File >>>> >> >>>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >>>> plib.py", >>>> >> line 695, in send >>>> >> ? ? self.connect() >>>> >> ? File >>>> >> >>>> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/htt >>>> plib.py", >>>> >> line 663, in connect >>>> >> ? ? socket.SOCK_STREAM): >>>> >> IOError: [Errno socket error] (8, 'nodename nor servname provided, >>>> or not >>>> >> known') >>>> >>>> >> Sorry if it is hard to read. >>>> >>>> >> Jeff McNeil-2 wrote: >>>> >>>> >> > Well, what about pulling that data out using Beautiful soup? If >>>> you >>>> >> > know the table name and whatnot, try something like this: >>>> >>>> >> > #!/usr/bin/python >>>> >>>> >> > import urllib >>>> >> > from BeautifulSoup import BeautifulSoup >>>> >>>> >> > def get_defs(term): >>>> >> > ? ? soup = BeautifulSoup(urllib.urlopen('http:// >>>> >> > dictionary.reference.com/search?q=%s' % term)) >>>> >>>> >> > ? ? for tabs in soup.findAll('table', {'class': 'luna-Ent'}): >>>> >> > ? ? ? ? yield tabs.findAll('td')[-1].contents[-1].string >>>> >>>> >> > print list(get_defs("frog")) >>>> >>>> >> > jeff at martian:~$ python test.py >>>> >> > [u'any tailless, stout-bodied amphibian of the order Anura, >>>> including >>>> >> > the smooth, moist-skinned frog species that live in a damp or >>>> >> > semiaquatic habitat and the warty, drier-skinned toad species that >>>> are >>>> >> > mostly terrestrial as adults. ', u' ', u' ', u'a French person or >>>> a >>>> >> > person of French descent. ', u'a small holder made of heavy >>>> material, >>>> >> > placed in a bowl or vase to hold flower stems in position. ', u'a >>>> >> > recessed panel on one of the larger faces of a brick or the like. >>>> ', >>>> >> > u' ', u'to hunt and catch frogs. ', u'French or Frenchlike. ', >>>> u'an >>>> >> > ornamental fastening for the front of a coat, consisting of a >>>> button >>>> >> > and a loop through which it passes. ', u'a sheath suspended from a >>>> >> > belt and supporting a scabbard. ', u'a device at the intersection >>>> of >>>> >> > two tracks to permit the wheels and flanges on one track to cross >>>> or >>>> >> > branch from the other. ', u'a triangular mass of elastic, horny >>>> >> > substance in the middle of the sole of the foot of a horse or >>>> related >>>> >> > animal. '] >>>> >>>> >> > HTH, >>>> >>>> >> > Jeff >>>> >>>> >> > On Jun 27, 7:28?pm, Alexnb wrote: >>>> >> >> I have read that multiple times. It is hard to understand but it >>>> did >>>> >> help >>>> >> >> a >>>> >> >> little. But I found a bit of a work-around for now which is not >>>> what I >>>> >> >> ultimately want. However, even when I can get to the page I want >>>> lets >>>> >> >> say, >>>> >> >> "Http://dictionary.reference.com/browse/cheese", I look on >>>> firebug, >>>> >> and >>>> >> >> extension and see the definition in javascript, >>>> >>>> >> >> >>>> >> >> >>>> >> >> >>>> >> >> >>>> >> >> >>>> >>>> >> >> Jeff McNeil-2 wrote: >>>> >>>> >> >> > the problem being that if I use code like this to get the html >>>> of >>>> >> that >>>> >>>> >> >> > page in python: >>>> >>>> >> >> > response = urllib2.urlopen("the webiste....") >>>> >> >> > html = response.read() >>>> >> >> > print html >>>> >>>> >> >> > then, I get a bunch of stuff, but it doesn't show me the code >>>> with >>>> >> the >>>> >> >> > table that the definition is in. So I am asking how do I access >>>> this >>>> >> >> > javascript. Also, if someone could point me to a better >>>> reference >>>> >> than >>>> >> >> the >>>> >> >> > last one, because that really doesn't tell me much, whether it >>>> be a >>>> >> >> book >>>> >> >> > or anything. >>>> >>>> >> >> > I stumbled across this a while back: >>>> >> >> >http://www.voidspace.org.uk/python/articles/urllib2.shtml. >>>> >> >> > It covers quite a bit. The urllib2 module is pretty >>>> straightforward >>>> >> >> > once you've used it a few times. ?Some of the class naming and >>>> >> whatnot >>>> >> >> > takes a bit of getting used to (I found that to be the most >>>> >> confusing >>>> >> >> > bit). >>>> >>>> >> >> > On Jun 27, 1:41 pm, Alexnb wrote: >>>> >> >> >> Okay, I tried to follow that, and it is kinda hard. But since >>>> you >>>> >> >> >> obviously >>>> >> >> >> know what you are doing, where did you learn this? Or where >>>> can I >>>> >> >> learn >>>> >> >> >> this? >>>> >>>> >> >> >> Maric Michaud wrote: >>>> >>>> >> >> >> > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit : >>>> >> >> >> >> I have never used the urllib or the urllib2. I really have >>>> >> looked >>>> >> >> >> online >>>> >> >> >> >> for help on this issue, and mailing lists, but I can't >>>> figure >>>> >> out >>>> >> >> my >>>> >> >> >> >> problem because people haven't been helping me, which is >>>> why I >>>> >> am >>>> >> >> >> here! >>>> >> >> >> >> :]. >>>> >> >> >> >> Okay, so basically I want to be able to submit a word to >>>> >> >> >> dictionary.com >>>> >> >> >> >> and >>>> >> >> >> >> then get the definitions. However, to start off learning >>>> >> urllib2, I >>>> >> >> >> just >>>> >> >> >> >> want to do a simple google search. Before you get mad, what >>>> I >>>> >> have >>>> >> >> >> found >>>> >> >> >> >> on >>>> >> >> >> >> urllib2 hasn't helped me. Anyway, How would you go about >>>> doing >>>> >> >> this. >>>> >> >> >> No, >>>> >> >> >> >> I >>>> >> >> >> >> did not post the html, but I mean if you want, right click >>>> on >>>> >> your >>>> >> >> >> >> browser >>>> >> >> >> >> and hit view source of the google homepage. Basically what >>>> I >>>> >> want >>>> >> >> to >>>> >> >> >> know >>>> >> >> >> >> is how to submit the values(the search term) and then >>>> search for >>>> >> >> that >>>> >> >> >> >> value. Heres what I know: >>>> >>>> >> >> >> >> import urllib2 >>>> >> >> >> >> response = urllib2.urlopen("http://www.google.com/") >>>> >> >> >> >> html = response.read() >>>> >> >> >> >> print html >>>> >>>> >> >> >> >> Now I know that all this does is print the source, but >>>> thats >>>> >> about >>>> >> >> all >>>> >> >> >> I >>>> >> >> >> >> know. I know it may be a lot to ask to have someone >>>> show/help >>>> >> me, >>>> >> >> but >>>> >> >> >> I >>>> >> >> >> >> really would appreciate it. >>>> >>>> >> >> >> > This example is for google, of course using pygoogle is >>>> easier in >>>> >> >> this >>>> >> >> >> > case, >>>> >> >> >> > but this is a valid example for the general case : >>>> >>>> >> >> >> >>>>[207]: import urllib, urllib2 >>>> >>>> >> >> >> > You need to trick the server with an imaginary User-Agent. >>>> >>>> >> >> >> >>>>[208]: def google_search(terms) : >>>> >> >> >> > ? ? return >>>> >> >> >> >>>> urllib2.urlopen(urllib2.Request("http://www.google.com/search?" >>>> >> >> >> > + >>>> >> >> >> > urllib.urlencode({'hl':'fr', 'q':terms}), >>>> >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? >>>> >> >> ?headers={'User-Agent':'MyNav >>>> >> >> >> > 1.0 >>>> >> >> >> > (compatible; MSIE 6.0; Linux'}) >>>> >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ).read() >>>> >> >> >> > ? ?.....: >>>> >>>> >> >> >> >>>>[212]: res = google_search("python & co") >>>> >>>> >> >> >> > Now you got the whole html response, you'll have to parse it >>>> to >>>> >> >> recover >>>> >> >> >> > datas, >>>> >> >> >> > a quick & dirty try on google response page : >>>> >>>> >> >> >> >>>>[213]: import re >>>> >>>> >> >> >> >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

    >>> >> >> >> class=r>.*?

    ', >>>> >> >> >> > res) ] >>>> >> >> >> > ...[229]: >>>> >> >> >> > ['Python Gallery', >>>> >> >> >> > ?'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie >>>> des >>>> >> Monty >>>> >> >> >> ...', >>>> >> >> >> > ?'Re: os x, panther, python & co: msg#00041', >>>> >> >> >> > ?'Re: os x, panther, python & co: msg#00040', >>>> >> >> >> > ?'Cardiff Web Site Design, Professional web site design >>>> services >>>> >> >> ...', >>>> >> >> >> > ?'Python Properties', >>>> >> >> >> > ?'Frees < Programs < Python < Bin-Co', >>>> >> >> >> > ?'Torb: an interface between Tcl and CORBA', >>>> >> >> >> > ?'Royal Python Morphs', >>>> >> >> >> > ?'Python & Co'] >>>> >>>> >> >> >> > -- >>>> >> >> >> > _____________ >>>> >>>> >> >> >> > Maric Michaud >>>> >> >> >> > -- >>>> >> >> >> >http://mail.python.org/mailman/listinfo/python-list >>>> >>>> >> >> >> -- >>>> >> >> >> View this message in >>>> >>>> >> context:http://www.nabble.com/using-urllib2-tp18150669p18160312.html >>>> >> >> >> Sent from the Python - python-list mailing list archive at >>>> >> Nabble.com. >>>> >>>> >> >> > -- >>>> >> >> >http://mail.python.org/mailman/listinfo/python-list >>>> >>>> >> >> -- >>>> >> >> View this message in >>>> >> >> >>>> context:http://www.nabble.com/using-urllib2-tp18150669p18165634.html >>>> >> >> Sent from the Python - python-list mailing list archive at >>>> Nabble.com. >>>> >>>> >> > -- >>>> >> >http://mail.python.org/mailman/listinfo/python-list >>>> >>>> >> -- >>>> >> View this message in... >>>> >>>> read more ? >>> >>> The definitions were embedded in tables with a 'luna-Ent' class. I >>> pulled all of the tables with that class out, and then returned the >>> string value of td containing the actual definition. The findAll >>> method takes an optional dictionary, thus the {}. >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >> >> > > -- View this message in context: http://www.nabble.com/using-urllib2-tp18150669p18184788.html Sent from the Python - python-list mailing list archive at Nabble.com. From mwilson at the-wire.com Sat Jun 28 00:48:47 2008 From: mwilson at the-wire.com (Mel) Date: Sat, 28 Jun 2008 00:48:47 -0400 Subject: this is simple... References: Message-ID: ToshiBoy wrote: > I have two lists A and B that are both defined as range(1,27) I want > to find the entries that are valid for A = BxB [ ... ] > I get, as expected 1,4,9,16,25 printed out being the only members of B > where the condition is true, but when I print B I get: > > [1, 2, 3, 4, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25] > > 1 to 5 is correct, but why doesn't the remove method remove 7 and > above? What am I doing wrong here? Try this: A = range(1,27) B = range(1,27) C = [] for b in B: print "Trying", b if b*b in A: print b C.append (b) else: print "Removing", b B.remove(b) print 'B', B print 'C', C The essential problem is that your `B.remove`s are pulling the rug out from under your `for b in B:`. There are ways to mess with B while you iterate. Running though B backwards will do: `for b in B[::-1]:`, or iterating over a copy of B: `for b in B[:]:` or `for b in list(B):`. Leaving B alone and building up the desired items in C is probably simplest. Mel. From dlists.cad at gmail.com Wed Jun 18 15:41:44 2008 From: dlists.cad at gmail.com (dlists.cad at gmail.com) Date: Wed, 18 Jun 2008 12:41:44 -0700 (PDT) Subject: Function argument conformity check References: <0efa09ce-dbf9-4699-b87c-34c2c3b271f0@34g2000hsh.googlegroups.com> Message-ID: <9577cf2e-4440-4d97-b8e8-1dbc00bfca68@34g2000hsh.googlegroups.com> On Jun 18, 3:13 pm, C?dric Lucantis wrote: > Hi, > > Le Wednesday 18 June 2008 20:19:12 dlists.... at gmail.com, vous avez ?crit : > > > Hi. I am looking for a way to check if some given set of (*args, > > **kwds) conforms to the argument specification of a given function, > > without calling that function. > > > For example, given the function foo: > > def foo(a, b, c): pass > > > and some tuple args and some dict kwds, is there a way to tell if i > > _could_ call foo(*args, **kwds) without getting an exception for those > > arguments? I am hoping there is a way to do this without actually > > writing out the argument logic python uses. > > Each function object is associated to a code object which you can get with > foo.func_code. Two of this object's attributes will help you: co_argcount and > co_varnames. The first is the number of arguments of the function, and the > second a list of all the local variables names, including the arguments > (which are always the first items of the list). When some arguments have > default values, they are stored in foo.func_defaults (and these arguments are > always after non-default args in the co_argnames list). > > Finally, it seems that some flags are set in code.co_flags if the function > accepts varargs like *args, **kwargs, but I don't know where these are > defined. > > Note that I never found any doc about that and merely guessed it by playing > with func objects, so consider all this possibly wrong or subject to change. > > -- > C?dric Lucantis I am aware of these attributes, although you can get them all in a more organized form using the getfullargspec function in the inspect module from the standard library. The problem is that using these attributes, I would essentially have to re-write the logic python uses when calling a function with a given set of arguments. I was hoping there is a way to get at that logic without rewriting it. From sjmachin at lexicon.net Fri Jun 13 07:23:38 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 13 Jun 2008 04:23:38 -0700 (PDT) Subject: using re module to find References: <5aeb32bd-923f-4b98-952b-06097ac8479d@v1g2000pra.googlegroups.com> Message-ID: <79634319-52e5-48ba-a379-aa24049842c9@2g2000hsn.googlegroups.com> On Jun 13, 6:23 pm, anton wrote: > John Machin lexicon.net> writes: > > > > > On Jun 12, 7:11 pm, anton wrote: > > > Hi, > > > > I want to replace all occourences of " by \" in a string. > > > > But I want to leave all occourences of \" as they are. > > > > The following should happen: > > > > this I want " while I dont want this \" > > ... cut text off > > > > > What you want is: > > > >> import re > > >> text = r'frob this " avoid this \", OK?' > > >>> text > > 'frob this " avoid this \\", OK?' > > >> re.sub(r'(? > frob this \\" avoid this \\", OK?' > > > HTH, > > John > > -- > >http://mail.python.org/mailman/listinfo/python-list > > First.. thanks John. > > The whole problem is discussed in > > http://docs.python.org/dev/howto/regex.html#the-backslash-plague > > in the section "The Backslash Plague" > > Unfortunately this is *NOT* mentioned in the standard > python documentation of the re module. Yes, and there's more to driving a car in heavy traffic than you will find in the manufacturer's manual. > > Another thing which will always remain strange to me, is that > even if in the python doc of raw string: > > http://docs.python.org/ref/strings.html > > its written: > "Specifically, a raw string cannot end in a single backslash" > > s=r"\\" # works fine > s=r"\" # works not (as stated) > > But both ENDS IN A SINGLE BACKSLASH ! Apply the interpretation that the first case ends in a double backslash, and move on. > > The main thing which is hard to understand is: > > If a raw string is a string which ignores backslashes, > then it should ignore them in all circumstances, Nobody defines a raw string to be a "string that ignores backslashes", so your premise is invalid. > or where could be the problem here (python parser somewhere??). Why r"\" is not a valid string token has been done to death IIRC at least twice in this newsgroup ... Cheers, John From e.yunak at gmail.com Mon Jun 23 18:26:49 2008 From: e.yunak at gmail.com (Val-Amart) Date: Mon, 23 Jun 2008 15:26:49 -0700 (PDT) Subject: Terminating processes on Windows (handles and IDs) References: <98b73a28-fa07-4eac-8f3c-aec65aa819fe@k37g2000hsf.googlegroups.com> Message-ID: <36a78f0c-cbd4-45cd-a69f-44566f47b15f@b1g2000hsg.googlegroups.com> On Jun 23, 6:33?pm, geoffbache wrote: > Hi all, > > I've always wondered why os.kill isn't supported on Windows. I found a > discussion somewhere from 2006 about this so it seems others have > wanted it, but still nothing. So I have a half-baked solution > involving calling "taskkill" on Windows Vista or "tskill" on Windows > XP via the shell. I feel there has to be a better way. > > I'm also fairly confused about when I've got an ID and when I've got a > handle. The subprocess module gives me IDs which the above programs > accept, but other ways of spawning processes give me process handles > (while referring to them as process IDs in the docs...) and I don't > know how to kill a process with these. Besides, I've found an > amazingly useful PyGTK method, gobject.child_watch_add, which does > exactly what I want on UNIX but wants process handles on Windows. So I > can't use it in conjunction with subprocess there, and if I use some > other way of spawning processes I can't clean them up later. > > Is there any way to convert one of these numbers to the other? Or to > get a process handle out of subprocess? > (There must be one down there somewhere, surely?) > > Sorry for rambling a bit, am confused. > > Regards, > Geoff Bache My way to do it is using excellent wmi module by Tim Golden, which relies on Mark Hammond's pywin32 and Windows native wmi functionality. Here is the link - http://tgolden.sc.sabren.com/python/wmi.html Maybe, there is a more elegant way of doing that, but it works for me, and i feel nice with wmi. From torriem at gmail.com Thu Jun 19 18:44:50 2008 From: torriem at gmail.com (Michael Torrie) Date: Thu, 19 Jun 2008 16:44:50 -0600 Subject: don't make it worse! - was Re: SPAM In-Reply-To: <485A0E77.2050009@gmail.com> References: <88f0c3ba-46e1-4b30-a61d-482e5ecf339a@t12g2000prg.googlegroups.com> <485A0E77.2050009@gmail.com> Message-ID: <485AE162.8050407@gmail.com> Aspersieman wrote: > SPAM Obviously. Please refrain from replying to the SPAM on this list. It just makes the problem worse. Thanks. From maric at aristote.info Wed Jun 25 17:31:00 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 25 Jun 2008 23:31:00 +0200 Subject: Freeze problem with Regular Expression In-Reply-To: References: <6cf614F3f8ocoU1@mid.individual.net> Message-ID: <200806252331.00839.maric@aristote.info> Le Wednesday 25 June 2008 18:40:08 cirfu, vous avez ?crit?: > On 25 Juni, 17:20, Kirk wrote: > > Hi All, > > the following regular expression matching seems to enter in a infinite > > loop: > > > > ################ > > import re > > text = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA) > > una ' > > re.findall('[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-z]*\s*(?:[0-9 > >] *[A-Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$', text) > > ################# > > > > No problem with perl with the same expression: > > > > ################# > > $s = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA) una > > '; > > $s =~ /[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-z]*\s*(?:[0-9]*[A- > > Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$/; > > print $1; > > ################# > > > > I've python 2.5.2 on Ubuntu 8.04. > > any idea? > > Thanks! > > > > -- > > Kirk > > what are you trying to do? This is indeed the good question. Whatever the implementation/language is, something like that can work with happiness, but I doubt you'll find one to tell you if it *should* work or if it shouldn't, my brain-embedded parser is doing some infinite loop too... That said, "[0-9|a-z|\-]" is by itself strange, pipe (|) between square brackets is the character '|', so there is no reason for it to appears twice. Very complicated regexps are always evil, and a two or three stage filtering is likely to do the job with good, or at least better, readability. But once more, what are you trying to do ? This is not even clear that regexp matching is the best tool for it. -- _____________ Maric Michaud From bob at mellowood.ca Wed Jun 11 20:15:49 2008 From: bob at mellowood.ca (bvdp) Date: Wed, 11 Jun 2008 17:15:49 -0700 Subject: Simple and safe evaluator References: Message-ID: Matimus wrote: > > The solution I posted should work and is safe. It may not seem very > readable, but it is using Pythons internal parser to parse the passed > in string into an abstract symbol tree (rather than code). Normally > Python would just use the ast internally to create code. Instead I've > written the code to do that. By avoiding anything but simple operators > and literals it is guaranteed safe. > Just wondering ... how safe would: eval(s, {"__builtins__":None}, {} ) be? From my testing it seems that it parses out numbers properly (int and float) and does simple math like +, -, **, etc. It doesn't do functions like int(), sin(), etc ... but that is fine for my puposes. Just playing a bit, it seems to give the same results as your code using ast does. I may be missing something! From __peter__ at web.de Fri Jun 20 07:12:03 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 20 Jun 2008 13:12:03 +0200 Subject: Strange re problem References: <2a0a6f87-f72e-4190-85f8-6e43821e313a@r66g2000hsg.googlegroups.com> Message-ID: TYR wrote: > OK, this ought to be simple. I'm parsing a large text file (originally > a database dump) in order to process the contents back into a SQLite3 > database. The data looks like this: > > 'AAA','PF',-17.416666666667,-145.5,'Anaa, French Polynesia','Pacific/ > Tahiti','Anaa';'AAB','AU',-26.75,141,'Arrabury, Queensland, > Australia','?','?';'AAC','EG',31.133333333333,33.8,'Al Arish, > Egypt','Africa/Cairo','El Arish International';'AAE','DZ', > 36.833333333333,8,'Annaba','Africa/Algiers','Rabah Bitat'; > > which goes on for another 308 lines. As keen and agile minds will no > doubt spot, the rows are separated by a ; so it should be simple to > parse it using a regex. So, I establish a db connection and cursor, > create the table, and open the source file. > > Then we do this: > > f = file.readlines() > biglist = re.split(';', f) > > and then iterate over the output from re.split(), inserting each set > of values into the db, and finally close the file and commit > transactions. But instead, I get this error: > > Traceback (most recent call last): > File "converter.py", line 12, in > biglist = re.split(';', f) > File "/usr/lib/python2.5/re.py", line 157, in split > return _compile(pattern, 0).split(string, maxsplit) > TypeError: expected string or buffer > > Is this because the lat and long values are integers rather than > strings? (If so, any ideas?) No, the result of f.readlines() is a list, but re.split() expects a string as the second parameter. f = file.read() biglist = re.split(";", f) should work if the file fits into memory, but you don't need regular expressions here: biglist = file.read().split(";") is just as good -- or bad, if your data contains any ";" characters. Peter From straton at lampsacos.demon.co.uk Fri Jun 27 08:23:51 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Fri, 27 Jun 2008 13:23:51 +0100 Subject: How do I unit-test a specific case of a home-rolled exception ? In-Reply-To: References: Message-ID: Peter Otten wrote: > Ken Starks wrote: > >> I have an exception class, and I want to check that >> a particular instance of it has been raised; or >> more accurately that one is raised that is equal to >> an instance I specify. >> >> In the example below, I can check that a >> 'LongRationalError' is raised, but I want >> to check that it is specifically a >> 'LongrationalError('1') or a 'LongRationalError('2') >> >> How do I do that? > > (all untested) > > try: > LongRational(1, "7") > except LongRationalError, e: > self.assertEquals(e.code, "2") > else: > self.fail() > > Alternatively you can subclass LongRationalError... > > class LongRationalError(Exception): > pass > > class LongRationalDenominatorError(LongRationalError): > pass > > class LongRationalNumeratorError(LongRationalError): > pass > > ...and then check for the specialized exception: > > self.assertRaises(LongRationalDenominatorError, LongRational, 1, "7") > > Personally, I'd probably throw a plain old TypeError for incompatible types > of both numerator and denominator. > > Peter Thanks Peter, that answers my question nicely. I rather thought I would need a try .. except structure in my unit-test itself. From jason.scheirer at gmail.com Wed Jun 25 04:28:16 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Wed, 25 Jun 2008 01:28:16 -0700 (PDT) Subject: Porn Addiction References: <0bc1d618-f140-4390-9dd0-4ade923ab054@w1g2000prd.googlegroups.com> Message-ID: <96c7b5d6-7207-4af7-bde7-49891290aed7@u36g2000prf.googlegroups.com> On Jun 24, 5:24?pm, Hughjar... at gmail.com wrote: > Help, I'm addicted to porn. I've been downloading porn online and > masturbating to it for a few years... Lately it's gotten even worse, I > spend hours and hours surfing and masturbating to it. It's taking over > my life and ruining everything.. I even missed days from work because > of this addiction. > > I'm going to the porn as a way to avoid unwanted feelings or > procrastination and then it just takes over. > > What can I do to end this horrible addiction? > > -Hugh Obviously porn is awesome and an integral part of your life, you spambot (and your responding stormbot friends). The only solution is PETABYTES OF PORN. TERRIBLE TERRIBLE PORN. From sjmachin at lexicon.net Sun Jun 29 20:18:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 29 Jun 2008 17:18:02 -0700 (PDT) Subject: Function to import module to namespace References: Message-ID: <4cea42f2-b896-43a8-b8dd-ead2a1add327@z16g2000prn.googlegroups.com> On Jun 30, 9:52 am, bvdp wrote: > Terry Reedy wrote: > > > > > > > > > > Do you mean something like this? > > > > > >>> math.__dict__.update(string.__dict__) > > >>> dir(math) > > ['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', > > > > I think this is working.... First off, 2 module files: > > funcs.py > def func1(): > print "I'm func1 in funcs.py" > > more.py > def func2(): > print "I'm func2 in 'more.py'" > > and my wonderful main program: > > xx.py > import funcs > def addnewfuncs(p): > x = __import__(p) > funcs.__dict__.update(x.__dict__) > funcs.func1() > addnewfuncs('more') > funcs.func2() > > The first problem I had was getting import to accept a variable. It > doesn't seem to, so I used __import__(). Then, I had to remember to > assign this to a variable ... and then it appears to work just fine. > > Did I miss anything in this??? You are updating with *everything* in the 'more' module, not just the functions. This includes such things as __name__, __doc__, __file__. Could have interesting side-effects. One quick silly question: why do you want to do this anyway? Sorry, *two* quick silly questions: are the add-on modules under your control, or do you want to be able to do this with arbitrary modules? [If under your control, you could insist that such modules had an __all__ attribute with appropriate contents] A third: why do you want to import into an existing namespace? Now that you know about __import__, why just not call the functions where they are? Cheers, John From enleverlesX.XmcX at XmclaveauX.com Sun Jun 1 04:46:24 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sun, 1 Jun 2008 10:46:24 +0200 Subject: Merging ordered lists In-Reply-To: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> References: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> Message-ID: <484262f8$0$866$ba4acef3@news.orange.fr> Hi! Use set (union). Example: la=[2,1,3,5,4,6] lb=[2,8,6,4,12] #compact: print list(set(la).union(set(lb))) #detail: s1 = set(la) s2 = set(lb) s3 = s1.union(s2) print list(s3) @-salutations Michel Claveau From andrei.avk at gmail.com Mon Jun 9 13:29:38 2008 From: andrei.avk at gmail.com (Rainy) Date: Mon, 9 Jun 2008 10:29:38 -0700 (PDT) Subject: Separators inside a var name Message-ID: I have a stylistic question. In most languages words in var. name are separated by underscores or cap letters, resulting in var names like var_name, VarName and varName. I don't like that very much because all 3 ways of naming look bad and/or hard to type. From what I understand, scheme can have variables like var-name. I'm curious about reasons that python chose to disallow this. Another question I have is what other languages allow this naming scheme? Were there any languages that allowed space as a separator? What would be a practical way to separate variables from keywords in that case? "some long variable name", 'just a string', or maybe using 2 spaces: one var + other var + third var ? I think being able to easy have very long names for vars that are easy to type would be a fairly significant advantage. I know I'm probably being too obsessive about this, but that didn't stop me from posting. Comments? From MyDomDom at gmail.com Sat Jun 21 07:17:49 2008 From: MyDomDom at gmail.com (dominique) Date: Sat, 21 Jun 2008 04:17:49 -0700 (PDT) Subject: How to convert a ">" into a > Message-ID: Hello All, In a wx GUI, I would like to let the user choose between >, < or =. So, I created a combobox and when the user chooses ">" for instance, I wanted to return > (the objective is to send the operator into another complex method): Example: if variable == ">": return > But this is invalid syntax. How can I transform a ">" into the > operator ie without parenthesis, so that I can load it into another function ? Thanks in advance Dominique From dananrg at yahoo.com Sun Jun 22 18:11:55 2008 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: Sun, 22 Jun 2008 15:11:55 -0700 (PDT) Subject: Getting column names from a cursor using ODBC module? References: <4fe11953-15a9-4363-819f-b54b4f05941c@y38g2000hsy.googlegroups.com> Message-ID: <0d8458af-d48e-4790-80dd-7fd7745b1c48@2g2000hsn.googlegroups.com> Thanks Chris and John. Chris, this worked perfectly with the ODBC module that ships with Python Win32: > column_names = [d[0] for d in cursor.description] John, I've never heard of pyodbc but I'll have to look into it. Thanks again. Dana From R.Brodie at rl.ac.uk Fri Jun 6 11:33:35 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 6 Jun 2008 16:33:35 +0100 Subject: cgi, parse_header and semi-colon References: Message-ID: "Sylvain" wrote in message news:b80af57f-897d-4fd1-bebc-df0782143314 at 25g2000hsx.googlegroups.com... > If we upload a file with a semi-colon (i.e : "C:/my;file.jpg") : > cgi.FieldStorage.filename returns only "my" everything after the semi- > colon is missing > > Is it a bug or i'm missing something ? I doubt it's bug in parse_header, since it's meant to split on semicolons. Whether it's a bug in one of its callers, or the client not escaping sufficiently, I couldn't say offhand. From Lie.1296 at gmail.com Tue Jun 3 07:32:39 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 3 Jun 2008 04:32:39 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> Message-ID: <8479ceec-848e-43c2-8d72-a89c5a61372f@h1g2000prh.googlegroups.com> On Jun 3, 5:07?pm, "BJ?rn Lindqvist" wrote: > On Mon, Jun 2, 2008 at 10:50 PM, Russ P. wrote: > > On Jun 2, 6:41 am, Carl Banks wrote: > > >> You are not realizing that only useful(**) thing about data hiding is > >> that some code has access to the data, other code does not. ?If you > >> "hide" data equally from everyone it's just a useless spelling change. > > > I think you're missing the point. > > > As I see it, the primary value of data hiding is that it provides > > useful information on which data and methods are intended for the > > client and which are intended for internal use. It's like putting a > > front panel on a TV set with the main controls intended for the > > viewer. > > Here's my two cents. First of all, a TV is a bad analogy compared to > reusable software libraries. Really bad analogy. A TV is a horribly > complicated device which has to be dumbed down because otherwise it > would be to hard to use for ordinary people. I think it's actually quite a good analogy, a class may get quite complicated and it may do completely different things that the public interface seems to imply. Anyway, an analogy is an analogy, don't expect it to be exactly the same as the case itself, expect it to illustrate the point well enough and ignore the differences not being illustrated. TV is a good analogy since it illustrated the point quite well, that there are some things user may freely interact, some that users should not mess with, and things that is strictly not for you. Nevertheless, with the proper knowledge and proper tools, any users could open the case and get the special screwdriver to open the TV, if all else fails, he could always get a hammer to break the casing and gone his way through. Python does not enforce data-hiding because it expect people that gone his way to ignore the warning and get the special screwdriver to be knowledgeable enough to mess with it. C/C++ expects people to use hammer to break through their casings, and in the end, since the casings has already been broken, the device may never look as beautiful as before. In python, the device may appear to look just as beautiful. > A software developers relation to a third party library is more > similar to a TV repair man trying to repair a TV than to a random > person watching TV. For a repair man, the front panel is just useless > and in the way. No, for a knowledgable man (a TV repairman), he'd try first to fix the TV without opening the case (such as seeing whether the power cable is actually plugged), and if those attempts fails (or if he already know where the damage is from the beginning), he'd then open the screws. The public interface isn't "useless and in the way". > Oh, and to continue on the TV analogy, one of the reason why a TV is > complicated is because its interface is totally different from its > implementation. Channels are just a bad abstraction for tuning the > receiver to different frequencies and for switching inputs. Merely > using a TV doesn't teach you anything about how it actually works. Why couldn't a class have interface that's completely different thing than the implementation. > KISS: Keep It Simple Stupid. And it is always simpler to not implement > the gunk needed for data hiding than to do it. By keeping things > simple you keep your code easy to implement, easy to understand and > easy to reuse. > > Data hiding sacrifices implementation simplicity supposedly to make > the interface simpler and to keep backwards compatibility. It allows > you to change implementation details without affecting the > interface. But do you really want to do that? Consider this silly Java > example: > > ? ? class Foo { > ? ? ? ? private int bar; > ? ? ? ? public int getBar() { > ? ? ? ? ? ? return bar; > ? ? ? ? } > ? ? }; > > Then for some reason you decide that hm, "bar" is not a good attribute > name so you change it to "babar". And you can do that without changing > the public interface! Woho! So now you have a public getter named > "getBar" that returns an attribute named "babar". That's in reality > just bad and whoever is maintaining the implementation is going to be > annoyed that the getters name doesn't match the attribute name. > > What would have happened without data hiding? Renaming the public > attribute "bar" to "babar" probably cause some grief for someone > reusing your library, but you would keep your implementation pure. > > What about semantic changes? Data hiding doesn't protect you against > that, so you'll have to change your interface anyway. The interface > for a car hasn't changed much in the last 100 years, but the > implementation has. How easy is it to repair a car nowadays compared > to 30 years ago? > > And data hiding as a documentation aid is just a sham. "These methods > are public so you can call them, these aren't so hands off!" A reuser > of your library *will* want to know what happens on the inside, by > trying to make stuff impossible to reach you are just making that kind > of information much harder to come by. And we expect those people is ready that the car may blow off right in their face since they have violated the lines. If they broke the lines and still think that we're guilty for his burnt face, that's their problem. > The better method is to just write proper docstrings that tell the > user what the methods do and when they can be called. > > Another good way to see how useless data hiding is, is to try and unit > test a very encapsulated library. You'll see that it is almost > impossible to write good unit tests unless you publicly export > almost everything in the code. At which point you come to realize that > all the data hiding was for naught. > > -- > mvh Bj?rn From martin at v.loewis.de Tue Jun 17 01:28:45 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 17 Jun 2008 07:28:45 +0200 Subject: PEP 372 -- Adding an ordered directory to collections In-Reply-To: <97b828d8-e64c-47db-8b8e-d403e8076756@x35g2000hsb.googlegroups.com> References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <4856e80c$0$30401$9b622d9e@news.freenet.de> <97b828d8-e64c-47db-8b8e-d403e8076756@x35g2000hsb.googlegroups.com> Message-ID: <48574B8D.6010102@v.loewis.de> > My guess is that the two main memory allocate/deallocate cases are 1) > appending a new item to the end, and 2) GC'ing the entire data > structure. I would optimize these 2 at the expense of all others. Does that include dictionary lookups? Regards, Martin From gagsl-py2 at yahoo.com.ar Wed Jun 25 18:58:48 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 25 Jun 2008 19:58:48 -0300 Subject: python script for tortoise cvs References: <8c7f10c60806190626i2dd28eacp50a4de20c2a6556d@mail.gmail.com> <5ed8a05d-81ac-4625-b4f5-8169495cb654@l42g2000hsc.googlegroups.com> Message-ID: En Tue, 24 Jun 2008 12:16:07 -0300, sandeep escribi?: > i think ur suggestions do formulate my problem.now since i know some > commands i wanted to know how can i execute cvs commands from python > or we can say how can i capture the output from the cvs command ?. Use the subprocess module py> cvsexe = r"c:\Archivos de programa\CVSNT\cvs.exe" py> import subprocess py> p = subprocess.Popen([cvsexe, "status", "dinglob.pas"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) py> output = p.communicate()[0] py> print output =================================================================== File: dinglob.pas Status: Up-to-date Working revision: 1.102 Repository revision: 1.102 /.../DINW/dinglob.pas,v Expansion option: kv Commit Identifier: 484474257304f18 Sticky Tag: (none) Sticky Date: (none) Sticky Options: (none) Merge From: (none) -- Gabriel Genellina From michele.simionato at gmail.com Mon Jun 16 05:01:13 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 16 Jun 2008 02:01:13 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> Message-ID: On Jun 16, 10:37?am, Armin Ronacher wrote: > Abstract > ======== > > This PEP proposes an ordered dictionary as a new data structure for > the ``collections`` module, called "odict" in this PEP for short. ?The > proposed API incorporates the experiences gained from working with > similar implementations that exist in various real-world applications > and other programming languages. +1, I have been waiting for an odict in the library for at least 5 years. Michele Simionato From eduardo.tessarioli at gmail.com Tue Jun 17 14:34:27 2008 From: eduardo.tessarioli at gmail.com (Eduardo Henrique Tessarioli) Date: Tue, 17 Jun 2008 15:34:27 -0300 Subject: Static memory allocation in Python Message-ID: <5868cf920806171134n33af0512j8ad93fc300fe015a@mail.gmail.com> Hi, I am running a very simple python application and I noted that the memory allocation is something like 4,5M. This is a problem in my case, because I have to run 2 thousand process at the same time. The memory I need is 100k or less. Is there any way to set this for the python process? Regards, Eduardo -------------- next part -------------- An HTML attachment was scrubbed... URL: From maric at aristote.info Tue Jun 24 04:33:07 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 24 Jun 2008 10:33:07 +0200 Subject: binary representation of an integer In-Reply-To: <14e14b5e-ce39-414a-a450-7c81baaabc3a@79g2000hsk.googlegroups.com> References: <14e14b5e-ce39-414a-a450-7c81baaabc3a@79g2000hsk.googlegroups.com> Message-ID: <200806241033.10037.maric@aristote.info> Le Tuesday 24 June 2008 10:03:58 eliben, vous avez ?crit?: > Hello, > > I'm interested in converting integers to a binary representation, > string. I.e. a desired function would produce: > > dec2bin(13) => "1101" > > The other way is easily done in Python with the int() function. > > Perl has a very efficient way to do dec2bin, because its pack/unpack > have a B format for binary representations, so it's done with: > > sub dec2bin { > my $str = unpack("B32", pack("N", shift)); > $str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros > return $str; > } > > Python's pack/unpack don't have the binary format for some reason, Yes, but I think the %b format specifier has been added to p3k but will not in python 2.x. > so > custom solutions have to be developed. One suggested in the ASPN > cookbook is: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 > However, it is very general and thus inefficient. > > What would be the quickest way to do this ? I think that for dec2bin > conversion, using hex() and then looping with a hex->bin lookup table > would be probably much faster than the general baseconvert from the > recipe. > > What do you think? Something like that, less typing with octal conversion :) >>>[8]: oct2bin = {'0':'000', '1':'001', '2':'010', '3':'011', '4':'100', '5':'101', '6':'110', '7':'111'} >>>[9]: ''.join(oct2bin[e] for e in "%o"%35).lstrip('0') ...[9]: '100011' -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 4 26 88 00 97 Mobile: +33 6 32 77 00 21 From ivan.illarionov at gmail.com Thu Jun 5 11:21:46 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 5 Jun 2008 08:21:46 -0700 (PDT) Subject: Tuples part 2 References: <6d3e6d40-63a6-40d1-8ea4-5ddf40238d8d@m44g2000hsc.googlegroups.com> <99bc30fb-532a-4c4f-9f5e-e7a18c28d2a5@z72g2000hsb.googlegroups.com> Message-ID: <0ecaaa47-3ad4-4f67-9d48-94d5d1951bc6@y21g2000hsf.googlegroups.com> On 5 ???, 18:56, Ivan Illarionov wrote: > On 5 ???, 18:19, "victor.hera... at gmail.com" > wrote: > > > > > On Jun 5, 3:49 pm, Ivan Illarionov wrote: > > > > On 5 ???, 01:57, "victor.hera... at gmail.com" > > > wrote: > > > > > Hi Everyone, > > > > > i have another question. What if i wanted to make n tuples, each with > > > > a list of coordinates. For example : > > > > > coords = list() > > > > for h in xrange(1,11,1): > > > > for i in xrange(1, 5, 1) : > > > > for j in xrange(1, 5, 1) : > > > > for k in xrange(1,2,1) : > > > > coords.append((i,j,k)) > > > > lista+str(h)= tuple coords > > > > print tuple(coords) > > > > > so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do > > > > it the way i show you above but it is not working properly. I wish you > > > > could help me with that. Thanks again, > > > >>> from itertools import repeat, izip > > > >>> coords = tuple((i,j,k) for i in xrange(1,5) for j in xrange(1,5) for k in xrange(1,2)) > > > >>> locals().update(("tuple%s" % i, coord) for i, coord in izip(xrange(1,11), repeat(coords))) > > > >>> tuple1 > > > > ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (2, 1, 1), (2, 2, 1), (2, > > > 3, 1), (2 > > > , 4, 1), (3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1), (4, 1, 1), (4, 2, > > > 1), (4, 3 > > > , 1), (4, 4, 1)) > > > > Does this help? > > > > But I don't understand why you need this? > > > > Ivan > > > Hi, > > > What i need is, for example: > > > tuple 1=((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)) > > > tuple 2=((2, 1, 1), (2, 2, 1), (2, 3, 1), (2, 4, 1)) > > > tuple 3=((3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1)) > > > and so on. Please help me and sorry for not taking the time to post my > > questions properly. > > > Victor > > Or even so: > > locals().update(("tuple_%s" % i, tuple((i,j,k) for j in range(1,5) for > k in range(1,2))) for i in range(1,5)) > > Ivan Tried to make it readable: def iter_coords(i): for j in xrange(1,5): for k in xrange(1,2): yield i, j, k def iter_vars(): for i in xrange(1, 5): yield "tuple_%s" % i, tuple(iter_coords(i)) locals().update(dict(iter_vars())) >>> tuple_1 ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)) >>> tuple_2 ((2, 1, 1), (2, 2, 1), (2, 3, 1), (2, 4, 1)) >>> tuple_3 ((3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1)) >>> tuple_4 ((4, 1, 1), (4, 2, 1), (4, 3, 1), (4, 4, 1)) Ivan From grante at visi.com Sat Jun 14 16:46:11 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 14 Jun 2008 15:46:11 -0500 Subject: Creating a TCP/IP connection on already-networked computers References: <4853f269$0$11615$607ed4bc@cv.net> <4854123f$0$5017$607ed4bc@cv.net> <485413d0$0$4997$607ed4bc@cv.net> <485425b2$0$11631$607ed4bc@cv.net> Message-ID: On 2008-06-14, John Salerno wrote: > Grant Edwards wrote: > >>> Shouldn't it be something different, since the requests are >>> coming from a different computer than the server computer? >> >> Works fine for me. When I run the client program on a machine >> different than the server program, the server program prints >> out "connected from:" and then the client machine's IP address. > > Hmm, so could the reason that the client request is shown to be coming > from the same IP address as the server machine be that they are on the > same home network? No, not for the usual value of "on the same home network". I've no idea how your home network is set up, so that's about all I can say. > I guess to truly test my question, I need to have two > computers that are completely "unrelated" to one another -- > meaning they are in no way connected via any type of network > prior to running these scripts. If the two computers are in no way connected via any type of network, then the two programs won't be able to talk to each other. The programs can't create a network, they can only use one that already exists. -- Grant Edwards grante Yow! I've got an IDEA!! at Why don't I STARE at you visi.com so HARD, you forget your SOCIAL SECURITY NUMBER!! From jschroed at gmail.com Mon Jun 9 03:27:16 2008 From: jschroed at gmail.com (John Schroeder) Date: Mon, 9 Jun 2008 00:27:16 -0700 Subject: Access to CAN-Bus In-Reply-To: <6b43jvF3a2qu9U1@mid.uni-berlin.de> References: <484cd469$0$28520$3b214f66@aconews.univie.ac.at> <6b43jvF3a2qu9U1@mid.uni-berlin.de> Message-ID: <4878ad7b0806090027ta169e8co14693a8d964801b9@mail.gmail.com> Isn't a CAN bus accessed via the COM ports (serial or parallel)? If this is the case, then you should use pySerial and/or pyParallel but you would have to define the protocol yourself. (I've used pyserial to implement a LAPB protocol.) On Mon, Jun 9, 2008 at 12:15 AM, Diez B. Roggisch wrote: > Thin Myrna schrieb: > >> I'd like to access some drive hardware via CAN bus from Python under Linux >> (sending rec'ing PDOs). Googling around I couldn't find a Python package, >> but people who said that they are doing this, though. I guess they are >> using their home brewn software. >> Any pointer to - such software (anyone willing to share his experience?) >> - how to write such software? >> >> Under Windows, I guess, I could use some COM or ctypes functionality to >> access the hardware vendor's hardware. What if I wanted to access such >> hardware from Linux? Is there a package that allows that in a vendor (who >> doesn't support Linux) independent way? >> > > I've never heard of a OS-level CAN-bus-integration. So I doubt that there > is any vendor-independent way. > > Doesn't your CAN-bus-interface have some library or driver support? > > Diez > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dan at catfolks.net Thu Jun 26 13:06:27 2008 From: dan at catfolks.net (Daniel Mahoney) Date: Thu, 26 Jun 2008 12:06:27 -0500 Subject: I Need A Placeholder References: Message-ID: On Thu, 26 Jun 2008 10:03:47 -0700, Ampedesign wrote: > I'm trying to build a try/except case, and I want to have the except > function like such: > > try: > # Do some code here > var = 1 # For example > except: > #Do nothing here > > The only problem is if I leave a comment only in the except block, I > get an error back saying that the except block is not properly > formatted, since it has no content other than a comment. > > So if anyone could suggest some code to put there as a placeholder > that would be wonderful. "pass" would work fine. try: # Do something that can throw an exception except: pass From kyosohma at gmail.com Mon Jun 9 14:00:28 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 9 Jun 2008 13:00:28 -0500 Subject: How to get full path to script? In-Reply-To: References: Message-ID: On Mon, Jun 9, 2008 at 12:42 PM, Sebastian lunar Wiesner wrote: > Mike Driscoll at Montag 09 Juni 2008 18:20: > >> On Mon, Jun 9, 2008 at 11:07 AM, kj wrote: >>> In "Mike Driscoll" >>> writes: >>> >>>>For my compiled scripts, I usually use this variation: >>> >>>>path = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))) >>> >>> Thanks. But why the os.path.join()? (BTW, I did read the docs >>> before posting, but they make no sense to me; they say that >>> os.path.join joins "one or more path components intelligently", >>> but what does it mean to join *one* component?) >>> >>> Kynn >>> >>> -- >>> NOTE: In my address everything before the first period is backwards; >>> and the last period, and everything after it, should be discarded. >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> The idea of the join method is to create the path in an OS agnostic >> fashion. Linux uses forward slashes and Windows uses backward slashes >> to join the parts. The join method does this for you so you don't have >> to. > > I guess, you didn't get his point. He seems to be aware that os.path.join > creates a path from _multiple_ strings by joining them with the correct > separator used by the underlying platform. > > But he was asking why one would invoke os.path.join on a _single_ string, as > you did in your example. I'm wondering about this, too. It doesn't make > sense to me. os.path.join doesn't convert existing separators to the > platform-specific ones. And even if it would, sys.argv[0] already contains > a correct path, so there is nothing that needs conversion. So why use it > with a _single_ argument? I'd appreciate an example, illustrating the use > of this ;) > > > -- > Freedom is always the freedom of dissenters. > (Rosa Luxemburg) > -- > http://mail.python.org/mailman/listinfo/python-list > Okay, basically the answer is that I'm kind of stupid. Months ago, the users on the wxPython group were discussing this issue and one of them posted that snippet of code to show how they worked around the issue. I thought I'd try it and it worked great, although I couldn't really follow what was happening at the time. Looking at it now, there doesn't appear to be any reason for the os.path.join part. I tried running one of my simple scripts with and without it and they return the same string. I apologize for propagating erroneous code. Mike From morton.thomas at googlemail.com Tue Jun 10 15:01:12 2008 From: morton.thomas at googlemail.com (Thomas Morton) Date: Tue, 10 Jun 2008 20:01:12 +0100 Subject: problems with opening files due to file's path References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <17761946.post@talk.nabble.com> Message-ID: <7B9AC1C9E17440AA89A4CB3937219C47@ErrantGaming> heh thanks Mike - glad im not going mad :P Just tested locally in IDLE (I know I know!) and it works for me like this: >>> test = os.path.join(os.getcwd(),"NEWS.txt") >>> test 'D:\\Python25\\NEWS.txt' >>> os.startfile(r"%s"%test) >>> And the file opens... Does the file definitely exist? Tom -------------------------------------------------- From: "Alexnb" Sent: Tuesday, June 10, 2008 7:37 PM To: Subject: Re: problems with opening files due to file's path > > No this time it perhaps gave me the worst of all heres what I entered, and > the output > >>>> startfile(r"%s"%full) ***full is the path*** > > startfile(r"%s"%full) > > WindowsError: [Error 2] The system cannot find the file specified: > '"C:\\Documents and Settings\\Alex\\My Documents\\My > Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I\'m Yours (Single)\x01 - I\'m > Yours.wma"' > > > Thomas Morton wrote: >> >> maybe try string substitution... not sure if that's really the BEST way >> to >> do it but it should work >> >> startfile(r"%s"%variable) >> >> -------------------------------------------------- >> From: "Alexnb" >> Sent: Tuesday, June 10, 2008 7:05 PM >> To: >> Subject: Re: problems with opening files due to file's path >> >>> >>> Well, now i've hit another problem, this time being that the path will >>> be >>> a >>> variable, and I can't figure out how to make startfile() make it raw >>> with >>> a >>> variable, if I put startfile(r variable), it doesn't work and >>> startfile(rvariable) obviously won't work, do you know how to make that >>> work >>> or better yet, how to take a regular string that is given and make every >>> single "\" into a double "\\"? >>> >>> Mike Driscoll wrote: >>>> >>>> On Jun 10, 11:45 am, Alexnb wrote: >>>>> Gerhard H?ring wrote: >>>>> >>>>> > Alexnb wrote: >>>>> >> Okay, so what I want my program to do it open a file, a music file >>>>> in >>>>> >> specific, and for this we will say it is an .mp3. Well, I am using >>>>> >> the >>>>> >> system() command from the os class. [...] >>>>> >>>>> >> system("\"C:\Documents and Settings\Alex\My Documents\My >>>>> >> Music\Rhapsody\Bryanbros\Weezer\(2001)\04 - Island In The >>>>> Sun.wma\"") >>>>> >> [...] >>>>> >>>>> > Try os.startfile() instead. It should work better. >>>>> >>>>> > -- Gerhard >>>>> >>>>> > -- >>>>> >http://mail.python.org/mailman/listinfo/python-list >>>>> >>>>> No, it didn't work, but it gave me some interesting feedback when I >>>>> ran >>>>> it >>>>> in the shell. Heres what it told me: >>>>> >>>>> >>> os.startfile("C:\Documents and Settings\Alex\My Documents\My >>>>> >>> Music\Rhapsody\Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm >>>>> >>> Yours.wma") >>>>> >>>>> Traceback (most recent call last): >>>>> File "", line 1, in >>>>> os.startfile("C:\Documents and Settings\Alex\My Documents\My >>>>> Music\Rhapsody\Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm >>>>> Yours.wma") >>>>> >>>>> WindowsError: [Error 2] The system cannot find the file specified: >>>>> "C:\\Documents and Settings\\Alex\\My Documents\\My >>>>> Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\x01 - I'm >>>>> Yours.wma" >>>>> >>>>> See it made each backslash into two, and the one by the parenthesis >>>>> and >>>>> the >>>>> 0 turned into an x.... >>>>> -- >>>>> View this message in >>>>> context:http://www.nabble.com/problems-with-opening-files-due-to-file%27s-pat... >>>>> Sent from the Python - python-list mailing list archive at Nabble.com. >>>> >>>> Yeah. You need to either double all the backslashes or make it a raw >>>> string by adding an "r" to the beginning, like so: >>>> >>>> os.startfile(r'C:\path\to\my\file') >>>> >>>> HTH >>>> >>>> Mike >>>> -- >>>> http://mail.python.org/mailman/listinfo/python-list >>>> >>>> >>> >>> -- >>> View this message in context: >>> http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17761338.html >>> Sent from the Python - python-list mailing list archive at Nabble.com. >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -- > View this message in context: > http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17761946.html > Sent from the Python - python-list mailing list archive at Nabble.com. > > -- > http://mail.python.org/mailman/listinfo/python-list From steve at holdenweb.com Wed Jun 4 08:57:08 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Jun 2008 08:57:08 -0400 Subject: Training Class in July Message-ID: <48469124.6050304@holdenweb.com> Holden Web is holding the second of its public "Introduction to Python" classes on July 8-10 in Springfield, VA (just outside Washington, DC). The class is described briefly at http://holdenweb.com/py/introclass/ and the current schedule is at http://holdenweb.com/py/training/ Bookings are now being accepted through our web site. Please contact info at holdenweb.com for multi-student discount details. Comments from the students on our March class: "Great class. Very informative" JSc "This tied Python together and now I can go learn on my own until I hit the next plateau" JSa "Excellent course, lots of good information" VB "It was a good course and the price was just right" AW -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From tjreedy at udel.edu Sun Jun 15 15:34:22 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 15 Jun 2008 15:34:22 -0400 Subject: Explaining Implementing a Binary Search Tree. References: Message-ID: "Bart Kastermans" wrote in message news:ae91857d-ea63-4204-9fc3-251049adee98 at k13g2000hse.googlegroups.com... |I wrote a binary search tree in python, explaining as I was doing it | how and why I did it. I am very interested in receiving comments on | the code, process, and anything else that will improve my coding or | writing. | | I wrote this all up in my blog at: | | http://kasterma.wordpress.com/2008/06/15/implementing-a-binary-search-tree/ | | The code of the class has been copied below, but the description of | the process (mostly an attempt at approaching test driving development | for as far as I understand the term) has not been copied. | | Any and all comments are appreciated. | | Best, | Bart | | *********** python code ************************ | | | import re | | class BSTree: | def __init__ (self, value = None): | self.value = value | self.left = None | self.right = None There are two possible approaches. 1. Define 1 tree class that is also used for subtrees -- what you did. Complication: self.value of root node can be none, so you constantly have to check self.value for None even though only possible for root node. 2. Define tree class and node class. This had other complications, but removes that above and makes str easier. tree.str = '(' str(rootnode) ')' and node.str= self.value '(' str(self.left) ')' '(' str(self.right) ')'. If use '' instead of None, no conditionals are needed. (This might apply partly to your version as well.) Or define class NullTree with a singleton instance with no attributes and a str method returning '' and an inOrder method yielding nothing. This would also eliminate the condifionals in the inOrder method. Not sure what is best. With a good test suite, it is easy to make sure alternative implementations 'work' before testing for speed. | def __str__ (self): string appending is an O(n**2) operations. The usual idiom, applied here, would be slist = ['('], slist.append(str(self.value)), .... return ''.join(slist). In other words, collect list of pieces and join at end. | string = "(" | if not self.value == None: | string += str (self.value) | | if not (self.left == None and self.right == None): | if self.left != None: | string += str (self.left) | else: | string += "()" | | if self.right != None: | string += str (self.right) | else: | string += "()" | | string += ")" | | return string | | def FromString (self, string): | """ parses the string and builds the corresponding tree. | | If the parsing fails we print an error message and make no | guarantees about the state of the tree. | | """ | | def readNumber (string, index): | """ reads the number starting at index. | | Returns the number (as a string) that starts at index and | the index that is just after the number. It expects the | index to point to the first numberal. | | """ | | isdigit = re.compile ("\d") | number = "" | while isdigit.match (string [index]): | number += string[index] | index += 1 | | return number, index | | def FromString_Help (string, index): | """ The function that actually does the parsing of the | string. | | Variable index indicates where in the string we start | working, | it should be pointing to an open paren, and in returning | point | to just after the corresponding closing paren. | | """ | | if not string [index] == "(": | print "FromString_Help: ERROR: no opening paren", | print string, index | | tree = BSTree () | | tree.value, index = readNumber (string, index + 1) | | if string [index] == "(": | tree.left, index = FromString_Help (string, index) | tree.right, index = FromString_Help (string, index) | | if not string[index] == ")": | print "FromString_Help: ERROR: no closing paren" | print string, index | | if tree.value == '' and tree.left == None and tree.right | == None: | return None, index + 1 | else: | tree.value = int (tree.value) | | return tree, index + 1 | | index = 0 | tree, index = FromString_Help (string, index) | | if tree == None: | print "FromString: ERROR: empty tree passed" | return | | self.value = tree.value | self.left = tree.left | self.right = tree.right | | def inOrder (self): | """ gives a generator that runs through the tree inOrder """ Nope. Returns an inorder list of values. For an actual generator, which I recommend, *yield* values. | | values = [] [delete this' | if self.left != None: | values += self.left.inOrder () for value in self.left.inOrder: yield value | if self.value != None: | values.append (self.value) yield self.value | if self.right != None: | values += self.right.inOrder () for value in self.right.inOrder: yield value | return values [delete this] The above with result in a stack of generators as deep as the tree. It would probably be faster to eliminate the recursion with an explicit stack of trees, but I cannot currently write that off the top of my head. (This is part of my current writing project.) But again, a test suite eases exploration of alternatives. | def Insert (self, value): | """ add value to the tree in BSTree fashion. | | We add the value so that the values of the tree will be in | order. We do not duplicate values in the tree. | | """ | if self.value == None: # first value added to this tree | self.value = value | | if self.value < value: | if self.right == None: | self.right = BSTree (value) | else: | self.right.Insert (value) | | if self.value > value: | if self.left == None: | self.left = BSTree (value) | else: | self.left.Insert (value) | | def Delete (self, value, parent = None, RL = None): | """ remove value from the tree in BSTree fashion. | | Note: we might end up with an empty tree. | | """ | if self.value == value: | if self.left == None and self.right == None: | if parent != None: | if RL == "right": | parent.right = None | else: | parent.left = None | else: | self.value = None # created an empty tree, note | only | # happens at the root. | return | if self.left == None: | self.value = self.right.value | self.left = self.right.left | self.right = self.right.right | elif self.left.right == None: | self.value = self.left.value | self.left = self.left.left | else: | moveup = self.left | while moveup.right != None: | # note that by the elif above at least one step is | taken | # we are here looking for the node to move up to | the root | moveup_parent = moveup | moveup = moveup.right | moveup_parent.right = moveup.left | self.value = moveup.value | return | | if self.value < value: | self.right.Delete (value, self, "right") | | if self.value > value: | self.left.Delete (value, self, "left") | | def Search (self, value): | if self.value == value: | return "yes" | if self.value < value: | if self.right == None: | return "no" | else: | return self.right.Search (value) | if self.value > value: | if self.left == None: | return "no" | else: | return self.left.Search (value) | -- | http://mail.python.org/mailman/listinfo/python-list | From joe.p.cool at googlemail.com Sat Jun 28 18:13:21 2008 From: joe.p.cool at googlemail.com (Joe P. Cool) Date: Sat, 28 Jun 2008 15:13:21 -0700 (PDT) Subject: surprising behaviour of os.environ.clear References: <463baf33-e2d5-41fd-839e-aae45ee5433e@b1g2000hsg.googlegroups.com> <52ecaa6c-b476-4720-9fd4-362471c2686e@k13g2000hse.googlegroups.com> Message-ID: <04719ede-59df-4845-bd63-4cbb2a34c649@z66g2000hsc.googlegroups.com> On 28 Jun., 23:06, "Joe P. Cool" wrote: > On 28 Jun., 04:05, Benjamin wrote: > > > On Jun 27, 4:05 pm, "Joe P. Cool" wrote: > > This is because of how os.environ is implement with a UserDict > > subclass. You should report this at bugs.python.org. > > issue 3227: os.environ.clear has no effect on child processes. According to Benjamin Peterson this has been fixed in the upcoming Python 2.6. From mnordhoff at mattnordhoff.com Fri Jun 27 12:50:34 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 27 Jun 2008 16:50:34 +0000 Subject: Windows OS , Bizarre File Pointer Fact In-Reply-To: <864ab9f2-7d99-49f0-9d41-93ec41e26203@y38g2000hsy.googlegroups.com> References: <864ab9f2-7d99-49f0-9d41-93ec41e26203@y38g2000hsy.googlegroups.com> Message-ID: <48651A5A.1020602@mattnordhoff.com> Taygun Kekec wrote: > Code : > #!/usr/bin/python > # -*- coding: utf-8 -*- > import os > > if os.name == 'nt': > OS_Selection = 0 > elif os.name == 'posix': > OS_Selection = 1 > else : > OS_Selection = 1 > > del_cmd_os = ( "del","rm") > filelist = ("ddd.txt","eee.txt","fff.txt") > > # Creating Files > for elem in filelist: > open( elem, 'w').write("Selam") > > # > # Removing Files > for elem in filelist: > fp = open( elem, 'r') > os.system( "%s %s" % (del_cmd_os[OS_Selection], fp.name)) > fp.close() > # > > Run this code on Windows XP , it says "the file is being used by > another process" and fails to delete the file. I tried replacing : > # > for elem in filelist: > open( elem, 'w').write("Selam") > # > with : > # > for elem in filelist: > fp = open( elem, 'w') > fp.write("Selam") > fp.close() > # > > in case of any interpreter file pointer destructor failure but it > didnt change anything. > Do you have any idea why my files cannot be deleted from my disk with > 2nd part of my code ? Why are you executing another program just to delete a file? >>> import os >>> os.remove('some/file.txt') -- From mmanns at gmx.net Sun Jun 1 14:17:36 2008 From: mmanns at gmx.net (Martin Manns) Date: Sun, 1 Jun 2008 20:17:36 +0200 Subject: pyspread 0.0.7 Message-ID: pyspread 0.0.7 has been released. -- New features: + CSV import dialog with preview grid Bug fixes: + setup.py now installs correctly into a sub-folder (tested for Linux and WinXP). -- About: pyspread is a spreadsheet that accepts a pure python expression in each cell. -- Highlights: + No non-python syntax add-ons + Access to python modules from cells + 3D grid + Numpy object array for representation of string entry into grid cell + Numpy object array for representation of eval function array + Cell access via slicing of numpy function array + X, Y, and Z yield current cell location for relative reference Requires: Python >=2.4, Numpy 1.0.4, and wxPython 2.8.7.1. License: GPL Project page: http://pyspread.sourceforge.net Best Regards Martin From saluk64007 at gmail.com Wed Jun 11 17:11:49 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Wed, 11 Jun 2008 14:11:49 -0700 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> <484e3526$0$30894$426a74cc@news.free.fr> <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> <783c55ec-a294-4600-91d9-4a0d78632c49@t12g2000prg.googlegroups.com> <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> <484f880c$0$6412$426a74cc@news.free.fr> Message-ID: On Wed, Jun 11, 2008 at 12:28 PM, Russ P. wrote: > > If Desthuilliers doesn't like my suggestion, then fine. If no other > Python programmer in the world likes it, then so be it. But do we > really need to get personal about it? Python will not be ruined if it > gets such a keyword, and Desthuilliers would be perfectly free to > continue using the leading-underscore convention if he wishes. Where > is the threat to his way of life? > Well, you have to understand that a lot of python programmers are refugees from the microsoft or sun worlds, where we were forced to do things a certain way, and often it was not in our opinion the best way, but there wasn't anything we could do about it. Some of these refugees are very experienced in that other world, and don't want to go back there. So proposing that python borrow these methods of control from the place we have fled from can feel threatening. Some people obviously take it more personally than others, but this is a general feeling a lot of python programmers share. Also I'm fairly certain you're not the first to mention this topic. Here's what the cookbook has to say: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/573442 Something like that is really your best bet. -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Thu Jun 19 12:37:16 2008 From: aahz at pythoncraft.com (Aahz) Date: 19 Jun 2008 09:37:16 -0700 Subject: dict order References: <4804032a-adef-4973-ae21-acc4ad2dce37@z72g2000hsb.googlegroups.com> <411fc353-dd54-4bbc-a72e-ddee66408313@c58g2000hsc.googlegroups.com> Message-ID: In article <411fc353-dd54-4bbc-a72e-ddee66408313 at c58g2000hsc.googlegroups.com>, wrote: > >Whoops > >for keys, values in dict_one.items(): > if keys in dict_two: > if values == dict_two[keys]: Except that "keys" implies a plural (meaning more than one thing); in a for loop, each iteration will have only one key. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From stefan_ml at behnel.de Thu Jun 26 13:58:04 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 26 Jun 2008 19:58:04 +0200 Subject: ask for a RE pattern to match TABLE in html In-Reply-To: References: Message-ID: <4863d8ac$0$27448$9b4e6d93@newsspool4.arcor-online.net> oyster wrote: > that is, there is no TABLE tag between a TABLE, for example >
    1.the curd of milk separated from the whey and >>>> prepared >>>> >> in >>>> >> >> many ways as a food.
    something with out table tag
    > what is the RE pattern? thanks > > the following is not right > [^table]*? Why not use an HTML parser instead? Try lxml.html. http://codespeak.net/lxml/ Stefan From ian.g.kelly at gmail.com Fri Jun 13 16:13:32 2008 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 13 Jun 2008 14:13:32 -0600 Subject: Mapping None. Why? In-Reply-To: References: Message-ID: <3fc761710806131313y56889965ic41197b1ce266d0f@mail.gmail.com> On Fri, Jun 13, 2008 at 2:00 PM, Terry Reedy wrote: > filter(None, iterable) works the same way: None-> identity function, > The immediate reason is the Python has no builtin id(). > But apparently there is also historical precedent in the functional > community for this convention. Another way of viewing it is that filter(None, iterable) applies no function at all before testing the truth values, which does make some sense. With map, however, this is not strictly true. From s0suk3 at gmail.com Mon Jun 16 19:20:01 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Mon, 16 Jun 2008 16:20:01 -0700 (PDT) Subject: Please explain Python "__whatever__" construct. References: <02c8f509-2889-433b-a548-62ead677bd19@p39g2000prm.googlegroups.com> Message-ID: On Jun 16, 4:56 pm, bsag... at gmail.com wrote: > After a couple of weeks studying Python, I already have a few useful > scripts, including one that downloads 1500 Yahoo stock quotes in 6 > seconds. However, many things are puzzling to me. I keep on seeing > things like "__main__" in scripts. A more obscure example would be > "__add__" used in string concatenation. For example, I can use "Hello > "+"world (or just "Hello" "world") to join those two words. But I can > also use "Hello ".__add__("world"). When and why would I ever use > "__main__" or the many other "__whatever__" constructs? Generally, names with two leading and trailing underscores signal something "internal". Though the string "__main__" is rather something else: the variable __name__ is set to the string "__main__" when a script is run as a script (i.e., is not imported). The convention is also common in built-in object methods, such as the one you mentioned: the built-in type str's __add__() method. Personally, I usually try to avoid using such methods directly, because, as I said, they're rather for internal use or for special functionality. For example, when the expression '"hello" + "world"' is evaluated, it's likely that Python is calling one of the string's __add__() method internally to perform the "addition." So I'd recommend that you don't use those methods unless you absolutely need direct access to their functionality. From aafshar at gmail.com Wed Jun 4 08:34:28 2008 From: aafshar at gmail.com (Ali) Date: Wed, 4 Jun 2008 05:34:28 -0700 (PDT) Subject: Help need with subprocess communicate References: <0312b7e9-bffe-4360-bf3a-f5b3b26d243d@l64g2000hse.googlegroups.com> Message-ID: On Jun 3, 10:04?pm, rdab... at gmail.com wrote: > I'm trying to perform following type of operation from inside a python > script. > 1. Open an application shell (basically a tcl ) > 2. Run some commands on that shell and get outputs from each command > 3. Close the shell > > I could do it using communicate if I concatenate all my commands > ( separated by newline ) and read all the output in the end. So > basically I could do following sequence: > 1. command1 \n command2 \n command 3 \n > 2. Read all the output > > But I want to perform it interactively. > 1. command1 > 2. read output > 3. command2 > 4. read output ...... > > Following is my code: > > from subprocess import * > p2 = Popen('qdl_tcl',stdin=PIPE,stdout=PIPE) > o,e = p2.communicate(input='qdl_help \n qdl_read ?\n > qdl_reg_group_list ') > > Please suggest a way to perform it interactively with killing the > process each time I want to communicate with it. > > Thanks in advance, > -Rahul. It sounds like this may help: http://www.noah.org/wiki/Pexpect (pure python expect-like functionality) Ali From johnjsal at gmailNOSPAM.com Sat Jun 28 23:18:30 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sat, 28 Jun 2008 23:18:30 -0400 Subject: How do web templates separate content and logic? In-Reply-To: References: <486510f7$0$3007$c3e8da3@news.astraweb.com> Message-ID: <4866ff46$0$7333$607ed4bc@cv.net> bruno.desthuilliers at gmail.com wrote: > For which definitions of "content" and "logic" ??? > > The point of mvc is to keep domain logic separated from presentation > logic, not to remove logic from presentation (which just couldn't > work). Templating systems are for presentation logic. Whether they > work by embedding an existing complete programmation language or by > providing they're own specialised mini-language (or a mix of both) is > not the point here IMHO. No, I don't mean presentation logic at all. I mean something along the lines of combining HTML (which is what I refer to as "content") and Python (which is what I meant by "logic"). So for example, if you have code like this (and this isn't necessarily proper code, I'm just making this up, but you'll see what I mean):

    Big Important Topic

    This is where I say something important about

      % for topic in topics:
    1. ${topic}
    Humph, I just made up that example to make the point that when you no longer have pure HTML, but instead have programmatic logic (Python) mixed in with the HTML, then you are mixing content and logic. However, as soon as I finished typing it out, it occurred to me that even the so-called logic in this example is really only producing more "content" to display. So maybe my question was a little premature. Or could it just be that this is a *good* way to mix HTML and Python, and there are other ways which may be bad? (For example, connecting to a database, like Sebastian's example. That definitely seems out of place in an HTML file.) From torriem at gmail.com Sun Jun 1 22:36:43 2008 From: torriem at gmail.com (Michael Torrie) Date: Sun, 01 Jun 2008 20:36:43 -0600 Subject: Good grid + calendar, etc.? In-Reply-To: References: <9c80b15f-791e-4933-984b-fd8bf0bafef1@m36g2000hse.googlegroups.com> Message-ID: <48435CBB.8040701@gmail.com> Gilles Ganault wrote: >> The grid can be quite advanced. Did you look at the wxPython demo? Or >> Dabo? > > Yes, but although the basic wigets are just fine, wxGrid looks a bit > like the basic TStringGrid in Delphi, ie. it's pretty basic so that > several vendors came up with enhanced alternatives. But maybe I > haven't played with it long enough. You don't say anything about looking at Dabo. If you are serious about writing real business apps, then you really do need to look at Dabo. While it's GUI objects may not be quite up to what you need, the framework itself is very critical to developing business apps. From your posts in this thread, it sounds to me like Dabo would greatly help you build the back-end database and business logic at least. Despite what you say about web interfaces in business applications, from what I've seen it's all going that way. PeopleSoft, etc. Everything is about web-delivered apps, with web services and custom integration these days. HTML/CSS/Ajax and a bit of Silverlight or Flash for the super custom widgets is actually competing *very* well with the traditional Delphi business widgets. True this requires you to maintain "code" in multiple languages, but frankly that's the cost of doing business. Business apps are *complicated* to build. When it does come down to it, you'll probably have to build some of your own widgets. PyQT makes this quite easy. Canvases, HTML widgets, etc. If you're going to all the work of developing a complete business app, then the work that goes into developing custom GUI components isn't that bad, compared. Since your target audience appears to be windows users, though, I'd second the notion of using IronPython and leveraging SWF .NET widgets. In theory this would run fine under Mono on Unix if you wanted to branch out. From mishok13 at gmail.com Sun Jun 15 06:48:54 2008 From: mishok13 at gmail.com (Andrii V. Mishkovskyi) Date: Sun, 15 Jun 2008 13:48:54 +0300 Subject: bpython - fancy Python shell In-Reply-To: References: Message-ID: <192840a00806150348r7189a8afq9648c93b18264374@mail.gmail.com> 2008/6/15, Bob Farrell : > > I released this a while ago but did some work recently to fix some bugs > so I thought I may as well post it here. To quickly summarise: > In-line syntax highlighting > Auto complete with suggestions as you type > Pastebin stuff, save to file > "Rewind" feature to jump back a line if you mess up (don't ask how it > works, please ;) > > You can get it here: > http://www.noiseforfree.com/bpython/ > > There's info about git repos and what have you there, and apparently > it's also in some real distro repos, but I don't know the details. > > Oh, and you'll need pygments and pyparsing, and it doesn't work on > Windows (heard good reports about it working fine on a Mac though). Great work, bobf. :) I've been using bpython from time to time for a month now, so I can only appreciate the fact that bpython is developing. I think that with that speed of development bpython will substitute ipython as my everyday python console in the near future (3-4 months). P.S. I think you should of cc'd this announcement to python-announce-list. ;) > -- > Bob Farrell > -- > http://mail.python.org/mailman/listinfo/python-list > -- Wbr, Andrii Mishkovskyi. He's got a heart of a little child, and he keeps it in a jar on his desk. From ptmcg at austin.rr.com Tue Jun 3 16:36:49 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 3 Jun 2008 13:36:49 -0700 (PDT) Subject: parser recommendation References: <686de663-94d2-4e8b-b079-197793d0a8cc@2g2000hsn.googlegroups.com> Message-ID: <8d2bb123-9e2b-4947-a93a-5359dbb5b29d@t54g2000hsg.googlegroups.com> On Jun 3, 12:34?pm, "Filipe Fernandes" wrote: > On Tue, Jun 3, 2008 at 10:41 AM, Paul McGuire wrote: > But I do have more questions... when reading the ply.py header (in > 2.5) I found the following paragraph... > > # The current implementation is only somewhat object-oriented. The > # LR parser itself is defined in terms of an object (which allows multiple > # parsers to co-exist). ?However, most of the variables used during table > # construction are defined in terms of global variables. ?Users shouldn't > # notice unless they are trying to define multiple parsers at the same > # time using threads (in which case they should have their head examined). > > Now, I'm invariably going to have to use threads... ?I'm not exactly > sure what the author is alluding to, but my guess is that to overcome > this limitation I need to acquire a thread lock first before > "defining/creating" a parser object before I can use it? > > Has anyone ran into this issue....? ?This would definitely be a > showstopper (for PLY anyway), if I couldn't create multiple parsers > because of threads. ?I'm not saying I need more than one, I'm just not > comfortable with that limitation. > > I have a feeling I'm just misunderstanding since it doesn't seem to > hold you back from creating multiple parsers under a single process. > > filipe You can use pyparsing from any thread, and you can create multiple parsers each running in a separate thread, but you cannot concurrently use one parser from two different threads. Some users work around this by instantiating a separate parser per thread using pickle to quickly construct the parser at thread start time. -- Paul From kretik at yahoo.com Tue Jun 17 00:53:21 2008 From: kretik at yahoo.com (kretik) Date: Mon, 16 Jun 2008 21:53:21 -0700 Subject: string.Template.delimiter cannot be overriden? Message-ID: <4rH5k.2032$to3.1384@newsfe15.phx> I've been trying to coax this class to use something other than the default '$' but it seems setting it to something else has no discernible effect. Is it necessary to inherit from the class to do this? I've only been using Python for a couple of weeks so I'm not sure what the best approach is here. Thanks in advance. From sturlamolden at yahoo.no Wed Jun 4 14:06:33 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 4 Jun 2008 11:06:33 -0700 (PDT) Subject: multiprocessing module (PEP 371) Message-ID: <877a5774-d3cc-49d3-bb64-5cab8505a419@m3g2000hsc.googlegroups.com> I sometimes read python-dev, but never contribute. So I'll post my rant here instead. I completely support adding this module to the standard lib. Get it in as soon as possible, regardless of PEP deadlines or whatever. I don't see pyprocessing as a drop-in replacement for the threading module. Multi-threading and multi-processing code tend to be different, unless something like mutable objects in shared memory is used as well (cf. Python Shared Objects). If this limitation can educate Python programmers to use queues instead of locks and mutable objects, even multi-threaded Python programs may actually benefit. Some API differences between threading and multiprocessing do not matter. Programmers should not consider processes as a drop-in replacement for threads. One limitation not discussed on python-dev is the lack of fork on Win32. This makes the pyprocessing module particularly inefficient at creating processes on this platform, as it depends on serializing (pickling and de-pickling) a lot of Python objects. Even a non-COWfork would be preferred. I will strongly suggest something is done to add support for os.fork to Python on Windows. Either create a full cow fork using ZwCreateProcess (ntdll.dll does support COWforking, but Win32 API does not expose it), or do the same as Cygwin is doing to fork a process without COW. Although a non-cow fork a la Cygwin is not as efficient as a fork on Linux/FreeBSD/Unix, it is still better than what pyprocessing is doing. From alexnbryan at gmail.com Wed Jun 25 19:07:11 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Wed, 25 Jun 2008 18:07:11 -0500 Subject: urllib tutorial and help Message-ID: <9212BFFF-759E-4421-AE87-353E0E9285AC@gmail.com> So I need to start learning about the urllib class, and am wondering where is a good place to start. I really don't want to go buy a book about it, but I was wondering if there is any good online tutorials or anything like that, that will help me out on connecting apps to the web, that specialize in the urllib class. Ideas? From bsagert at gmail.com Wed Jun 18 13:10:17 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Wed, 18 Jun 2008 10:10:17 -0700 (PDT) Subject: Importing module PIL vs beautifulSoup. Message-ID: I downloaded BeautifulSoup.py from http://www.crummy.com/software/BeautifulSoup/ and being a n00bie, I just placed it in my Windows c:\python25\lib\ file. When I type "import beautifulsoup" from the interactive prompt it works like a charm. This seemed too easy in retrospect. Then I downloaded the PIL (Python Imaging Library) module from http://www.pythonware.com/products/pil/. Instead of a simple file that BeautifulSoup sent me, PIL is an .exe that installed itself in c: \python25\lib\site-packages\PIL\. However it won't load by typing "import pil". I know I am supposed to RTFM, but a Google search has not led to the holy grail that Monty Python found. I realize that PIL is a package as opposed to a simple script (and it does not include a readme file). Thanks in advance for any help. From rurpy at yahoo.com Tue Jun 3 20:03:45 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Tue, 3 Jun 2008 17:03:45 -0700 (PDT) Subject: parser recommendation References: <686de663-94d2-4e8b-b079-197793d0a8cc@2g2000hsn.googlegroups.com> <8d2bb123-9e2b-4947-a93a-5359dbb5b29d@t54g2000hsg.googlegroups.com> Message-ID: On Jun 3, 2:55 pm, "Filipe Fernandes" wrote: > I haven't given up on pyparsing, although I'm now heavily leaning > towards PLY as an end solution since lex and yacc parsing is available > on other platforms as well. Keep in mind that PLY's "compatibility" with YACC is functional, not syntactical. That is, you can not take a YACC file, replace the actions with Python actions and feed it to PLY. It's a shame that the Python world has no truly YACC compatible parser like YAPP in the Perl world. From python at rcn.com Tue Jun 17 01:20:23 2008 From: python at rcn.com (Raymond Hettinger) Date: Mon, 16 Jun 2008 22:20:23 -0700 (PDT) Subject: string.Template.delimiter cannot be overriden? References: <4rH5k.2032$to3.1384@newsfe15.phx> Message-ID: <35e212be-e85b-41fd-90c2-f90959053232@l28g2000prd.googlegroups.com> On Jun 16, 9:53?pm, kretik wrote: > I've been trying to coax this class to use something other than the > default '$' but it seems setting it to something else has no discernible > effect. Is it necessary to inherit from the class to do this? Yes, subclassing is the intended way to produce variants of Template with a different delimiter. >>> import string >>> class PercentTemplate(string.Template): delimiter = "%" >>> s = PercentTemplate('Move %piece to %position') >>> s.substitute(piece='pawn', position='K4') 'Move pawn to K4' Raymond From esugreg at gmail.com Sat Jun 7 00:51:12 2008 From: esugreg at gmail.com (gms) Date: Fri, 6 Jun 2008 21:51:12 -0700 (PDT) Subject: Needing python experts to help with a problem Message-ID: Hello, I have the following list: [{'count': u'2', 'manu': }, {'count': u'4', 'manu': }, {'count': u'2', 'manu': }, {'count': u'2', 'manu': }] My current list currently contains four dictionaries. They are: {'count': u'2', 'manu': } {'count': u'4', 'manu': } {'count': u'2', 'manu': } {'count': u'2', 'manu': } I need to create a list for each specific Manufacturer. Since I have two dictionaries that have 'Manu2' as it's manufacturer. I will need some code that will create the following from the list above: [{'count': u'2', 'manu': }] [{'count': u'4', 'manu': },{'count': u'2', 'manu': }] [{'count': u'2', 'manu': }] The reason for this is because I want to send one email to each manufacturer. In this case I would send two emails to Manu2 because I have two dictionaries that have Manu2 as the manufacturer. That is why I need to create a separate list for each manufacturer. Any help on on how best to do this would be greatly appreciated! Thanks From ramb at sonic.net Sat Jun 14 03:50:55 2008 From: ramb at sonic.net (ramb at sonic.net) Date: Sat, 14 Jun 2008 00:50:55 -0700 Subject: ANN: pytoken 1.0 - native 86 machine code scanner generator Message-ID: I am pleased to announce the 1.0 version of pytoken. It is available here: http://code.google.com/p/pytoken/downloads/list What is pytoken Pytoken is a scanner generator. Given an input specification - a bunch of regular expressions - pytoken will generate x86 machine code that recognizes those regular expressions. Pytoken will be most useful for programmers that want to parse complex text files. Pytoken has separate objects for scanners and buffers. Here is a simple example: import pytoken lexer_obj = pytoken.lexer() lexer_obj.add_pattern("a", 1) lexer_obj.add_pattern("b", 2) lexer_obj.compile_to_machine_code() buf = pytoken.lexer_state() buf.set_input("ab") tok = lexer_obj.get_token(buf) assert tok == 1 tok = lexer_obj.get_token(buf) assert tok == 2 Pytoken has been written in a portable fashion - it is designed to support multiple CPU types, even though only the x86 (32 bit) is supported now. -Ram From aahz at pythoncraft.com Wed Jun 25 14:16:40 2008 From: aahz at pythoncraft.com (Aahz) Date: 25 Jun 2008 11:16:40 -0700 Subject: Threads, GIL and re.match() performance References: Message-ID: In article , Mirko Dziadzka wrote: > >I understand that the C implementation of Python use a global interpreter >lock to avoid problems, so doing CPU bound tasks in multiple threads >will not result in better performance on multi-CPU systems. > >However, I assumed that calls to (thread safe) C Library functions >release the global interpreter lock. Generally speaking that only applies to I/O calls. >Today I checked the performance of some slow re.match() calls and found, >that the do not run in parallel on a multi-CPU system. > >1) Is there a reason for this? >2) Is the regex library not thread-safe? >3) Is it possible, to release the GIL in re.match() to > get more performance? Theoretically possible, but the usual rule applies: patches welcome -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From duncan.booth at invalid.invalid Mon Jun 23 11:00:07 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Jun 2008 15:00:07 GMT Subject: -1/2 References: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> <2231475d-c1d6-45de-9ccb-ab82e923e902@x1g2000prh.googlegroups.com> Message-ID: Lie wrote: > On Jun 23, 1:32?am, "Serve Lau" wrote: >> What is the expected result of -1/2 in python? > > > Operator precedence: > Both python 2 and 3 follows the same rule for operator precedence, > see: > http://www.ibiblio.org/g2swap/byteofpython/read/operator-precedence.htm > l . In -1/2, unary negative takes precedence, then division, i.e. it's > interpreted as ((-1) / 2). > > Py3k and Python 2 differences: > Before Python 3, integer division is always rounds to minus infinity. > In Python 3, integer division yields floats. To use integer division > in Python 3, you use // operator. > > Simple answer: > Python 2: (-1)/2 = round(-0.5) = -1 > Py3k: (-1)/2 = float(-1) / float(2) = -0.5 > Python 2.x gives -1 or -0.5 depending on the division mode in operation and for -1 may also generate a deprecation warning: C:\>python25\python -Qnew -c "print -1/2" -0.5 C:\>python25\python -Qwarn -c "print -1/2" -c:1: DeprecationWarning: classic int division -1 -- Duncan Booth http://kupuguy.blogspot.com From gabriel.rossetti at arimaz.com Fri Jun 13 02:33:52 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Fri, 13 Jun 2008 08:33:52 +0200 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: References: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> Message-ID: <485214D0.5010907@arimaz.com> Duncan Booth wrote: > Mike Orr wrote: > > >> That's a misunderstanding of classes vs instances. If you have an >> instance of MyClass(Superclass), there is one instance but several >> classes. The instance is of MyClass; there is no instance of >> Superclass. 'self' has a .__class__ attribute because it's an >> instance, but MyClass and Superclass do not because they're already >> classes. >> > > Classes are also instances, usually they are instances of the type 'type' > (and even 'type' is an instance of itself): > > Ok, I didn't know that >>>> class SuperClass(object): pass >>>> > > >>>> SuperClass.__class__ >>>> > > >>>> type(SuperClass) >>>> > > >>>> type.__class__ >>>> > > > Old style classes don't have a class attribute, but you shouldn't be using > old style classes anyway and so long as you use > type(x) > to access its class rather than accessing the __class__ attribute directly > that doesn't particularly matter. > > Yes, I don't use old style classes From dstromberglists at gmail.com Fri Jun 13 14:20:10 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Fri, 13 Jun 2008 18:20:10 GMT Subject: Python Socket programming References: Message-ID: On Fri, 13 Jun 2008 21:59:06 +0530, srinivasan srinivas wrote: > Hi, > I am going to do some socket related programming in Python. Before that, > I wish to know the Gotchas of Python Scoket Programming. Can anyone send > me any link that satisfies my needs?? Thanks, > Srini > > > Explore your hobbies and interests. Go to > http://in.promos.yahoo.com/groups/ IMO, there aren't many. Some methods require a tuple where you might think they shouldn't need one. And you have to be careful not to make assumptions about, say, writing n bytes in your server and reading n bytes in the client - you may not get all n right away. TCP is free to split or aggregate your chunks as it sees fit. So you need some sort of record terminator or something, rather than assuming transfer sizes will be preserved by TCP. Often they will be preserved, but they aren't guaranteed to be. But this is true of just about any language with a socket interface. For the latter issue (the chunk size thing), I put together http:// stromberg.dnsalias.org/~strombrg/bufsock.html From bruno.42.desthuilliers at websiteburo.invalid Wed Jun 18 03:34:40 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 18 Jun 2008 09:34:40 +0200 Subject: Name lookup inside class definition In-Reply-To: <1c1a1181-905c-4401-ae00-36b3fabebab9@v1g2000pra.googlegroups.com> References: <1c1a1181-905c-4401-ae00-36b3fabebab9@v1g2000pra.googlegroups.com> Message-ID: <4858ba90$0$16043$426a74cc@news.free.fr> WaterWalk a ?crit : > Hello. Consider the following two examples: > class Test1(object): > att1 = 1 > def func(self): > print Test1.att1 // ok or print type(self).att1 > class Test2(object): > att1 = 1 > att2 = Test2.att1 // NameError: Name Test2 is not defined > > It seems a little strange. Why a class name can be used in a method > while cannot be used in the class block itself? class is an executable statement. The whole "class" block is first eval'd, then the class object is created and bound to it's name. So when the function is called, the class statement has already been executed, the class object created and bound to the name Test1. But when the att2=Test2.att1 is executed, the class object doesn't yet exists, nor the name Test2. Anyway, you don't need to refer to the class name here: class Toto(object): titi = 1 toto = titi + 1 From gert.cuykens at gmail.com Sat Jun 28 22:08:59 2008 From: gert.cuykens at gmail.com (gert) Date: Sat, 28 Jun 2008 19:08:59 -0700 (PDT) Subject: pxssh submit su commands = very very slow References: <39f89067-8ee6-470a-92ce-77b46a344f37@34g2000hsf.googlegroups.com> Message-ID: <48196ce2-42bd-437f-b914-c0e68e0097d3@y21g2000hsf.googlegroups.com> this does the same except 100 times faster ? I don't understand the logic about the prompt, its not the same as the output from the bash shell ? root at r12276:~# cat ssh2.py import pexpect import sys child = pexpect.spawn("ssh gert at 127.0.0.1") #child.logfile = sys.stdout i = child.expect(['assword:', r'yes/no'],timeout=120) if i==0: child.sendline('123') elif i==1: child.sendline('yes') child.expect('assword:', timeout=120) child.sendline('123') child.expect('gert at rxxxx.ovh.net: ~') print child.before child.sendline('ls -l') child.expect('gert at rxxxx.ovh.net:') print child.before child.sendline('su') child.expect('assword:') child.sendline('123') child.expect('gert at rxxxx.ovh.net: /srv/www/gert') print child.before child.sendline('ls -l') child.expect('root at rxxxx.ovh.net:') print child.before From Lie.1296 at gmail.com Wed Jun 18 15:57:44 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 18 Jun 2008 12:57:44 -0700 (PDT) Subject: python string comparison oddity References: Message-ID: <3ebd170e-8686-4bb4-9e47-0fba2179feb3@p39g2000prm.googlegroups.com> On Jun 19, 2:26?am, Faheem Mitha wrote: > Hi everybody, > > I was wondering if anyone can explain this. My understanding is that 'is' > checks if the object is the same. However, in that case, why this > inconsistency for short strings? I would expect a 'False' for all three > comparisons. This is reproducible across two different machines, so it is > not just a local quirk. I'm running Debian etch with Python 2.4.4 (the > default). > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Thanks, Faheem. > > In [1]: a = '--' > > In [2]: a is '--' > Out[2]: False > > In [4]: a = '-' > > In [5]: a is '-' > Out[5]: True > > In [6]: a = 'foo' > > In [7]: a is 'foo' > Out[7]: True Yes, this happens because of small objects caching. When small integers or short strings are created, there are possibility that they might refer to the same objects behind-the-scene. Don't rely on this behavior. From geonomica at gmail.com Sat Jun 14 11:39:47 2008 From: geonomica at gmail.com (gianluca) Date: Sat, 14 Jun 2008 08:39:47 -0700 (PDT) Subject: #define in swig Message-ID: <61886d78-f769-48d8-94f5-5a7d010a879b@56g2000hsm.googlegroups.com> I've a problem with python wrapper of C library. In a library's file there are #define istruction but I can't access it from python. Other functio works correctly. The define istruction is like this: #define START_OF_D _table_element=_mainsys- >matD,_table_end=_table_element+Dsize(_mainsys) #define START_OF_X _table_element=_mainsys- >matX,_table_end=_table_element+_mainsys->matXsize #define START_OF_MAT(set,num) _table_element=(set),_table_end=_table_element+(num)*_mainsys- >setAsize #define END_OF_MAT (_table_element<_table_end) #define NEXT_OF_MAT _table_element+=_mainsys->setAsize #define ELEM_OF_MAT _table_element #define ElemOfRule(rules,num,attr) (rules)[(num)*(_mainsys- >attributes_num)+(attr)] thanks Gianluca From ironfroggy at socialserve.com Sun Jun 15 13:20:38 2008 From: ironfroggy at socialserve.com (Calvin Spealman) Date: Sun, 15 Jun 2008 13:20:38 -0400 Subject: Iterate creating variables? In-Reply-To: <6b671d56-1060-4fd4-86ca-b36a1e4c936f@m44g2000hsc.googlegroups.com> References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> <6b671d56-1060-4fd4-86ca-b36a1e4c936f@m44g2000hsc.googlegroups.com> Message-ID: That smells bad the same was the eval() usage in the thread "Hard to understand 'eval'". This is only one pythoners opinion, of course. On Jun 13, 2008, at 3:29 PM, Jason Scheirer wrote: > for x in xrange(1, 26): > setattr(self, 'checkbox_%i' % x, ...) > -- > http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Thu Jun 26 19:27:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 26 Jun 2008 16:27:35 -0700 (PDT) Subject: Need help capturing output of re.search References: <771ef68a-d976-4f61-a3cc-7ed56fddc756@k37g2000hsf.googlegroups.com> Message-ID: <9757288e-0b48-46ee-8fd0-0adf36bbd710@p39g2000prm.googlegroups.com> On Jun 27, 8:31 am, joemacbusin... at yahoo.com wrote: > Hi - > > I need help capturing the output of a RegEx search. > I dont understand why this conditional fails. > > Here is the code: > > #================================= start snip > ====================================== > #!/usr/local/bin/python > > import os > import re > > dirName = '/home/user/bin/logs' > os.chdir(dirName) > files = os.listdir(dirName) > for myFile in files: > # print 'checking ...', myFile > reCheck = '' > reCheck = re.search(r'\bCC_', myFile) > # print 'reCheck = ', '=', reCheck, '=' > > if reCheck == "None": > print myFile, ' ..... does not qualify' > else: > print ' ', myFile, 'qualifies...', reCheck > > #================================= end snip > ====================================== > > The problem is that reCheck never == None. > So all of the files "qualify". My understanding of the > re.search (re.search(r'\bCC_', myFile)) is ... > 1) give me only files that start with a word boundary (\b) > 2) followed by a (CC_) > 3) in myFile > > Why doesn't the output of the re.search load reCheck with valid data? > (like "None") Because "None" is not "valid data" in this case. re.search returns None or a MatchObject instance. >>> type(None) >>> type("None") >>> None == "None" False >>> You may like to read this: http://www.amk.ca/python/howto/regex/ If you want to check for strings that start with some condition, you need re.match, not re.search. You don't need the '\b'; re.match(r'CC_', filename) would do the job. But then so would filename.startswith('CC_') HTH, John From larry.bates at websafe.com` Thu Jun 5 08:06:52 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 05 Jun 2008 07:06:52 -0500 Subject: line continuation for lines ending in "and" or "or" In-Reply-To: References: <90ee8b5d-1509-4463-aaab-f712f7e72d4b@j33g2000pri.googlegroups.com> <0d723e6d-f81b-4545-b406-fc60b20c5433@u6g2000prc.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: > On Wed, 4 Jun 2008 21:50:19 -0700 (PDT), "Russ P." > declaimed the following in comp.lang.python: > >> Darnit! You're right. I've been reading up on Scala lately, and I >> guess I got confused. Well, it wouldn't be a bad idea for Python to do >> what I thought it did, *plus* what I said it ought to do. >> > Is it that much of a difficulty to start multiline expresssions with > a (... > > That already covers all the conditions you want... Or just using a > line ending of \ > (which I find less appealing than the (... ) I suppose this is a matter of "taste". I find using parenthesis to trigger line continuations undesirable. Lines ending in backslash are explicit and easy to mentally parse. -Larry From andrei.avk at gmail.com Mon Jun 9 20:53:58 2008 From: andrei.avk at gmail.com (Rainy) Date: Mon, 9 Jun 2008 17:53:58 -0700 (PDT) Subject: Separators inside a var name References: Message-ID: On Jun 9, 5:34?pm, Alexander Schmolck wrote: > Rainy writes: > > I have a stylistic question. In most languages words in var. name are > > separated by underscores or cap letters, resulting in var names like > > var_name, VarName and varName. I don't like that very much because all > > 3 ways of naming look bad and/or hard to type. From what I understand, > > scheme can have variables like var-name. I'm curious about reasons > > that python chose to disallow this. > > Legacy -- mathematical notation is broken and conflates negation and > subtraction (causing all sorts of annoyances including this one). Thus if you > want to be able to name a variable ``a-b`` you either have to write ``a - b`` > to disambiguate subtracton from the variable name ``a-b`` or you need to chose > a different symbol for subtraction (writing "a ~ b" would likely be the best > choice). ~ is terrible, imho, I'd much rather disallow a - b for subtraction (and all math ops). > > > Another question I have is what other languages allow this naming scheme? > > All lisps. Dylan. Rebol. Postscript. Forth. I'm sure there are a few others. > > > Were there any languages that allowed space as a separator? > > Sure. > > > What would be a practical way to separate variables from keywords in that > > case? > > Lisp allows you to use pretty much anything in a variable name, you just have > to quote it, either > > ?like\ this > > or > > ?|like this| This is actually pretty nice. I think I like this much better than C/Java/etc convention. I wouldn't use pipes but I'd pick something that's easy to type and is nicely readable. Not sure what.. > > > "some long variable name", 'just a string', or maybe using 2 spaces: one var > > + other var + third var ? I think being able to easy have very long names > > for vars that are easy to type would be a fairly significant advantage. > > I assume you haven't programmed too much? The problem with long names is that > they obscure structure, so they are only worthwhile for rarely used and fairly > obscure concepts where the added descriptiveness yields a net advantage. Only about 8 years, but it may be that I'm just not very good ;-). I'm not sure that's the case. My problem with long names is that they look ugly, and the longer they are, the uglier they look when you use underscores or caps. Other than that, I'd like to have an option to use longer names. Maybe it won't be used all the time, but still.. > > > I know I'm probably being too obsessive about this, but that didn't stop me > > from posting. Comments? > > I think you're right -- the common naming convention's suck and "python's" is > particularly bad (HtmlFrob HTMLFrob htmlFrob html_frob htmlfrob HTML_FROB > HTMLFROB -- which one will it be? No way to know without looking at the rest > of the code, the only consistency is that the last two are mostly used for > constants; everything else is completely up for grabs). You'd better get used > to it though, it's become "standardized". > > 'as Well, I agree, this is terrible. If I were Guido I'd make a very explicit rule that a certain naming scheme is preferred and other schemes are very bad. And I'd get it in the beginning of official tutorial, libref, in books, etc. Mostly it's ClassName and func_name and var_name and so on, but very often it's something else. BUT even if that was the rule and everyone followed it, though it would be much better than what we have now, it would still offend my taste. Just saying! From noreply at yahoo.com Mon Jun 30 10:45:18 2008 From: noreply at yahoo.com (Kirk) Date: 30 Jun 2008 14:45:18 GMT Subject: Freeze problem with Regular Expression References: <6cf614F3f8ocoU1@mid.individual.net> <0e1a9726-cc1d-4bd2-b0ba-b2bcc1c27ee8@f24g2000prh.googlegroups.com> Message-ID: <6cs9rtF3g9fsvU1@mid.individual.net> On Wed, 25 Jun 2008 15:29:38 -0700, John Machin wrote: > Several problems: Ciao John (and All partecipating in this thread), first of all I'm sorry for the delay but I was out for business. > (1) lose the vertical bars (as advised by others) (2) ALWAYS use a raw > string for regexes; your \s* will match on lower- case 's', not on > spaces right! thanks! > (3) why are you using findall on a pattern that ends in "$"? Yes, you are right, I started with a different need and then it changed over time... > (6) as remarked by others, you haven't said what you are trying to do; I reply here to all of you about such point: that's not important, although I appreciate very much your suggestions! My point was 'something that works in Perl, has problems in Python'. In respect to this, I thank Peter for his analysis. Probably Perl has a different pattern matching algorithm. Thanks again to all of you! Bye! -- Kirk From larry.bates at websafe.com` Mon Jun 30 19:21:10 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 30 Jun 2008 18:21:10 -0500 Subject: The Yield statement In-Reply-To: References: Message-ID: Alex Bryan wrote: > Okay, so i don't really understand the Yield thing and i know it is > useful. I've read a few things about it but it is all programming jargon > and so basically it is hard for me to understand. So can anyone give me > a description or link me to a site that has a good definition and/or > examples of it? If you could I would really appreciate it. Use yield when you want the function to act as a generator. That is each time it is called it generates a response and returns it, but leaves its state intact so that the next time you call it, it can pick up where it left off and continue on. Best example I ever saw is the code that implements os.walk() function: def walk(top, topdown=True, onerror=None): """ Example: from os.path import join, getsize for root, dirs, files in walk('python/Lib/email'): print root, "consumes", print sum([getsize(join(root, name)) for name in files]), print "bytes in", len(files), "non-directory files" if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories """ from os.path import join, isdir, islink try: names = listdir(top) except error, err: if onerror is not None: onerror(err) return dirs, nondirs = [], [] for name in names: if isdir(join(top, name)): dirs.append(name) else: nondirs.append(name) if topdown: yield top, dirs, nondirs for name in dirs: path = join(top, name) if not islink(path): for x in walk(path, topdown, onerror): yield x if not topdown: yield top, dirs, nondirs Actually this code uses yield and is recursive. Pretty neat. -Larry From gherron at islandtraining.com Wed Jun 18 02:35:32 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 17 Jun 2008 23:35:32 -0700 Subject: Ternary operator alternative in Ptyhon In-Reply-To: References: Message-ID: <4858ACB4.70109@islandtraining.com> kretik wrote: > I'm sure this is a popular one, but after Googling for a while I > couldn't figure out how to pull this off. > > Let's say I have this initializer on a class: > > def __init__(self, **params): > > I'd like to short-circuit the assignment of class field values passed > in this dictionary to something like this: > > self.SomeField = \ > params.has_key("mykey") ? params["mykey"] : None) For years, Python did not have such a thing, but recent versions support the syntax a if c else b In spite of the odd ordering of that parts, they are executed (or not) just as you like. self.SomeField = params["mykey"] if params.has_key("mykey") else None Gary Herron > > Obviously I know this is not actual Python syntax, but what would be > the equivalent? I'm trying to avoid this, basically: > > if params.has_key("mykey"): > self.SomeField = params["mykey"] > else: > self.SomeField = None > > This is not a big deal of course, but I guess my main goal is to try > and figure out of I'm not missing something more esoteric in the > language that lets me do this. > > Thanks in advance. > -- > http://mail.python.org/mailman/listinfo/python-list From martin at v.loewis.de Thu Jun 19 15:40:03 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 19 Jun 2008 21:40:03 +0200 Subject: Python-3.0b1 build fails on Linux : _gestalt In-Reply-To: <6bupftF3d2d0kU1@mid.dfncis.de> References: <6bupftF3d2d0kU1@mid.dfncis.de> Message-ID: <485ab613$0$31976$9b622d9e@news.freenet.de> > Failed to find the necessary bits to build these modules: > _gestalt > > Looking at setup.py it seems that module '_gestalt' > is only needed on Darwin but my build on Linux fails > nevertheless. Why do you think the build fails (i.e. what specific error message makes you believe it failed)? Regards, Martin From carsten.haese at gmail.com Wed Jun 11 08:40:28 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Wed, 11 Jun 2008 08:40:28 -0400 Subject: problems with opening files due to file's path In-Reply-To: References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> Message-ID: <1JP3k.6889$jI5.5927@flpi148.ffdc.sbc.com> Alexnb wrote: > I don't think you understand it doesn't matter how the variable gets there But it *does* matter. Compare this: py> filename = "C:\Somewhere\01 - Some Song.mp3" py> print filename C:\Somewhere - Some Song.mp3 To this: py> filename = raw_input("Enter the filename: ") Enter the filename: C:\Somewhere\01 - Some Song.mp3 py> print filename C:\Somewhere\01 - Some Song.mp3 Note that the "\01" in the first case seems to have disappeared, whereas in the second case it's preserved. Now, if you want us to help you, please post your ACTUAL code with a description of the ACTUAL problem. -- Carsten Haese http://informixdb.sourceforge.net From duncan.booth at invalid.invalid Thu Jun 19 09:09:47 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Jun 2008 13:09:47 GMT Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <1ea1731d-9de9-4e73-9c08-e9f5572b9fd6@t54g2000hsg.googlegroups.com> <1a8797c6-a165-49b1-82de-94a6054cf856@z16g2000prn.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > My memory value comes from experiments, I have created a little > program like this: > > from memory import memory > > def main(N): > m1 = memory() > print m1 > > d = {} > for i in xrange(N): > d[i] = None > > m2 = memory() > print m2 > print float((m2 - m1) * 1024) / N > main(20000000) > > Where memory is a small module of mine that calls a little known > program that tells how much memory is used by the current Python > process. The results for that run n=20000000 are (first two numbers > are kilobytes, the third number is byte/pair): > > 1876 > 633932 > 32.3612672 > > It means to store 20_000_000 pairs it requires about 647_000_000 > bytes, Python 2.5.2, on Win. > What do you get if you change the output to exclude the integers from the memory calculation so you are only looking at the dictionary elements themselves? e.g. def main(N): keys = range(N) m1 = memory() print m1 d = {} for i in keys: d[i] = None m2 = memory() print m2 print float((m2 - m1) * 1024) / N main(20000000) -- Duncan Booth http://kupuguy.blogspot.com From cokofreedom at gmail.com Mon Jun 30 05:48:47 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 30 Jun 2008 02:48:47 -0700 (PDT) Subject: Why is recursion so slow? References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> <5504f9ac0806290703h1bf44639jbfe5331c4a2d1369@mail.gmail.com> Message-ID: <5dbba5c9-1855-47cc-979e-a55750bb88f7@a70g2000hsh.googlegroups.com> In case anyone is interested... # Retrieved from: http://en.literateprograms.org/Fibonacci_numbers_(Python)?oldid=10746 # Recursion with memoization memo = {0:0, 1:1} def fib(n): if not n in memo: memo[n] = fib(n-1) + fib(n-2) return memo[n] # Quick exact computation of large individual Fibonacci numbers def powLF(n): if n == 1: return (1, 1) L, F = powLF(n/2) L, F = (L**2 + 5*F**2) >> 1, L*F if n & 1: return ((L + 5*F)>>1, (L + F) >>1) else: return (L, F) def fib(n): return powLF(n)[1] From fanweixiao at gmail.com Sat Jun 28 15:46:25 2008 From: fanweixiao at gmail.com (weixiao.fan) Date: Sat, 28 Jun 2008 12:46:25 -0700 (PDT) Subject: how to upgrade python on centOS 5.2 Message-ID: <7456ecc5-0620-4b6a-929e-5db7dcd60555@u36g2000prf.googlegroups.com> CentOS5.2 installed python2.4 by default, but google app engine need 2.5+ version. I download the tar package from python.org then run ./ configure,make,make install and some other work. but I can't use it in gae with exceptions like can't use import time ... Is there a detailed guide on how to upgrade python to 2.5+ version on centos 5.2? thank you. From fake.mail at noone.be Sun Jun 22 05:44:13 2008 From: fake.mail at noone.be (Josip) Date: Sun, 22 Jun 2008 11:44:13 +0200 Subject: Storing value with limits in object Message-ID: I'm trying to limit a value stored by object (either int or float): class Limited(object): def __init__(self, value, min, max): self.min, self.max = min, max self.n = value def set_n(self,value): if value < self.min: # boundary check self.n = self.min if value > self.max: self.n = self.max else: self.n = value n = property(lambda self : self._value, set_n) This works, except I would like the class to behave like built-in types, so I can use it like this: a = Limited(7, 0, 10) b = math.sin(a) So that object itself returns it's value (which is stored in a.n). Is this possible? From bearophileHUGS at lycos.com Thu Jun 12 07:35:48 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 12 Jun 2008 04:35:48 -0700 (PDT) Subject: get keys with the same values References: Message-ID: Nader: > d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} > I will something as : > d.keys(where their values are the same) That's magic. > With this statement I can get two lists for this example: > l1= ['a','e'] > l2=['b','d'] > Would somebody tell me how I can do it? You can create a new dict where the keys are the values of the input dict and the values are a list of the keys of the original dict. So scanning the keys, values of the input dict, you can fill the second dict. Then you can scan the second dict, and create a list that contains only value lists longer than one. Bye, bearophile From thermostat at gmail.com Fri Jun 27 15:30:17 2008 From: thermostat at gmail.com (Dan) Date: Fri, 27 Jun 2008 12:30:17 -0700 (PDT) Subject: ask for a RE pattern to match TABLE in html References: <6a4f17690806260653i136681bdsabe0f6bb1dfab67b@mail.gmail.com> <62f752f3-d840-42de-a414-0d56d15d7c5a@w4g2000prd.googlegroups.com> Message-ID: <50285840-7601-41be-aa3d-865f46fe85c6@56g2000hsm.googlegroups.com> On Jun 27, 1:32 pm, "David C. Ullrich" wrote: > In article > <62f752f3-d840-42de-a414-0d56d15d7... at w4g2000prd.googlegroups.com>, > Jonathan Gardner wrote: > > > On Jun 26, 3:22 pm, MRAB wrote: > > > Try something like: > > > > re.compile(r'.*?', re.DOTALL) > > > So you would pick up strings like "
    foo > td>
    "? I doubt that is what oyster wants. > > I asked a question recently - nobody answered, I think > because they assumed it was just a rhetorical question: > > (i) It's true, isn't it, that it's impossible for the > formal CS notion of "regular expression" to correctly > parse nested open/close delimiters? Yes. For the proof, you want to look at the pumping lemma found in your favorite Theory of Computation textbook. > > (ii) The regexes in languages like Python and Perl include > features that are not part of the formal CS notion of > "regular expression". Do they include something that > does allow parsing nested delimiters properly? So, I think most of the extensions fall into syntactic sugar (certainly all the character classes \b \s \w, etc). The ability to look at input without consuming it is more than syntactic sugar, but my intuition is that it could be pretty easily modeled by a nondeterministic finite state machine, which is of equivalent power to REs. The only thing I can really think of that is completely non- regular is the \1 \2, etc syntax to match previously match strings exactly. But since you can't to an arbitrary number of them, I don't think its actually context free. (I'm not prepared to give a proof either way). Needless to say that even if you could, it would be highly impractical to match parentheses using those. So, yeah, to match arbitrary nested delimiters, you need a real context free parser. > > -- > David C. Ullrich -Dan From paul at boddie.org.uk Thu Jun 5 17:13:07 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 5 Jun 2008 14:13:07 -0700 (PDT) Subject: line continuation for lines ending in "and" or "or" References: <90ee8b5d-1509-4463-aaab-f712f7e72d4b@j33g2000pri.googlegroups.com> <0d723e6d-f81b-4545-b406-fc60b20c5433@u6g2000prc.googlegroups.com> Message-ID: <198c0b6a-65b3-437c-bcb0-ff58985f8ee7@l42g2000hsc.googlegroups.com> On 5 Jun, 22:40, "Terry Reedy" wrote: > > A line ending in an operator is ambiguous in that it *could* indicate that > the programmer intends to continue on the next line while it also could > indicate that the programmer forgot to finish before hitting return, or > that something got erased but not replaced. Yes, this is an excellent point. For the logical operators, consider code like the following... x = obj1.something() and obj2.conditional() and # time for lunch! obj4.obligatory_something() Although a trailing "and" or "or" operator might suggest a continuation of the expression on the next line, one has to consider whether the next line (or almost any line defining an expression) should suggest possible membership of an expression on the preceding line by default for its contents. One could, of course, insist on indentation to prevent such ambiguity since the second line above shouldn't be indented further if part of a separate statement. More work is definitely needed on such a proposal, certainly. Paul From michalis.avraam at gmail.com Fri Jun 20 12:45:25 2008 From: michalis.avraam at gmail.com (michalis.avraam at gmail.com) Date: Fri, 20 Jun 2008 09:45:25 -0700 (PDT) Subject: Python "is" behavior References: <02d58c63-f8d8-44a8-ac09-d483a0fa8c0f@v1g2000pra.googlegroups.com> <725bcf7a-3d6a-4a38-a906-bb397bdd447f@26g2000hsk.googlegroups.com> Message-ID: <03a030b7-1d47-4386-9826-435ce936c130@p39g2000prm.googlegroups.com> On Jun 20, 9:42?am, George Sakkis wrote: > On Jun 20, 12:31 pm, michalis.avr... at gmail.com wrote: > > > > > I am not certain why this is the case, but... > > > >>> a = 256 > > >>> b = 256 > > >>> a is b > > > True > > > >>> a = 257 > > >>> b = 257 > > >>> a is b > > > False > > > Can anyone explain this further? Why does it happen? 8-bit integer > > differences? > > No, implementation-dependent optimization (caching). For all we know, > the next python version may cache up to 1024 or it may turn off > caching completely; do not rely on it. More generally, do not use 'is' > when you really mean '=='. > > George Thank you George. I am very curious about some of these internal Python things that I keep stumbling upon through friends. And thank you for all the help! From dp_pearce at hotmail.com Thu Jun 19 06:25:02 2008 From: dp_pearce at hotmail.com (dp_pearce) Date: Thu, 19 Jun 2008 03:25:02 -0700 (PDT) Subject: Simple wxPython SetLabel question References: <005654a8-3406-4063-8e06-d7cf567b96d6@z66g2000hsc.googlegroups.com> Message-ID: Thank you very much C?dric. I thought it would be something very straight forward. From n.emami at gmail.com Mon Jun 9 09:47:40 2008 From: n.emami at gmail.com (Nader) Date: Mon, 9 Jun 2008 06:47:40 -0700 (PDT) Subject: lists to save in a tuple References: <130e261e-1e1a-4657-b8db-8a7704fb083d@z66g2000hsc.googlegroups.com> <6b4psbF35e8fgU1@mid.uni-berlin.de> Message-ID: <2d6b3e13-70c5-491d-ba07-3f8f36f28adc@e39g2000hsf.googlegroups.com> On Jun 9, 3:34 pm, "Diez B. Roggisch" wrote: > Nader wrote: > > Hello, > > > I have two lists and would save them in a tuple. > > > a = [1,2,3] > > b = ['a','b','c'] > > > with the next statement I can do that: > > > t = [(x,y), for x in a for y in b] > > > This gives the next list: > > > [(1,'a'),(1,'b'),(1,'c'), (2,'a'),(2,'b'),(2,'c'), (3,'a'),(3,'b'), > > (3,'c')] > > > But I want the next list: > > > [(1,'a'),(2,'b'),(3,'c')] > > > Would somebody tell me how I can solve this problem? > > zip(a, b) > > Diez Thank you! From gabriel.rossetti at arimaz.com Thu Jun 12 02:54:30 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Thu, 12 Jun 2008 08:54:30 +0200 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: <48494d73$0$31857$426a74cc@news.free.fr> References: <48494d73$0$31857$426a74cc@news.free.fr> Message-ID: <4850C826.7030108@arimaz.com> Bruno Desthuilliers wrote: > Gabriel Rossetti a ?crit : >> Larry Bates wrote: >>> Gabriel Rossetti wrote: >>>> Hello everyone, >>>> >>>> I had read somewhere that it is preferred to use >>>> self.__class__.attribute over ClassName.attribute to access class >>>> (aka static) attributes. I had done this and it seamed to work, >>>> until I subclassed a class using this technique and from there on >>>> things started screwing up. I finally tracked it down to >>>> self.__class__.attribute! What was happening is that the child >>>> classes each over-rode the class attribute at their level, and the >>>> parent's was never set, so while I was thinking that I had indeed a >>>> class attribute set in the parent, it was the child's that was set, >>>> and every child had it's own instance! Since it was a locking >>>> mechanism, lots of fun to debug... So, I suggest never using >>>> self.__class__.attribute, unless you don't mind it's children >>>> overriding it, but if you want a truly top-level class attribute, >>>> use ClassName.attribute everywhere! >>>> >>>> I wish books and tutorials mentioned this explicitly.... >>>> >>>> Gabriel >>> >>> If you define a class instance variable with the same name as the >>> class attribute, how would Python be able to distinguish the two? >>> That is a feature not a problem. Getter looks for instance >>> attribute, if one is not found it looks for a class attribute, and >>> upwards. This behavior is used by Zope to do all sorts of neat stuff. >>> >>> -Larry Bates >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >> A class instance variable, you must mean an instance attribute no? > > I think that's what he meant, yes. Ok. > >> If that is so, then with just self.attribute? Maybe there is a >> concept that I don't know about, > > The concept of name resolution (aka lookup) rules in Python, perhaps ? > When you do obj.attribute, attribute is first looked for in the > object, then in it's class, then in the parent classes. So yes, you > can get a class (or parent class) attribute directly on the instance. > Note that assignment on the instance (obj.attribute = value) will > alway (computed attributes or other hooks excepted) create the > attribute on the target, so if you have Class.attribute set, and then > do obj = Class(); obj.attribute = 42, then obj.attribute will shadow > Class.attribute. > Not really, see my answer to Mike Orr's msg. >> I've studied class/static attributes and instance attributes in my >> OOP classes. > > Forget about your OOP classes, mostly if it was in fact a Java or C++ > class. Python's object model is very far away from what most courses > present as "OOP". > Ok, in some ways yes. >> Gabriel > -- > http://mail.python.org/mailman/listinfo/python-list > > From mensanator at aol.com Mon Jun 23 13:47:57 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 23 Jun 2008 10:47:57 -0700 (PDT) Subject: Question: How do I format printing in python References: Message-ID: <2e43cbba-bcd1-492e-97aa-bf8d2708d665@26g2000hsk.googlegroups.com> On Jun 23, 12:12?pm, joemacbusin... at yahoo.com wrote: > Hi All, > > How do I format printed data in python? > I could not find this in the Python Reference Manual:http://docs.python.org/ref/print.html > Nor could I find it in Matloff's great tutorial:http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf > > For example, how do I turn this: > > 512 Jun 5 2004 X11r6 > 22 Jan 17 2005 a2p > 22 Jan 17 2005 acctcom > 5374 Sep 15 2002 acledit > 5664 May 13 2004 aclget > 12020 May 13 2004 aclput > 115734 Jun 2 2004 adb > 46518 Jun 4 2004 admin > 66750 Sep 16 2002 ali > 1453 Sep 15 2002 alias > 28150 Jun 4 2004 alog > 15 May 12 2005 alstat > > into this: > > 512 ? ? ? ?Jun ? 5 ? 2004 ? ?X11r6 > 22 ? ? ? ? Jan ? 17 ?2005 ? ?a2p > 22 ? ? ? ? Jan ? 17 ?2005 ? ?acctcom > 5374 ? ? ? Sep ? 15 ?2002 ? ?acledit > 5664 ? ? ? May ? 13 ?2004 ? ?aclget > 12020 ? ? ?May ? 13 ?2004 ? ?aclput > 115734 ? ? Jun ? 2 ? 2004 ? ?adb > 46518 ? ? ?Jun ? 4 ? 2004 ? ?admin > 66750 ? ? ?Sep ? 16 ?2002 ? ?ali > 1453 ? ? ? Sep ? 15 ?2002 ? ?alias > 28150 ? ? ?Jun ? 4 ? 2004 ? ?alog > 15 ? ? ? ? May ? 12 ?2005 ? ?alstat > > Thank you You could do this: data = ['512 Jun 5 2004 X11r6 ', \ '22 Jan 17 2005 a2p', \ '22 Jan 17 2005 acctcom ', \ '5374 Sep 15 2002 acledit ', \ '5664 May 13 2004 aclget ', \ '12020 May 13 2004 aclput ', \ '115734 Jun 2 2004 adb ', \ '46518 Jun 4 2004 admin ', \ '66750 Sep 16 2002 ali ', \ '1453 Sep 15 2002 alias ', \ '28150 Jun 4 2004 alog ', \ '15 May 12 2005 alstat '] for i in data: d = i.split() print d[0].ljust(9), print d[1].ljust(6), print d[2].ljust(4), print d[3].ljust(7), print d[4].ljust(9) which gives you 512 Jun 5 2004 X11r6 22 Jan 17 2005 a2p 22 Jan 17 2005 acctcom 5374 Sep 15 2002 acledit 5664 May 13 2004 aclget 12020 May 13 2004 aclput 115734 Jun 2 2004 adb 46518 Jun 4 2004 admin 66750 Sep 16 2002 ali 1453 Sep 15 2002 alias 28150 Jun 4 2004 alog 15 May 12 2005 alstat or perhaps this: for i in data: d = i.split() print d[0].rjust(9), print d[1].ljust(6), print d[2].zfill(2).ljust(4), print d[3].ljust(7), print d[4].ljust(9) which gives this (if you want the digits in the numbers to line up): 512 Jun 05 2004 X11r6 22 Jan 17 2005 a2p 22 Jan 17 2005 acctcom 5374 Sep 15 2002 acledit 5664 May 13 2004 aclget 12020 May 13 2004 aclput 115734 Jun 02 2004 adb 46518 Jun 04 2004 admin 66750 Sep 16 2002 ali 1453 Sep 15 2002 alias 28150 Jun 04 2004 alog 15 May 12 2005 alstat From bsagert at gmail.com Wed Jun 11 00:33:50 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Tue, 10 Jun 2008 21:33:50 -0700 (PDT) Subject: Thanks for help re: %userprofile% Message-ID: <5e9eff4c-8a0e-48e1-9a53-cb0a8d4624e5@p39g2000prm.googlegroups.com> The python community is very helpful to newbies like me. I did however manage to solve my problem in the meantime. I needed the modification time of certain files on various computers, but I didn't know the usernames ahead of time, so I used windows %userprofile% method. Python likes forward slashes in file names, whereas windows likes back slashes. Here is my script. import os, re u = os.getenv("USERPROFILE") # python returns "c:\\documents and Settings\\user" # note the escaped backslashes which windows hates. # let's repair that with re.sub u = re.sub( r"\\", "/", u) f = u+"/dir1/file1" mod = os.path.getmtime(f) # success, now do something c = "copy '%userprofile%\dir1\file1' c:\dir2\file2" # note back slashes here which windows tolerates. # In the os.system context, python delivers unescaped slashes. os.system(c) # success I'm a retired old fart trying to learn python so I welcome criticism and advice. My original post was at http://groups.google.ca/group/comp.lang.python/browse_thread/thread/59cc71e92bef1ee2?hl=en# From johnjsal at NOSPAMgmail.com Mon Jun 23 14:37:36 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 23 Jun 2008 14:37:36 -0400 Subject: Using Python to run SSH commands on a remote server References: <03a078c8$0$3229$c3e8da3@news.astraweb.com> <86adnQ8H4MFYdcLVnZ2dnUVZ_sHinZ2d@cablespeedwa.com> Message-ID: <03a08853$0$3220$c3e8da3@news.astraweb.com> "Jeffrey Froman" wrote in message news:86adnQ8H4MFYdcLVnZ2dnUVZ_sHinZ2d at cablespeedwa.com... > Be careful, this procedure sounds potential risky, security-wise ;-) I guess a blanket process might be a tad risky, but don't you want all CGI files to be executable by all? From omer at no-log.org Fri Jun 13 12:46:46 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Fri, 13 Jun 2008 18:46:46 +0200 Subject: Python Socket programming In-Reply-To: <655455.29695.qm@web7907.mail.in.yahoo.com> References: <655455.29695.qm@web7907.mail.in.yahoo.com> Message-ID: <200806131846.46807.omer@no-log.org> Hi, Le Friday 13 June 2008 18:29:06 srinivasan srinivas, vous avez ?crit?: > Hi, > I am going to do some socket related programming in Python. Before that, I > wish to know the Gotchas of Python Scoket Programming. Can anyone send me > any link that satisfies my needs?? Yes, the friendly manual :) http://docs.python.org/lib/module-socket.html and if you want to know more about socket themselves, the gnu libc info page is a good starting point as the python module is basically an interface to it: http://www.gnu.org/software/libc/manual/html_node/Sockets.html#Sockets -- C?dric Lucantis From gh at ghaering.de Fri Jun 13 09:31:50 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 13 Jun 2008 15:31:50 +0200 Subject: Summing a 2D list In-Reply-To: <740c3aec0806130558i2b02594dq5a6f3daf39c214a5@mail.gmail.com> References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <740c3aec0806130558i2b02594dq5a6f3daf39c214a5@mail.gmail.com> Message-ID: BJ?rn Lindqvist wrote: > [...] > Here is another solution: > > from itertools import groupby > from operator import itemgetter > > users = [1, 1, 1, 2, 2, 3, 4, 4, 4] > scores = [0, 1, 5, 3, 1, 2, 3, 3, 2] > > for u, s in groupby(zip(users, scores), itemgetter(0)): > print u, sum(y for x, y in s) Except that this won't work unless users and scores are sorted by user first. groupby() only coalesces identical values, and doesn't do what a "GROUP BY" clause in SQL is doing. Adding a sorted() call around zip() should be enough to make groupby() actually useful. But then, this code definitely starts to look like somebody desperately wanted to find a use for Python's new gimmicks. Here's more of the same sort ;-) >>> import sqlite3 >>> sqlite3.connect(":memory:").execute("create table tmp(user, score)").executemany("insert into tmp(user, score) values (?, ?)", zip(users, scores)).execute("select user, sum(score) from tmp group by user").fetchall() [(1, 6), (2, 4), (3, 2), (4, 8)] -- Gerhard From daveparker at flamingthunder.com Wed Jun 11 10:36:59 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Wed, 11 Jun 2008 07:36:59 -0700 (PDT) Subject: Dynamic HTML from Python Script References: <484f151c$0$5009$607ed4bc@cv.net> <484f21aa$1@dnews.tpgi.com.au> <484f24e9$0$5020$607ed4bc@cv.net> <484f2870$1@dnews.tpgi.com.au> <484f3574$0$4998$607ed4bc@cv.net> <5493ff9f-7ed0-41db-9837-94b11f757d3f@j1g2000prb.googlegroups.com> Message-ID: On Jun 11, 7:59 am, Lie wrote: > You can't make the browser refresh automatically in the server side, Yes you can. I don't know how to do it in Python, but here's an example in Flaming Thunder of a small, fast, light compiled server side CGI that delivers dynamic content every 10 seconds. # Write out the HTTP headers, followed by a blank line. # Make sure to write CRLF and not just LF, as per HTTP # specs. Also, turn off caching using the no-cache and # expires options, so that caching doesn't conflict with # refreshes. Set CRLF to CarriageReturn+LineFeed. Write "Refresh: 10; url=http://www.flamingthunder.com/cgi/ refresh.cgi",CRLF. Write "Content-type: text/html",CRLF. Write "Pragma: no-cache",CRLF. Write "Expires: 0",CRLF. Write "Cache-Control: no-cache",CRLF. Write CRLF. # Write out the dynamic information. In this # case, we'll just write out Greenwich mean time. Write GetGreenwichMeanTime. For this example, the dynamic content is just Greenwich mean time. You can see it in action at: http://www.flamingthunder.com/cgi/refresh.cgi To create the CGI script, I used Flaming Thunder's cross compiling ability to compile the script under Windows, targeting Linux: ft file refresh.ft output refresh.cgi target linux32 I then ftp'd refresh.cgi up to the cgi directory on my server, set the permissions to 700 to make it executable, and it works (without needing to install any bulky, plodding interpreter). On Jun 11, 7:59?am, Lie wrote: > On Jun 11, 9:16?am, asdf wrote: > > > > > > > On Wed, 11 Jun 2008 11:20:48 +1000, Aidan wrote: > > > asdf wrote: > > >>> Well, there's a few ways you could approach it. > > > >>> You could create a cgi program from your script - this is probably the > > >>> solution you're looking for. > > > >> Output from the script does come up very often. There is a new output > > >> every 10 secs and it's possible that the script might be run > > >> indefinitely. Basically I want all that output displayed in a web > > >> browser > > > > Well, in that case you could simply append the new output to a static > > > file every 10 seconds, or whenever there is new output. ?That way, you > > > just need to refresh the static file in your browser to see updates... > > > Given what I understand of your situation, that's how I'd do it. > > > The problem with this is that browser would have to be refreshed manually > > every 10 seconds. Unless there is a way to set this in the script itself. > > Surely you don't think you can do that without Javascript don't you? > You can't make the browser refresh automatically in the server side, > it has to be done in the client side scripting or like Opera browser > that have an option to make it refresh a page every few seconds. > > > > > > A constantly running CGI app is probably not the best idea, given > > > timeouts and other such constraints you might run into. > > > >>> You could have the script run periodically and create a static html > > >>> file in the webroot... this would be acceptable, maybe preferable, if > > >>> the output from your script doesn't change frequently.- Hide quoted text - > > - Show quoted text -- Hide quoted text - > > - Show quoted text - From tdahsu at gmail.com Sat Jun 14 18:29:26 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Sat, 14 Jun 2008 15:29:26 -0700 (PDT) Subject: Avoiding redirects with urllib References: Message-ID: <5c25f007-03dd-487f-9548-4e8481fc6142@m36g2000hse.googlegroups.com> On Jun 14, 6:18?pm, tda... at gmail.com wrote: > On Jun 14, 5:22?pm, Fernando Rodriguez > > wrote: > > Hi, > > > I'musing urllib to download pages from a site. How can I detect if a given > > url is being redirected somewhere else? I want to avoid this, is it possible? > > > Thanks in advance! > > Try this: > > import urllib > url_opener = urllib.URLopener() # create URLopener > #You could also work with urllib.FancyURLopener > > try: > ? ? data = url_opener.open("http://www.somedomain.com/index.html") ? # > open index.html > except IOError, error_code: > ? ? if error_code[0] == "http error": > ? ? ? ? if error_code[1] == 301: > ? ? ? ? ? ? #do something here > ? ? ? ? if error_code[2] == 302: > ? ? ? ? ? ? #do something here > > I hope that's of some help! ?I think you may want to delve deeper into > FancyURLopener... That last part might better be: if error_code[1] == 301: #do something here elif error_code[1] == 302: #do something here From spectrumdt at gmail.com Thu Jun 19 07:47:39 2008 From: spectrumdt at gmail.com (Spectrum) Date: Thu, 19 Jun 2008 04:47:39 -0700 (PDT) Subject: Extending Python with C: Cannot find MPI library Message-ID: I am writing some Python code using the Message Passing Interface (MPI), an API used in parallel computing. There exist a number of Python implementations of MPI, but apparently they all rely on the Numeric Python (numpy) package. I need to run my code on a particular machine made available by my university, which does not have numpy and will not be getting it. So I am trying to write my own mini-wrapper for MPI in C to extend my Python program. There exists a special C compiler to use when compiling C programs that use MPI, called mpicc. Here is what I have tried: I have written a minimal C program that uses MPI. It works correctly when compiled with mpicc. Then I've written Python boilerplate code and a Python script to compile my C program into a Python-includable module. This does not work a priori because the Python compilation script uses gcc rather than mpicc. So I have taken the exact gcc command that the script uses and replaced "gcc" with "mpicc". This produces an *.so file that compiles without errors. Unfortunately, it fails when I try to import it in Python. It can't find the MPI library. My MPI code looks like this (plus some boilerplate code): /* Return the MPI rank of the current process. */ int rank(){ int argc; char **argv; int rank, size; MPI_Init( &argc, &argv ); MPI_Comm_rank( MPI_COMM_WORLD, &rank ); MPI_Finalize(); return rank; } /* Main. A 'Hello World' function. */ int hello() { int rankNumber = rank(); printf ("Hello, World. I am process %d.\n", rankNumber); return rankNumber; } My Python program that includes it looks like this: import ctest ctest.hello() My error message is this: [ore at localhost Opgave03]$ mpiexec -n 1 python ctest.py Traceback (most recent call last): File "ctest.py", line 1, in import ctest ImportError: /big/School/Cluster/Opgave03/ctest.so: undefined symbol: ompi_mpi_comm_world [ore at localhost Opgave03]$ Can anyone suggest anything? Can I get MPI to work in Python? Last time I asked a similar question, someone recommended that I check out Cython instead of C. Do MPI bindings for Cython exist? Thanks in advance. - Claus Appel From eliben at gmail.com Fri Jun 27 09:10:17 2008 From: eliben at gmail.com (eliben) Date: Fri, 27 Jun 2008 06:10:17 -0700 (PDT) Subject: problem compiling extensions with mingw Message-ID: <4973972a-e510-49b1-86bf-4ee4294842cd@m44g2000hsc.googlegroups.com> Hello, I'm trying to compile the minimal example from http://en.wikibooks.org/wiki/Python_Programming/Extending_with_C with MinGW (latest version) and Python 2.5 (latest ActiveState binary install). When running the setup file, the following happens: running build running build_ext building 'hello' extension writing build\temp.win32-2.5\Release\hello.def d:\mingw\bin\gcc.exe -mno-cygwin -shared -s build \temp.win32-2.5\Release\hellomo dule.o build\temp.win32-2.5\Release\hello.def -LC:\Python25\libs -LC: \Python25\P Cbuild -lpython25 -lmsvcr71 -o build\lib.win32-2.5\hello.pyd build\temp.win32-2.5\Release\hellomodule.o:hellomodule.c:(.text+0x3e): undefined reference to `_imp___Py_NoneStruct' build\temp.win32-2.5\Release\hellomodule.o:hellomodule.c:(.text+0x46): undefined reference to `_imp___Py_NoneStruct' collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 What's more, compiling the same extension with Visual Studio 2005 (without using distutils) works fine, the extension is loaded and ran successfully from Python. Any ideas about this error ? Eli From andrei.avk at gmail.com Mon Jun 9 14:01:29 2008 From: andrei.avk at gmail.com (Rainy) Date: Mon, 9 Jun 2008 11:01:29 -0700 (PDT) Subject: Separators inside a var name References: Message-ID: <8f93a005-3149-41ef-90c8-934f9543fe75@79g2000hsk.googlegroups.com> On Jun 9, 1:42?pm, Gary Herron wrote: > Rainy wrote: > > I have a stylistic question. In most languages words in var. name are > > separated by underscores or cap letters, resulting in var names like > > var_name, VarName and varName. I don't like that very much because all > > 3 ways of naming look bad and/or hard to type. From what I understand, > > scheme can have variables like var-name. I'm curious about reasons > > that python chose to disallow this. > > Because we'd prefer var-name to mean subtraction of values: var minus > name. ?If you want to use a that character in names, what syntax would > you prefer for subtraction? ?Do you consider lisp/scheme (- a b) to be > reasonable in Python? I would make it that var - var2 would be subtraction and var-name would be a var name. I don't like (- a b) but I might have preferred it if it allowed dashes inside var names, if I got used to it. Hard to say. > > > Another question I have is what > > other languages allow this naming scheme? Were there any languages > > that allowed space as a separator? > > Fortran used to. ?(Haven't checked in on it in years though so I don't > know now). ?And it not so much as allowed spaces as it *ignored* all > spaces. ?This was now-a-days considered a *really* bad idea, and is > rumored to be responsible for a bug that crashed a satellite. ?(At least > that's the way a nice urban legend tells it.) Well, if I understand right, fortran used caps for many things? I'm not sure how it separated things if it ignored all spaces. I'll trust you that it's not a good idea :-). However that's not what I meant, I'd just like to use (or rather try using) spaces inside var names. From wolfgang.grafen at ericsson.com Mon Jun 16 08:57:07 2008 From: wolfgang.grafen at ericsson.com (Wolfgang Grafen) Date: Mon, 16 Jun 2008 14:57:07 +0200 Subject: bpython - fancy Python shell In-Reply-To: References: Message-ID: I couldn't get it work on Solaris (modified some lines for Python2.3). One reason was that I had to download pyreadline separately - I did than but now pyreadline requires either ironpython or a windows installation. Something is going wrong... Best regards Wolfgang Bob Farrell schrieb: > I released this a while ago but did some work recently to fix some bugs > so I thought I may as well post it here. To quickly summarise: > In-line syntax highlighting > Auto complete with suggestions as you type > Pastebin stuff, save to file > "Rewind" feature to jump back a line if you mess up (don't ask how it > works, please ;) > > You can get it here: > http://www.noiseforfree.com/bpython/ > > There's info about git repos and what have you there, and apparently > it's also in some real distro repos, but I don't know the details. > > Oh, and you'll need pygments and pyparsing, and it doesn't work on > Windows (heard good reports about it working fine on a Mac though). From pavlovevidence at gmail.com Mon Jun 2 20:11:31 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 2 Jun 2008 17:11:31 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> Message-ID: On Jun 2, 7:41 pm, "Russ P." wrote: > I thought you were saying that encapsulation or so-called "data > hiding" is worthless. If I misunderstood you, then I apologize. I > don't have time to go back and sort it all out. No, not at all. I was suggesting that Antoon's example of data hiding wasn't useful because it didn't really hide data: it was merely a spelling change. (I'm not, mind you, saying that it's ordinarily a good trade-off to encapsulate data, but I do get the point of it.) > Here's what I think Python should have. I think it should have a > keyword, something like "priv," to identify data or functions as > "private." As I said earlier, "private" for class data or functions > ("methods") could be implemented like "protected" in C++. That means > that derived classes would have access to it, but clients of the class > would not. If the client really needs or wants access, he could be > given a sort of "back door" access similar to the current Python rule > regarding double leading underscores. Thus, the client would have > access, but he would know very well that he is using something that > the original designer did not intend for him to use. Reasonable enough. I've always thought C++ should have a private_cast. Carl Banks From rdh at new.rr.com Thu Jun 5 08:48:18 2008 From: rdh at new.rr.com (DataSmash) Date: Thu, 5 Jun 2008 05:48:18 -0700 (PDT) Subject: readline() & seek() ??? References: <12655f64-33b1-4ab0-b6fb-294bfd2fa8c6@d45g2000hsc.googlegroups.com> Message-ID: <9c09e3cf-9117-4d62-b7bc-6fc59fe13ed1@m36g2000hse.googlegroups.com> On Jun 5, 3:50 am, Carl Banks wrote: > On Jun 4, 5:30 pm, DataSmash wrote: > > > Hi group, > > I have a text file that contains thousands of lines and each line is > > 256 characters long. > > > This is my task: > > For each line in the file, move to the 25th character, if the > > character is a "T", > > move to the 35th character of the line and read 5 characters from > > there. > > Capture these 5 characters and write them to a new text file, each 5 > > characters separated by a comma. > > Your professor possibly reads comp.lang.python, and if so, is likely > to know how to track you down with your IP address. > > Carl Banks Marc, Thanks. Tim, Thanks for the code. It's a easy task IF you know what to look for. I didn't. Carl, I'm not a student. Was just looking for some ideas. From tracyde at gmail.com Fri Jun 6 08:50:31 2008 From: tracyde at gmail.com (Derek Tracy) Date: Fri, 6 Jun 2008 08:50:31 -0400 Subject: Python CGI Upload from Server Status Message-ID: <9999810b0806060550w5a7297dbm8ba5cc902cad6f8b@mail.gmail.com> I am trying to create a simple python cgi app that allows the user to kick off an ftp from the server the cgi is on to another server; I have that piece working using ftplib but since the files in question are usually very large (500mb to 2gb) in size I want to be able to display some sort of status to the user, preferrably a progress bar of some sort. I have been scouring the internet for 2 days and have not came across a solution. I am unable to add modules that are not standard python modules (security restrictions), and have tried doing a page refresh meta tag and just have the cgi keep adding information to the page, but that doesn't seem to work. Does anybody have any ideas as to how I can attack this issue? -- --------------------------------- Derek Tracy tracyde at gmail.com --------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From lawtonpaul at gmail.com Sun Jun 15 20:18:54 2008 From: lawtonpaul at gmail.com (takayuki) Date: Sun, 15 Jun 2008 17:18:54 -0700 (PDT) Subject: newbie: for loop within for loop question Message-ID: <4ce96e03-d336-4c44-9d10-4a9418ce359d@w34g2000prm.googlegroups.com> Hi everyone, I'm studying python via the excellent "how to think like a python programmer" book by Allen Downey. Noob question follows... I have a txt file (animals.txt) which contains the following text each on a separate line: aardvark, bat, cat, dog, elephant, fish, giraffe, horse, inchworm, jackelope I want to create a function that loops through the animals.txt file and does *not* print the word if any of the user specified letters are in that word. def hasnolet(x): From kyosohma at gmail.com Tue Jun 10 20:45:26 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 10 Jun 2008 17:45:26 -0700 (PDT) Subject: Instructions on how to build py2exe 0.6.8 (or an installer would be nice, too!) References: <5426baaf-2ba6-41b0-a0ec-1070429b5195@x35g2000hsb.googlegroups.com> <7f3360e4-8a12-45cf-99fa-6172cb5a1aaa@a1g2000hsb.googlegroups.com> <1pqdneEnFojla9PVnZ2dnUVZ_oSunZ2d@comcast.com> Message-ID: <52e147d4-43ca-4f74-b21e-fa31ea49d219@m3g2000hsc.googlegroups.com> On Jun 10, 4:47?pm, Larry Bates wrote: > chard... at gmail.com wrote: > > On Jun 10, 11:34 am, Mike Driscoll wrote: > >> Maybe I'm missing something, but I can rename the executables I create > >> using py2exe 0.6.6 to anything I want after they're created. > > >> Or are you talking about a Windows installer for the py2exe module > >> itself? Where are you finding this 0.6.8 version anyway? I can't find > >> it onwww.py2exe.org > > >> Anyway, what Thomas is talking about is that the only way to create a > >> usable installer of py2exe on Windows is to use the same compiler that > >> the Python you are using. As I understand it, Python 2.4 and 2.5 used > >> Visual Studio 2003. I think 2.3 used VS6. I have both, so I can try to > >> compile an installer for any of those versions if you can link me to > >> the source. > > >> Mike > > >> Python Extension Building Network: ? ? http:\\www.pythonlibrary.org > > > The issue with renaming executables only applies to single-file > > executables, i.e. ones created with zipfile = None as an argument to > > setup() and --bundle 1 as a command line argument. This is a known > > issue as of 0.6.6:http://py2exe.org/index.cgi/ProblemsToBeFixed > > > I found sources for 0.6.8 on CVS at:http://sourceforge.net/cvs/?group_id=15583 > > > A Windows installer for the 0.6.8 py2exe module would be ideal, but > > somehow I doubt that's going to happen anytime soon since there hasn't > > been a new installer since 2006. If you are willing to build that for > > me (since I don't have VS) I'd really appreciate it : ) I'm using 32- > > bit WinXP on this computer. > > About every two weeks this "issue" pops up. ?Question: Why is is so important to > package everything into a single file? ?There are no Windows applications (that > I'm aware of) that ship as single files. ?Many of them consist of hundreds and > in some cases 'thousands' of files. ?Now if you want to DISTRIBUTE a single > setup.exe file, that makes sense to me. ?Use py2exe without the single file > option and ship a setup.exe file created by Inno Installer. ?Problem solved. > You will thank me when you want to include: registry entries, shortcuts, > documentation, configuration files, etc. in the distribution. > > -Larry Excellent point. I do include other files with my one exe using Inno myself. Originally when I bundled it all in one, my reasoning was that I needed to push it out to my organization and I figured pushing one large files was better than pushing a bunch of small ones. Or something like that. In retrospect, that's a dumb reason as I have lots of automated Python installers for things like Adobe Reader and Java and they basically just do copy jobs. Anyway, thanks for pointing that out. Mike From tdahsu at gmail.com Fri Jun 13 11:43:28 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Fri, 13 Jun 2008 08:43:28 -0700 (PDT) Subject: Iterate creating variables? References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> <6bfhj5F3b47fmU1@mid.uni-berlin.de> Message-ID: On Jun 13, 11:21?am, "Diez B. Roggisch" wrote: > tda... at gmail.com schrieb: > > > > > I have twenty-five checkboxes I need to create (don't ask): > > > self.checkbox1 = ... > > self.checkbox2 = ... > > . > > . > > . > > self.checkbox25 = ... > > > Right now, my code has 25 lines in it, one for each checkbox, since > > these are all variables. > > > Is there a way to write a loop so that I can have fewer lines of code > > but still keep the variables? > > > I've tried: > > > for o in xrange(25): > > ? ? self.checkbox[o] = ... > > > which didn't work, and > > > for o in xrange(25): > > ? ? self.checkbox[''%d'%(o)] = ... > > > which also didn't work. > > > Both give the error message: "Attribute error: Main.App has no > > attribute "checkbox"", which clearly indicates that I'm not keeping > > the "variability" aspect I want. > > > Is there a way? > > Keep either a list or dictionary around. Like this: > > checkboxes = [] > > for o in xrange(25): > ? ? ?checkboxes.append(....create a checkbox...) > > self.checkboxes = checkboxes > > Diez I don't understand... how do I then complete the assignment statement? If I have: self.checkbox1 = xrc.XRCCTRL(self.panel01, 'Checkbox1') . . . self.checkbox25 = xrc.XRCCTRL(self.panel01, 'Checkbox25') using your method, wouldn't I still need to figure out my original question? If I have a list of checkboxes, then I'll have: checkboxes = [checkbox1, checkbox2 ... checkbox25] in which case I'd still need to figure out how to get the variable at the end of checkbox to do the rest of the "=" statement. Or am I missing something? (I'm guessing that's likely!) Thanks. From fivetwentysix at gmail.com Thu Jun 5 02:46:26 2008 From: fivetwentysix at gmail.com (fivetwentysix at gmail.com) Date: Wed, 4 Jun 2008 23:46:26 -0700 (PDT) Subject: Looking for some good python learning resources on the web Message-ID: <8c4fb782-2767-4163-a577-195a22623493@v1g2000pra.googlegroups.com> What are the best sites to read to learn python? From gh at ghaering.de Mon Jun 9 04:06:12 2008 From: gh at ghaering.de (=?UTF-8?B?R2VyaGFyZCBIw6RyaW5n?=) Date: Mon, 09 Jun 2008 10:06:12 +0200 Subject: SQlite none english char In-Reply-To: References: <6b1ld5F3a4hsvU1@mid.uni-berlin.de> Message-ID: Gandalf wrote: > [...] > I solved the problem by entering data manually but now the problem is > that i had to delete this function: > con.text_factory = str > and now I can't see the data that I entered thought my sqlite manager Then apparently there is still non-UTF-8 data in the database. Perhaps SQLite Manager allows you to insert invalid data as well? Try this: con.text_factory = lambda s: unicode(s, "utf-8", "replace") This will decode to UTF-8 as good as possible, and for non-decodable characters you will get a REPLACEMENT CHARACTER instead. To demonstrate: >>> result = con.execute("select ? || ? || ?", ('text ok ', chr(230), ' ok, too')).fetchone()[0] The chr(230) is just random garbage that isn't valid UTF-8: >>> print result text ok ?k, too As you can see, there is now a strange character, but the second 'ok, too' got messed up :-/ But at least you can then find out which rows in the database have messed up data. You can then iterate over all rows with something like: Then, assuming the text to check for validity is in result, you can do something like: >>> import unicodedata >>> unicodedata.lookup("REPLACEMENT CHARACTER") in result True Does this help? -- Gerhard PS: This thread reinforces my believe that I have to make it harder for users of pysqlite to make themselves shoot in the foot with non-UTF-8 data. From wescpy at gmail.com Mon Jun 16 20:46:30 2008 From: wescpy at gmail.com (wesley chun) Date: Mon, 16 Jun 2008 17:46:30 -0700 Subject: FYA: visualizing repository commits Message-ID: <78b3a9580806161746k6916ae45ldb1621706daf259e@mail.gmail.com> have you guys seen this on Slashdot yet? (i did a quick search in the archives and haven't seen any posts yet so hopefully this isn't a duplicate msg!) http://developers.slashdot.org/developers/08/06/16/1855209.shtml this video is a visualization of the commits to the source base (and made by whom) over Python's lifetime: http://www.vimeo.com/1093745 the visualization project's home page is at: http://vis.cs.ucdavis.edu/~ogawa/codeswarm/ -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From jwkenne at attglobal.net Tue Jun 24 18:42:15 2008 From: jwkenne at attglobal.net (John W Kennedy) Date: Tue, 24 Jun 2008 18:42:15 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: Message-ID: <48617847$0$5021$607ed4bc@cv.net> David Combs wrote: > passing > *unnamed* functions as args (could Algol 60 also do something like that, > via something it maybe termed a "thunk") No, the "thunks" were necessary at the machine-language level to /implement/ ALGOL 60, but they could not be expressed /in/ ALGOL. -- John W. Kennedy "The first effect of not believing in God is to believe in anything...." -- Emile Cammaerts, "The Laughing Prophet" From mail at timgolden.me.uk Thu Jun 26 13:44:38 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 26 Jun 2008 18:44:38 +0100 Subject: Windows process ownership trouble In-Reply-To: <33847c9a-a816-48a1-a8c9-4209db9bf0b5@e53g2000hsa.googlegroups.com> References: <3fcf363f-3685-4b7b-8ba5-1ffc32e58af7@m44g2000hsc.googlegroups.com> <990516b7-f7ef-464a-97d0-fd55a0354ab4@y21g2000hsf.googlegroups.com> <33847c9a-a816-48a1-a8c9-4209db9bf0b5@e53g2000hsa.googlegroups.com> Message-ID: <4863D586.8030004@timgolden.me.uk> geoffbache wrote: > Tim, > > Unfortunately my previous message was premature, it seems your > workaround doesn't work > either on my system (Windows XP, Python 2.5.1) I get the following > printed out > > Traceback (most recent call last): > File "C:\TextTest\processown.py", line 12, in > os.remove ("filename") > WindowsError: [Error 32] The process cannot access the file because it > is being used by another process: 'filename' > close failed: [Errno 9] Bad file descriptor (Assuming you have the pywin32 extensions installed...) If you tweak your copy of subprocess.py by switching on the use of the pywin32 extensions in preference to the _subprocess module, the problem goes away, I think because the PyHANDLE object auto-closes. I'm not saying it won't ever fail -- the interactions of objects, scope, frames, exceptions and garbage collection are things I've never looked at too closely. But if you change line 378 from if 0: to if 1:, then the following works fine: import os import subprocess f = open ("filename", "w") try: p = subprocess.Popen ("blah", stdout=f) except WindowsError: f.close () os.remove ("filename") Note that the os.remove is *outside* the except handler. This is, I think, because the underlying handle object is still active until the try/except block closes. At which point it is, probably, gc-ed and closes. And you can remove the file. TJG From timr at probo.com Sun Jun 29 23:27:00 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 30 Jun 2008 03:27:00 GMT Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> Message-ID: <0ckg64hkkcjb7et08rv2hn5vb6nchkmbcl@4ax.com> John Salerno wrote: > >No, I don't mean presentation logic at all. I mean something along the >lines of combining HTML (which is what I refer to as "content") and >Python (which is what I meant by "logic"). So for example, if you have >code like this (and this isn't necessarily proper code, I'm just making >this up, but you'll see what I mean): > > >

    Big Important Topic

    >

    This is where I say something important about

    >
      > % for topic in topics: >
    1. ${topic}
    2. >
    > > >Humph, I just made up that example to make the point that when you no >longer have pure HTML, but instead have programmatic logic (Python) >mixed in with the HTML, then you are mixing content and logic. Technically, you are probably right, but a model like MVC is supposed to enable better programming. It's not intended to be straightjacket and handcuffs. If that snippet makes sense to you, then there's nothing wrong with it. What's the alternative? The alternative is to have your Python code do something like this: topicList = [] for topic in topics: topicList.append( topic ) topicList = '
  • '.join( topicList ) and have your HTML page be:
    1. ${topicList}
    but now I've put chocolate into my peanut butter by embedding
  • tags in my Python code. >So maybe my question was a little premature. Or could it just be that >this is a *good* way to mix HTML and Python, and there are other ways >which may be bad? (For example, connecting to a database, like >Sebastian's example. That definitely seems out of place in an HTML file.) If it seems out of place to you, then you shouldn't do it. In general, you need to find a model that makes sense to you, and that allows you to write readable, workable, maintainable code. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From larry.bates at websafe.com` Mon Jun 2 17:02:34 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 02 Jun 2008 16:02:34 -0500 Subject: Cast list of objects to list of strings In-Reply-To: <48546eb1-11f3-4a88-b1ac-97bd485a1823@k30g2000hse.googlegroups.com> References: <48546eb1-11f3-4a88-b1ac-97bd485a1823@k30g2000hse.googlegroups.com> Message-ID: bukzor wrote: > I have this function: > > def write_err(obj): > from sys import stderr > stderr.write(str(obj)+"\n") > > and I'd like to rewrite it to take a variable number of objects. > Something like this: > > def write_err(*objs): > from sys import stderr > stderr.write(" ".join(objs)+"\n") > > but I lose the property that the function works on any object. What's > the simplest way to fix this? In essence, I need to cast a list of > objects to a list of strings. I'd like to do just "str(objs)" but that > (obviously) doesn't quite do what I need. > I think what you want is: def write_err(*args): from sys import stderr stderr.write("\n".join([str(o) for o in args])) but then I don't really understand why you would want such a function so I could be way wrong. -Larry From sjmachin at lexicon.net Fri Jun 27 09:23:56 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 27 Jun 2008 06:23:56 -0700 (PDT) Subject: where is the error? References: <8f8e1bf7-78b0-4292-9d56-396527b9dfb1@z66g2000hsc.googlegroups.com> <15ea1cb1-76a3-4fd3-8e4c-521b9aefcca2@m3g2000hsc.googlegroups.com> Message-ID: On Jun 27, 10:12 pm, la... at caramail.com wrote: > There was an error with the name of the variable !!!! I would not ask > this if it was just a question of different variable names !!!!! > Calm down. Stop shouting. It is not evident whether the above means that diff_temp_Stumpf was an error (should have been merely diff_temp) or not. > diff_temp=(logical_and(values[:,5] > -2,values[:,5] < 2)).nonzero() > new_values=values[diff_temp,:] > > Okay, I'm going to try to explain that more specifically that I did. I > have an array called values (size mxn). In this database, I just want > the lines for which the values of the nth row are between two values > (it's the purpose of diff_temp). So diff_temp gets me the number of > the lines for which this latter criteria is right. I think that you mean that diff_temp will be an array of the numberS (plural) of the lines (rows?) in values array that met the -2 < x < 2 criterion. Now you want to be able to use diff_temp to get the corresponding subset of some other array. Am I getting close? > But I'm interested > on the values of the lines corresponding to the number given by > diff_temp. Now you want to be able to use diff_temp to get the corresponding subset of some other array. Am I getting close? Perhaps you need something like other_array.take(diff_temp) ? > > In matlab, I will do > > diff_temp=find(values(:,5) > -2 & values[:,5) <2) > > new_values=values(diff_temp,:) > > Is it clear? Not very, I don't grok matlab. By the way, shouldn't you be using numpy? I thought numarray was going away by mid-2008 i.e. now. HTH, John > Thanks > Cedric From timr at probo.com Wed Jun 11 02:58:49 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 11 Jun 2008 06:58:49 GMT Subject: Python doesn't understand %userprofile% References: Message-ID: bsagert at gmail.com wrote: > >In xp when I try os.path.getmtime("%userprofile/dir/file%") Python >bites back with "cannot find the path specified" Since my script has >to run on machines where the username is unspecified I need a fix. For the record, the %PERCENT% syntax for looking up an environment variable is just a feature of the XP command shell. It has no meaning to any other part of Windows. os.environ is the right answer. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From vaahi0404 at gmail.com Thu Jun 5 04:55:44 2008 From: vaahi0404 at gmail.com (dev) Date: Thu, 5 Jun 2008 01:55:44 -0700 (PDT) Subject: comp.lang.python Message-ID: <71fba7ee-8f48-40b5-9d96-6cf12a97db7b@i36g2000prf.googlegroups.com> www.freeservice6.blogspot.com From mail at timgolden.me.uk Mon Jun 23 14:58:31 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 23 Jun 2008 19:58:31 +0100 Subject: Using Python and MS-SQL Server In-Reply-To: <734a9927-a18b-4af6-a717-eaf2631b4836@c58g2000hsc.googlegroups.com> References: <734a9927-a18b-4af6-a717-eaf2631b4836@c58g2000hsc.googlegroups.com> Message-ID: <485FF257.9090702@timgolden.me.uk> hwcowan at hotmail.com wrote: > I have programmed before, but I am new to using Python. I am > currently using the ArcGIS software which uses Python as its scripting > language for automating tasks. > > The current script that I am working on requires pulling in some > information from a Microsoft SQL Server. > > I was wondering if anyone could suggest the best way of doing this? I > have looked at the different modules that are specific to SQL server, > but none of them seem to be active or up to date. > > If not, could anyone make any suggestions? Or would it be better to > go the ODBC route? I am not talking about large amounts of data, so I > am not concerned about performance so ODBC would be fine to use as > well. Have a look at this: http://ramblings.timgolden.me.uk/2007/09/26/using-mssql-from-within-python-25/ It's hardly comprehensive, but it more-or-less answers your question. > Also, being new to Python, I recently read about dictionaries and was > wondering if there was a quick way to dump a table into a dictionary? > > For example, I have a customer list with a customer ID. It would be > great to have the ID as the "key" and the name as the "data" (or even > better, have a list as the data element containing all the information > about the customer). > > I am sure that this could be done manually, by looping through each > record and adding it to the dictionary -- but I was just wondering if > something like this has already been done (I don't need to reinvent > the wheel here). The key phrase you're looking for here is ORM (Object-Relational Mapper). Again, not an exact match for what you're saying, but unless you app remains *remarkably* simple, you're going to end up reinventing an ORM anyway. Probably the front runner these days is sqlalchemy (which certainly supports MS-SQL): http://sqlalchemy.org but just Google for "python orm" for any number of discussions and comparisons. TJG From socyl at 987jk.com.invalid Fri Jun 20 08:15:31 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 20 Jun 2008 12:15:31 +0000 (UTC) Subject: Why no output from xml.dom.ext.PrettyPrint? References: <19999864-b381-41b5-90fa-7e3cc3996d65@w8g2000prd.googlegroups.com> Message-ID: In <19999864-b381-41b5-90fa-7e3cc3996d65 at w8g2000prd.googlegroups.com> John Machin writes: >On Jun 20, 7:17 am, kj wrote: >> OK, the following should work but doesn't, and I can't figure out >> why: >> >> >>> from xml.marshal.generic import dumps >> >>> dumps( ( 1, 2.0, 'foo', [3,4,5] ) ) >> >> '12.0foo345' >> >> >>> from xml.dom.ext import PrettyPrint >> >>> PrettyPrint( dumps( ( 1, 2.0, 'foo', [3,4,5] ) ) ) >> >>> import sys >> >>> PrettyPrint( dumps( ( 1, 2.0, 'foo', [3,4,5] ) ), sys.stdout ) >> >> Why am I seeing no output from PrettyPrint? >> >You need to ask whoever you got your xml package from. In standard- >issue Python 2.5.2, there is an xml package with xml.dom, but it >contains no xml.dom.ext nor an xml.marshal. Hmmm!? OK. Thanks! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From lajam at caramail.com Fri Jun 27 09:55:26 2008 From: lajam at caramail.com (lajam at caramail.com) Date: Fri, 27 Jun 2008 06:55:26 -0700 (PDT) Subject: where is the error? References: <8f8e1bf7-78b0-4292-9d56-396527b9dfb1@z66g2000hsc.googlegroups.com> <15ea1cb1-76a3-4fd3-8e4c-521b9aefcca2@m3g2000hsc.googlegroups.com> Message-ID: <6a8b6c1c-c74c-448d-89c7-01dd5c3b4a40@m45g2000hsb.googlegroups.com> > > I think that you mean that diff_temp will be an array of the numberS > (plural) of the lines (rows?) in values array that met the -2 < x < 2 > criterion. Now you want to be able to use diff_temp to get the > corresponding subset of some other array. Am I getting close? I think that you're getting close. I want to get the lines that met the criterion. Diff_temp is an array containing the values of the lines. So bascially, > Now you want to be able to use diff_temp to get the corresponding > subset of some other array. Am I getting close? yes > Perhaps you need something like other_array.take(diff_temp) ? And my problem was that the commands worked on windows but not on linux. > By the way, shouldn't you be using numpy? I thought numarray was going > away by mid-2008 i.e. now. I know, but i'm not sure that it's the problem. Thanks Cedric From drakonik at gmail.com Sat Jun 28 11:56:25 2008 From: drakonik at gmail.com (Nick Dumas) Date: Sat, 28 Jun 2008 11:56:25 -0400 Subject: Pygame and Tkinter Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I'm doing a project with Pygame, a Snake game, and I've just taken a look at Tkinter and I really like how easy it is to build a GUI with it. The thing is that I don't know how I would use Tkinter and Pygame in conjunction. They seem to have some overlapping functionality (event handling and window drawing) so I'm not sure which tool I should use for which. Should I code the GUI and game in Pygame? Could I possibly embed the game in a Tkinter window/frame/widget? I would like to hear ideas on this; it's a very important project and I'd like to do it well. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkhmXykACgkQLMI5fndAv9giRwCgn/Zu2MGk+tKxHx+x+dkxSjvN l5MAoITZ0K8ekV6mgbvOGpTAreznahcv =Br5C -----END PGP SIGNATURE----- From vdutto at gmail.com Tue Jun 3 03:22:40 2008 From: vdutto at gmail.com (V) Date: Tue, 3 Jun 2008 00:22:40 -0700 (PDT) Subject: Books for programmers Message-ID: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> Hi, I'm a C++, Java and C programmer, and I'm searching for a (preferably printed) book that teaches me the "Python idioms", i.e. the "Python way" of doing something. Ideally, I'm searching for a book like "Effective C++" or "Effective Java", that does not lose time teaching what is a class, or a function, or a loop, but that enters into details and describes not only the "how", but also the "why". I read the book "Dive into Python", but I found too schematic and not enough advanced for my interests. I generally do not like books from O'Reilly, while I prefere those from Addison Wesley. Best regards. From gagsl-py2 at yahoo.com.ar Tue Jun 10 23:47:54 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Jun 2008 00:47:54 -0300 Subject: Using ElementTree as backend for a chat web application issues References: <1e5bcefd0806091132p78f42109t1edb5e5acfaadb43@mail.gmail.com> Message-ID: En Mon, 09 Jun 2008 15:32:00 -0300, Marcelo de Moraes Serpa escribi?: > I've built a chat with a front-end Ajax client and backend usign > ElementTree > to persist the data. > > In some circunstances I could not yet discover (it seems random) when I > edit/save the structure, the structure gets corrupted, elementree seems > to > get lost in its internal "cursor", usually something like this happens: > > > > > > > id="3"/> > > Pretty strange, and it drives the whole application unusable. > > I don't know if the concurrent nature of the application (multiple users > using the client at almost the same time and sending data to the server > which in turn must save the data to the same global.xml file) has > something > to do with it - I don't know if ElementTree is suitable for this kind of > thing. How to hanlde this concurrent issue? I don't think it's a problem with ElementTree. Perhaps you are writing the same (global) configuration file from several threads at the same time? You may need some locking mechanism in that case. -- Gabriel Genellina From eric.talevich at gmail.com Tue Jun 3 13:35:42 2008 From: eric.talevich at gmail.com (etal) Date: Tue, 3 Jun 2008 10:35:42 -0700 (PDT) Subject: Merging ordered lists References: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> <5722bab6-471b-4512-9d5e-7b173722d55b@p25g2000pri.googlegroups.com> <7d6bbe74-d6c5-4bb1-98b6-455f1fa0e18d@59g2000hsb.googlegroups.com> Message-ID: <4d8b256a-e918-48f9-b7fc-d98188508137@f36g2000hsa.googlegroups.com> On Jun 2, 11:08?pm, Raymond Hettinger wrote: > > If the inputs were not sorted, then I don't think you have a precise > idea of what it means to merge them while preserving order. ? For > example if the inputs are XYZPDQ and bYlmPz, then what does a merged > sequence look like once the Y and P duplicates are removed? Is it > XZPDQblmz or some intermix of the two like XbZlPmDzQ? ?If it is the > first of those, then the answer is simple: > I was looking at Bram Cohen's description of his diff algorithm, implemented in Bazaar: http://bramcohen.livejournal.com/37690.html "Instead of doing a longest common subsequence on everything, it does a longest common subsequence on lines which occur exactly once on both sides, then recurses between lines which got matched on that pass." So, if sources looks like: [list("XYZPDQ"), list("bYlmPz")] Then the proper merge would use Y and P as the delimiters, putting X and b before Y; Z, l and m before P; and D, Q and z after P -- like your second example (but keeping an instance of Y). Right? Leaving us with the context-dependent issue of ordering between the delimiters, probably depending on which list is used as the reference initially. So, if the reference list's elements go first, the result would be XbYZlmPDQz. If the elements from later sources go after the last common element (my first approach), it's bXYlmZPzDQ. However, in the cold light of morning it looks like that was the wrong approach -- it makes sense to treat any data that doesn't occur in the reference list as semi-obsolete and append it instead -- so I think I'll use your much simpler algorithm. Thanks! From johnjsal at NOSPAMgmail.com Thu Jun 26 12:10:45 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 26 Jun 2008 12:10:45 -0400 Subject: Mako vs. Cheetah? References: <4862f57c$0$11621$607ed4bc@cv.net> Message-ID: <4863bf9c$0$14081$c3e8da3@news.astraweb.com> "John Salerno" wrote in message news:4862f57c$0$11621$607ed4bc at cv.net... >I always have the desire to learn one thing well instead of split my >attention between several options, so I'm trying to decide which of these >two to start learning. Are there any particular things I should look at >when deciding between them, in terms of features, for example? Do they do >all the same things? Is it correct to say that Mako allows you to embed Python code within HTML, whereas Cheetah requires a certain amount of "tweaking" of Python code so that it isn't really code you could just run independently in the interpreter? I'm getting that impression from what I see so far. From mdw at distorted.org.uk Sun Jun 8 08:40:37 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Sun, 8 Jun 2008 12:40:37 +0000 (UTC) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> Message-ID: Russ P. wrote: > The idea of being able to discern properties of an object by its name > alone is something that is not normally done in programming in > general. Really? You obviously haven't noticed Prolog, Smalltalk, Haskell, ML, or Erlang then. And that's just the ones I can think of off the top of my head. * Prolog and Erlang distinguish atoms from variables by the case of the first letter; also `_' is magical and is equivalent to a new variable name every time you use it. * Smalltalk distinguishes between global and local variables according to the case of the first letter. * Haskell distinguishes between normal functions and constructors (both data constructors and type constructors) by the case of the first letter, and has Prolog's `_' convention. * ML allows a single-quote in variable names, but reserves names beginning with a single-quote for type variables. It also has Prolog's `_' convention. As far as I can see, discerning properties of a thing from its name seems relatively common. -- [mdw] From geoff.bache at jeppesen.com Thu Jun 19 04:09:59 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Thu, 19 Jun 2008 01:09:59 -0700 (PDT) Subject: Annoying message when interrupting python scripts References: <578d1ef8-231b-46fa-a181-e320fe1cc368@s33g2000pri.googlegroups.com> <87y753wk9a.fsf@benfinney.id.au> <1729bb65-0d3c-4407-858b-3816e19a46a3@d19g2000prm.googlegroups.com> <565c5f0e-5aef-4bcf-ab26-793ff138348f@59g2000hsb.googlegroups.com> Message-ID: <4d0f56dc-fc8a-4b54-ab59-24d827b15a39@c58g2000hsc.googlegroups.com> As nobody decried the idea of this being a bug, it now is :) http://bugs.python.org/issue3137 /Geoff From dullrich at sprynet.com Fri Jun 13 13:04:31 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 13 Jun 2008 12:04:31 -0500 Subject: Mapping None. Why? References: Message-ID: In article , Paddy wrote: > On Jun 13, 12:49 pm, David C. Ullrich wrote: > > On Thu, 12 Jun 2008 12:05:02 -0700 (PDT), Paddy > > > > wrote: > > > > >Iam wondering why the peculiar behavior of map when the function in > > >given as None: > > > > If you start with a value x and then apply no function > > at all to it, what results is x. > > > > David C. Ullrich > > True, but None is not a function. It's a sentinel value to turn on the > functionality. Uh, thanks. I think I knew that - I was just suggesting why the way map works makes sense. > - Paddy. -- David C. Ullrich From pavlovevidence at gmail.com Mon Jun 2 08:14:59 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 2 Jun 2008 05:14:59 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> Message-ID: On Jun 2, 6:40 am, Antoon Pardon wrote: > On 2008-06-02, Carl Banks wrote: > > > > > On Jun 2, 5:38 am, Antoon Pardon wrote: > >> If you really need it, you can do data hiding in python. It just > >> requires a bit more work. > > >> ----------------------------- Hide.py --------------------------------- > >> class Rec(object): > >> def __init__(__, **kwargs): > >> for key,value in kwargs.items(): > >> setattr(__, key, value) > > >> def __getitem__(self, key): > >> return getattr(self, key) > > >> def __setitem__ (self, key, val): > >> setattr(self, key, val) > > >> class Foo(object): > > >> def __init__(self): > > >> hidden = Rec(x=0, y=0) > > >> def SetX(val): > >> hidden.x = val > > >> def SetY(val): > >> hidden.y = val > > >> def GetX(): > >> return hidden.x > > >> def GetY(): > >> return hidden.y > > >> self.SetX = SetX > >> self.SetY = SetY > >> self.GetX = GetX > >> self.GetY = GetY > > > Red Herring. > > > 1. This doesn't hide the variables; it just changes their spelling. > > 2. This also "hides" the variables from its own class. > > > In other words, it's a useless no-op. > > > In fact, I'd say this is even worse than useless. Creating accessor > > functions is a sort of blessing for external use. Knowing that there > > are accessor functions is likely to cause a user to show even less > > restraint. > > I think you completed missed the point. I'm not sure I missed the point so much as I failed to read your mind. > This is just a proof of concept thing. In a real example there would > of course no Set en Get methods but just methods that in the course > of their execution would access or update the hidden attributes Fair enough, but I don't see anything in your example that suggests a way to discriminate between access from within the class and access from outside the class, which is the crucial aspect of data hiding. Carl Banks From gherron at islandtraining.com Fri Jun 6 17:40:39 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 06 Jun 2008 14:40:39 -0700 Subject: Learning which modules were loaded In-Reply-To: References: Message-ID: <4849AED7.9010509@islandtraining.com> James Stroud wrote: > I am rolling up a distribution of a program I wrote. It uses > matplotlib with tkagg so the bundle is HUGE (47 MB, 14 MB after bz > compression). Is there any way to run the program, put it through all > of its paces, and then inspect which modules were loaded. I would like > to gather these in a list and delete any others that py2app and py2exe > attempt to include. Currently, these (or py2app, at least) use > dependency graphing and icnlude everything belonging to pylab, > matplotlib, and numpy by default. I don't want everything, I only want > what my program needs to run. For example, some modules are imported > by functions (in Pmw, for example) that never get called. I don't want > to include these. > > Thanks in advance for any help. > > James > -- > http://mail.python.org/mailman/listinfo/python-list Import sys, then look at sys.modules. It's a dictionary that contains all the imported modules, but I suspect you'll find that it's much easier to let py2app and py2exe determine what's imported than it is to go through sys.modules yourself. Gary Herron From martin at v.loewis.de Tue Jun 17 18:34:32 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 18 Jun 2008 00:34:32 +0200 Subject: PEP 372 -- Adding an ordered directory to collections In-Reply-To: <31defced-c60d-45dc-a32a-af01a2b84c89@2g2000hsn.googlegroups.com> References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <4856e80c$0$30401$9b622d9e@news.freenet.de> <2d1e9b84-3dc7-4822-9c61-73991a527c67@s50g2000hsb.googlegroups.com> <48574b41$0$30410$9b622d9e@news.freenet.de> <31defced-c60d-45dc-a32a-af01a2b84c89@2g2000hsn.googlegroups.com> Message-ID: <48583bf9$0$14752$9b622d9e@news.freenet.de> > I think I have lost the thread here, sorry. So I explain again what I > mean. I think for this data structure it's important to keep all the > normal dict operations at the same speed. If you use a C > implementation vaguely similar to my pure python recipe you can > perform the del in O(1) too, because pairs are joined in (double) > linked list. But such data structure is O(n) to find the n-th item > inserted into the sequence. Right. So byindex(n) would be O(n) then, right? If so, what's the purpose of having that method in the first place? The PEP doesn't give a rationale, but just proposes that the method be there. My guess is that it includes it for performance reasons. However, I think the PEP (author) is misguided in assuming that making byindex() a method of odict, you get better performance than directly doing .items()[n] - which, as you say, you won't. Regards, Martin From bob at mellowood.ca Mon Jun 16 16:47:30 2008 From: bob at mellowood.ca (bvdp) Date: Mon, 16 Jun 2008 13:47:30 -0700 Subject: Simple and safe evaluator Message-ID: Okay guys. I have the _ast based safe eval installed and working in my program. It appears to be working just fine. Thanks for the help. Now, a few more questions: 1. I see that _ast is a 2.5 module?? So, for folks using my code with <2.5 I could do something like this: # I've got some imports here to look after the error() and warning() funcs .... emsg_done = 0 etx = "" def unsafe_eval(s): """ safe eval for < python 2.5 (lacks _ast) """ global emsg_done if not emsg_done: warning("You are using an unsafe eval() function. Please upgrade to Python version 2.5 or greater.") emsg_done=1 # need error trap here as well ... return eval(s, {"__builtins__":None}, {} ) def safe_eval(text): "similar to eval, but only works on numerical values." global etx try: ast = compile(text, "", 'eval', _ast.PyCF_ONLY_AST) except: error("Expression error in '%s'" % text) etx = text # for error reporting, bvdp return _traverse(ast.body) try: import _ast num_eval = safe_eval except: num_eval = unsafe_eval # rest of matt's ast code follows. Which appears to do the following: if there isn't an _ast module we just define an alternate, not-so-safe, function and warn the user; otherwise we use the safe version. I'm a bit uncomfortable with the import _ast being after the function which uses the code, but it seems to work. 2. I thought I'd be happy with * / + -, etc. Of course now I want to add a few more funcs like int() and sin(). How would I do that? Thanks. This is looking very nice indeed. Bob. From mensanator at aol.com Sat Jun 7 21:56:12 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 7 Jun 2008 18:56:12 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> <484ad07b$0$25721$607ed4bc@cv.net> <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> <484b3464$0$25724$607ed4bc@cv.net> Message-ID: <09d98480-c834-42bd-b97f-481133be9cb4@s50g2000hsb.googlegroups.com> On Jun 7, 8:22?pm, John Salerno wrote: > Mensanator wrote: > > What I DID say was that how the builtins actually > > work should be understood and it APPEARED that the > > OP didn't understand that. Maybe he understood that > > all along but his example betrayed no evidence of > > that understanding. > > Well, the truth is that I know zip truncates to the shorter of the two > arguments, Ok, sorry I thought otherwise. > and also in my case the two arguments would always be the > same length. Yes, because you're controlling the source code. But since lists are mutable, source code literals don't always control the length of the list. > But it is still helpful for other people to point out to me > potential problems like this, My intentions were always to be helpful, not arrogant. Otherwise, I'd just tell you to go RTFM. I do seem to have a gift for rubbing people the wrong way. What's important at the end of the day is that you have a working program, right? > so I can be aware of it the next time I > might want to use zip with unequal length arguments. There are, of course, situations where that's desireable, that's why I said such behaviour is by design. It's much easier to debug a program that crahes than one that works but gives you the wrong answer. You'll find the "out of range" errors readily enough, it's when the list is longer than the range and the answer comes up short that are hard to spot. That previous example I gave you? I've run that with a list of over 800,000 numbers, far too many to manually verify. I must have absolute confidence that the algorithm works correctly. That's what you should strive for - confidence that things will work even when you can't manually verify them. From carsten.haese at gmail.com Wed Jun 11 14:05:03 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Wed, 11 Jun 2008 14:05:03 -0400 Subject: problems with opening files due to file's path In-Reply-To: References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> <77acc29a-fffa-44d6-b07b-6bcf8b5bdd74@h1g2000prh.googlegroups.com> Message-ID: Alexnb wrote: > Okay, so as a response to all of you, I will be using the Entry() widget in > Tkinter to get this path. and the repr() function just makes all my > backslashes 4 instead of just 1, and it still screwes it up with the numbers > and parenthesis is has been since the first post. Oh and I know all about > escape characters, (\n,\b,\a,etc.) I can program C, not a lot, but enough to > know that I like python better. Anyway, so far I tried all of your stuff, > and it didn't work. infact, it puts backslashes in front of the "'" in some > of the words, such as "I'm" goes to "I\'m." So I posted the code I will be > using if you want to see the Tkinter code I can post it, but I don't see how > it will help. Your reluctance to post your code puzzles me. Several people have asked you several times to post your code. We're not doing this to waste your time. In fact, your reluctance to post your code wastes your time and our time by making us guess. Seeing your code should enable us to see exactly what the problem is. Your vague descriptions of what's going on are not useful because they are filtered through your inaccurate understanding of what's going on. I mean no offense by this, but if your understanding were accurate, you wouldn't be here asking for help. So, if you want us to help you, please humor us and post the actual code that gets the filename from the user and attempts to open the file. Also tell us what input you're entering and the output the code produces. -- Carsten Haese http://informixdb.sourceforge.net From maric at aristote.info Fri Jun 27 03:34:22 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 27 Jun 2008 09:34:22 +0200 Subject: Email Bounce Detection In-Reply-To: References: Message-ID: <200806270934.23395.maric@aristote.info> Le Friday 27 June 2008 09:03:15 madhav, vous avez ?crit?: > Hello everybody, I need a mechanism to detect email bounces. I tried > browsing through smtplib implementation and found not helpful in this > case. Actually it is said in the documentation that if a mail is sent > to say: "somerandomname at randomorg.com", then "_send()" in the > SMTPConnection class returns 550(Unknown recceipient). I checked the > same but its not returning 550 and return 250(receipient ok). This is not the same scenario, the SMTP server that will respond 550 is the MX for the domain, if you send your mails using an outgoing SMTP server, it can't know in advance the list of remote adressesbut will bounce your message when receiving the 550 from the remote MX. > Later, I tried getting the smtp error code from the mail body of a > bounced msg. the "Message" class doesnot have any error code attribute > by default. We need to get it from the mailbody(by regex ing), which i > think is not a valid solution, as "550" can occur anywhere in the body > of any message otherthan the bounced msg also. > Please help me regarding this. > Thanks in advance. Bounces are multipart messages easily parsed with the email package of the stdlib (dont' use regexes here). Abounce message is of type : Content-Type: multipart/report; report-type=delivery-status; a delivery-status imply that one of the subpart of the message is a message/delivery-status with all needed infos set in the headers. This one is taken from a real example : Content-Description: Delivery report Content-Type: message/delivery-status Reporting-MTA: dns; aristote.info X-Postfix-Queue-ID: 1D07D1409FF X-Postfix-Sender: rfc822; maric at aristote.info Arrival-Date: Fri, 27 Jun 2008 09:10:14 +0200 (CEST) Final-Recipient: rfc822; unknownadress at nerim.net Original-Recipient: rfc822;unknownadress at nerim.net Action: failed Status: 5.0.0 Remote-MTA: dns; tyrande.nerim.net Diagnostic-Code: smtp; 550 : Recipient address rejected: User unknown in local recipient table So, for example : >>>[48]: import email >>>[49]: bounce = email.message_from_string(open('ex.eml').read()) >>>[50]: bounce.get_content_type() ...[50]: 'multipart/report' >>>[51]: >>>[52]: for i in bounce.get_payload() : ....: if i.get_content_type() == 'message/delivery-status' : ....: print i.get_payload()[1]['status'] ....: ....: 5.0.0 -- _____________ Maric Michaud From Lie.1296 at gmail.com Mon Jun 9 18:02:16 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 9 Jun 2008 15:02:16 -0700 (PDT) Subject: Question by someone coming from C... References: <9d40211d-e03f-4f0c-a512-3ac78b0ede21@i18g2000prn.googlegroups.com> <4789a069-1038-4ee2-a2d6-933a9eaf6e2e@s21g2000prm.googlegroups.com> Message-ID: <94256cb0-cdb3-45ba-b7b7-b6fc53366270@w4g2000prd.googlegroups.com> On Jun 10, 4:32?am, Skye wrote: > OK, sounds good. ?So if not bitfields, what would be a good Python-y > way to do it? The word is "pythonic". > Flip booleans in a "debug config" dictionary or something? I'm not really sure, I've been programming with Python (and some other languages) but never really felt the need to store data in such super- efficient manners. I reckon a dict should do the job and it would be easier to read too compared to bitfield, since dict's entry is named. Actually, in python I usually do not put debugging codes before entering debugging cycle, and I usually remove all those debugging codes when the debugging cycle has finished (I'm talking for myself, not the whole python community). > Skye From cs at zip.com.au Wed Jun 25 23:32:12 2008 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 26 Jun 2008 13:32:12 +1000 Subject: struct.pack behavior In-Reply-To: Message-ID: <20080626033212.GA5526@cskk.homeip.net> On 25Jun2008 22:38, Steven Clark wrote: | On Wed, Jun 25, 2008 at 7:03 PM, John Machin wrote: | > On Jun 26, 9:00 am, "Steven Clark" wrote: | >> Can anyone explain to me why | >> struct.pack('HB',1,2) gives 3 bytes, whereas struct.pack('BH',1,2) | >> gives 4 bytes? | >> | > Alignment -- read the manual. | | If "the manual" is the help files for the struct module, I've read it | several times over. I understand endianness; I don't understand | alignment. Could anyone give a less cryptic / terse answer? For efficiency reasons many CPUs require particular primitive data types (integers/pointers of various sizes) to be placed in memory at particular boundaries. For example, shorts ("H" above, usually two bytes and probably always so in the struct module) are often required to be on even addresses, and longer objects to be on 4 or 8 byte boundaries. This allows for much more efficient memory access on many platforms (of course the rules depend on the platform). Although RAM _appears_ to the random access to arbitrary bytes, the underlying hardware will often fetch chunks of bytes in parallel. If a number spanned the boundaries of such a chunk it would require two fetch cycles instead of one. So this is avoided for performance reasons. So, packing "HB" puts a short at offset 0 (even) and then a byte. Conversely, packing "BH" puts a byte at offset zero but puts the short at offset 2 (to be even), leaving a gap after the byte to achieve this, thus the 4 byte size of the result (byte, gap, short). This layout procedure is called "alignment". Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Kilimanjaro is a pretty tricky climb. Most of it's up, until you reach the very, very top, and then it tends to slope away rather sharply. From gongchangzhaojie at gmail.com Wed Jun 4 18:50:44 2008 From: gongchangzhaojie at gmail.com (Zhaojie Boulder) Date: Wed, 4 Jun 2008 16:50:44 -0600 Subject: gcc error in Mac OS X Message-ID: <12956470806041550k7e2815b4ga6823ee7967a8718@mail.gmail.com> Hello, I am new to Mac and used python in linux before. What I am trying to do is to install "Ipython" and "PyCogent" in Mac OS X. For PyCogent, after entering the package path, I typed "python setup.py install". The results are as follows: Didn't find Pyrex - will compile from .c files running install running build running build_py running build_ext building 'cogent.align._compare' extension gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DMACOSX -I/usr/include/ffi -DENABLE_DTRACE -arch i386 -arch ppc -pipe -I/Users/zhaojie/Downloads/PyCogent-1.0.1/include -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -c cogent/align/_compare.c -o build/temp.macosx-10.5-i386-2.5/cogent/align/_compare.o -w unable to execute gcc: No such file or directory error: command 'gcc' failed with exit status 1 After google, I installed Xcode,but it did not help. Also, the Xcode folder is not within "applications" folder, but a separate one parallel with "applications". Dragging Xcode folder into the applications folder did not make a difference, either. Hope someone familiar with Mac can help me out. Thank you, Jie -------------- next part -------------- An HTML attachment was scrubbed... URL: From yxs008 at gmail.com Mon Jun 30 02:27:38 2008 From: yxs008 at gmail.com (yxs008 at gmail.com) Date: Sun, 29 Jun 2008 23:27:38 -0700 (PDT) Subject: Chanel shoes - Best High Quality Chanel shoes www.luxury-gift.org Message-ID: Chanel shoes - Best High Quality Chanel shoes www.luxury-gift.org Luxury Gift : http://www.luxury-gift.org Chanel shoes : http://www.luxury-gift.org/Shoes/Chanel-shoes.html Chanel shoes series contain the following items, each item is the perfect marriage of function and design. Chanel shoes are finely copied, you don't need to worry about the quality. We believe that no matter what you're looking for in a watch, our Chanel shoes will exceed your expectations. Explore the World of Brand Watches & Handbags It is a well-known fact that a watch you wear not just serves as a faithful time keeping device,but is also associated with your social status.style and evenframe of mind.If you intend tomake a wise choice as for purchasing awatch just right for you,devote your attention to awide range of high quality brand watches . The Best Chanel shoes Series : Chanel shoes All Products : Chanel shoes RCS001, Chanel shoes RCS002, Chanel shoes RCS003, Chanel shoes RCS004, Chanel Boots CS001, Chanel Boots CS002, Chanel Boots CS003, Chanel Boots CS004, Chanel Shoes CS005, Chanel Shoes CS006, Chanel Shoes CS007, Chanel Shoes CS008, Chanel Shoes CS009, chanel shoes RCS0711001, chanel shoes RCS0711002, chanel shoes RCS0711003, chanel shoes RCS0711004, chanel shoes RCS0711005, chanel shoes RCS0711006, chanel shoes RCS0711007, chanel shoes RCS0711008, chanel shoes RCS0711009, chanel shoes RCS0711010, chanel shoes RCS0711011, chanel shoes RCS0711012, chanel shoes RCS0711013, chanel shoes RCS0711014, chanel shoes RCS0711015, chanel shoes RCS0711016, chanel shoes RCS0711017, chanel shoes RCS0711018, chanel shoes RCS0711019, Chanel Shoes CAS0802001, Chanel Shoes CAS0802002, Chanel Shoes CAS0802003, Chanel Shoes CAS0802004, Chanel Shoes CAS0802005, Chanel Shoes CAS0802006, Chanel Shoes CAS0802007, Chanel Shoes CAS0802008, Chanel Shoes CAS0802009, Chanel Shoes CAS0802010, Chanel Shoes CAS0802011, Chanel Shoes CAS0802012, Chanel Shoes CAS0802013, Chanel Shoes CAS0802014, chanel shoes CAS0803001, chanel shoes CAS0803002, chanel shoes CAS0803003, chanel shoes CAS0803004, chanel shoes CAS0803005, chanel shoes CAS0803006, chanel shoes CAS0803007, chanel shoes CAS0803008, chanel shoes CAS0803009, chanel shoes CAS0803010, chanel shoes CAS0803011, chanel shoes CAS0803012, chanel shoes CAS0803013, chanel shoes CAS0803014, chanel shoes CAS0803015, Chanel shoes : http://www.luxury-gift.org/Shoes/Chanel-shoes.html From stephan at transvection.de Mon Jun 9 03:34:41 2008 From: stephan at transvection.de (Stephan Diehl) Date: Mon, 09 Jun 2008 09:34:41 +0200 Subject: Access to CAN-Bus In-Reply-To: <484cd469$0$28520$3b214f66@aconews.univie.ac.at> References: <484cd469$0$28520$3b214f66@aconews.univie.ac.at> Message-ID: Thin Myrna schrieb: > I'd like to access some drive hardware via CAN bus from Python under Linux > (sending rec'ing PDOs). Googling around I couldn't find a Python package, > but people who said that they are doing this, though. I guess they are > using their home brewn software. > > Any pointer to > - such software (anyone willing to share his experience?) > - how to write such software? > > Under Windows, I guess, I could use some COM or ctypes functionality to > access the hardware vendor's hardware. What if I wanted to access such > hardware from Linux? Is there a package that allows that in a vendor (who > doesn't support Linux) independent way? > > Many thanks in advance > Thin We've done this once (sorry no open source). If I remember right, we've been using ctypes on windows to access the CAN card. If I had to do something like this again, I'd definatelly check out an USB CAN adapter which might be easier to handle (but one never knows). Stephan From Hughjar700 at gmail.com Tue Jun 24 20:24:17 2008 From: Hughjar700 at gmail.com (Hughjar700 at gmail.com) Date: Tue, 24 Jun 2008 17:24:17 -0700 (PDT) Subject: Porn Addiction Message-ID: <0bc1d618-f140-4390-9dd0-4ade923ab054@w1g2000prd.googlegroups.com> Help, I'm addicted to porn. I've been downloading porn online and masturbating to it for a few years... Lately it's gotten even worse, I spend hours and hours surfing and masturbating to it. It's taking over my life and ruining everything.. I even missed days from work because of this addiction. I'm going to the porn as a way to avoid unwanted feelings or procrastination and then it just takes over. What can I do to end this horrible addiction? -Hugh From alexnbryan at gmail.com Tue Jun 10 21:55:25 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 10 Jun 2008 18:55:25 -0700 (PDT) Subject: problems with opening files due to file's path In-Reply-To: References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> Message-ID: <17768511.post@talk.nabble.com> Okay, I don't understand how it is too vague, but here: >>> path = "C:\Documents and Settings\Alex\My Documents\My >>> Music\Rhapsody\Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm >>> Yours.wma" >>> os.startfile(path) Traceback (most recent call last): File "", line 1, in os.startfile(path) WindowsError: [Error 2] The system cannot find the file specified: "C:\\Documents and Settings\\Alex\\My Documents\\My Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\x01 - I'm Yours.wma" Here's another way: >>> os.startfile(r"%s"%path) Traceback (most recent call last): File "", line 1, in os.startfile(r"%s"%path) WindowsError: [Error 2] The system cannot find the file specified: "C:\\Documents and Settings\\Alex\\My Documents\\My Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\x01 - I'm Yours.wma" Same output, however if I personally input it like so: >>> os.startfile("C:\\Documents and Settings\\Alex\\My Documents\\My >>> Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\\01 - I'm >>> Yours.wma") It works out fine because I can make each backslash doubles so it doesn't mess stuff up. So if I could take the path varible and make ever "\" into a "\\" then it would also work. Did I clarify? Grant Edwards wrote: > > On 2008-06-11, Alexnb wrote: > >> I am using GUI, Tkinter to be exact. But regardless of how the >> path gets there, it needs to opened correctly. The problem I >> am running into is that the program receives a path of a file, >> either .wma or .mp3 and is supposed to open it. I run into >> problems when there is either a ")" or a number next to the >> backslash "\" in the file path. I am looking for a way to make >> it work with a variable, I can make it work when I physically >> type it in, but not with a variable that holds the path. > > You're going to have to show us code and example input and > output. Your description of the problem is far too vague for > anybody to help you. > > -- > Grant Edwards grante Yow! With YOU, I can > be > at MYSELF... We don't NEED > visi.com Dan Rather... > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17768511.html Sent from the Python - python-list mailing list archive at Nabble.com. From timr at probo.com Wed Jun 11 02:05:03 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 11 Jun 2008 06:05:03 GMT Subject: time.clock() or Windows bug? References: <0uep44hpn8rupgr15a135f37q346tif9v2@4ax.com> Message-ID: Nick Craig-Wood wrote: > >Hmmm, 10,000,000 cycles (40 ms @2.5GHz) is nowhere near the ~90,000 >second jump in time.clock() output reported by the OP. I wonder if >there could be a different cause? Just wild theorizing, but it's possible that they are actually getting a negative delta, and some kind of signed/unsigned manipulation produces the 90,000 number. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From johnjsal at gmailNOSPAM.com Mon Jun 16 23:40:14 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Mon, 16 Jun 2008 23:40:14 -0400 Subject: Does '!=' equivelent to 'is not' In-Reply-To: References: Message-ID: <4857321f$0$11606$607ed4bc@cv.net> pirata wrote: > I'm a bit confusing about whether "is not" equivelent to "!=" > > if a != b: > ... > > if a is not b: > ... > > > What's the difference between "is not" and "!=" or they are the same thing? No, they are not the same thing. == and != test to see if the *value* of two variables are the same. Like so: >>> a = 'hello world' >>> b = 'hello world' >>> a == b True a and b both have the value of 'hello world', so they are equal is and is not, however, do not test for value equivalence, they test for object identity. In other words, they test to see if the object the two variables reference are the same object in memory, like so: >>> a is b False a and b are assigned to two different objects that happen to have the same value, but nevertheless there are two separate 'hello world' objects in memory, and therefore you cannot say that a *is* b Now look at this: >>> c = d = 'hello world' >>> c == d True >>> c is d True In this case, they are again the same value, but now the is test also shows that they are the same *object* as well, because both c and d refer to the same 'hello world' object in memory. There is only one this time. != and is not work the same: >>> a != b False >>> a is not b True >>> c != d False >>> c is not d False >>> Hope that helps! From gagsl-py2 at yahoo.com.ar Tue Jun 17 03:46:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 17 Jun 2008 04:46:38 -0300 Subject: print problem References: <2MWdnYXqCY3yy8rVnZ2dnUVZ_sbinZ2d@posted.internode> <48576371.7000209@gmail.com> Message-ID: En Tue, 17 Jun 2008 04:10:41 -0300, Rich Healey escribi?: > Gabriel Genellina wrote: >> En Tue, 17 Jun 2008 03:15:11 -0300, pirata escribi?: >> >>> I was trying to print a dot on console every second to indicates >>> running process, so I wrote, for example: >>> >>> for i in xrange(10): >>> print ".", >>> time.sleep(1) >>> >>> Idealy, a dot will be printed out each second. But there is nothing >>> print out until after 10 seconds, all 10 dots come out together. >>> >>> I've tried lose the comma in the print statement, and it works. >>> >>> Is that because of the print statement buffer the characters until >>> there is a new line character? >> >> Very probably, altough I can't reproduce it on Windows. Try invoking the script with python -u (unbuffered input/output): >> >> python -u your_script.py >> > Or just write to sys.stdout without the print wrapper.. I think the output is still buffered, even if you write directly to sys.stdout, but I don't have a Linux box to test right now. -- Gabriel Genellina From shank.nasa at gmail.com Mon Jun 30 14:46:07 2008 From: shank.nasa at gmail.com (Shankar Narayana) Date: Mon, 30 Jun 2008 14:46:07 -0400 Subject: Query regarding PythonQt In-Reply-To: <3231b5170806271141o38e7c2fcqffe7ecab04d33590@mail.gmail.com> References: <3231b5170806271141o38e7c2fcqffe7ecab04d33590@mail.gmail.com> Message-ID: <3231b5170806301146y6e530920o14123c863eba86ae@mail.gmail.com> Hi, After a big fight, I could get through the problem. I am posting it so that others does not waste time solving the issue. I dont know why "evalfile" method is having problems with existing .pyc files. But, we can solve it this way. First create your .cpp and .py file in directory. Then, do the following 1. Create somename.qrc file Filename.py 2. Navigate to the directory . Type the command: qmake -project (It creates project (.pro) file) 3. Next command: qmake (It creates a make file). 4. Then update the makefile INCPATH to add for Python and Python-Qt -I/usr/include/python2.5 -I/home/workspace/PythonQt-1.0/src 5. Update the LIBS -L/usr/lib/python2.5/config/libpython2.5.a -L/home/workspace/PythonQt-1.0/lib -lpython2.5 -lPythonQt WARNING: Always use ":" in your cpp file eval command. Then only Qrc will be used to create the corresponding. pyc file. Otherwise, the terminal will crash. Now issue the command "make" and run your application. Things work fine now. I am not very clear with QRC but its a very good solution. Rgds, Shankar On Fri, Jun 27, 2008 at 2:41 PM, Shankar Narayana wrote: > Hi, > I am newbie to PythonQt. I wanted to access the Qt objects created in C++ > using Python and update things. I had a look at this URL " > http://doc.trolltech.com/qq/qq23-pythonqt.html#decoratorsandcwrappers" > which talks about using PythonQt for the same. > I followed the instructions given in the example. I created my cpp file > and .py file and could make them working. > But once after the first time after .pyc file is created, my program no > longer executes. It is giving me a segmentation fault. If I remove my .pyc > file and run the program, things work fine. > > My cpp file > #include > #include > #include "PythonQt.h" > int main(int argc, char* argv[]) > { > QApplication app(argc,argv); > QTextEdit *welcomemsg = new QTextEdit("Hi whatsup"); > PythonQt::init(); > PythonQtObjectPtr mainModule = PythonQt::self()->getMainModule(); > mainModule.addObject("welcomemsg",welcomemsg); // Check with different > names > mainModule.evalFile("Pyscript.py"); > mainModule.removeVariable("welcomemsg"); > PythonQt::cleanup(); > return app.exec(); > } > > My Python file (Pyscript.py) > > from PythonQt import * > #append the text to the existing text edit > welcomemsg.append("Hurray I did it") > welcomemsg.show() > > Can somebody help me what makes this not to run once Python interpreter > works on the Python file and creates a .pyc file ? > > > Regards, > Shankar > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at gmail.com Fri Jun 6 02:36:33 2008 From: cwitts at gmail.com (Chris) Date: Thu, 5 Jun 2008 23:36:33 -0700 (PDT) Subject: readline() & seek() ??? References: <12655f64-33b1-4ab0-b6fb-294bfd2fa8c6@d45g2000hsc.googlegroups.com> Message-ID: <078bfcbf-4f6c-459c-9f68-619af24c3678@27g2000hsf.googlegroups.com> On Jun 6, 5:13?am, Kam-Hung Soh wrote: > Tim Roberts wrote: > > DataSmash wrote: > >> I have a text file that contains thousands of lines and each line is > >> 256 characters long. > > >> This is my task: > >> For each line in the file, move to the 25th character, if the > >> character is a "T", > >> move to the 35th character of the line and read 5 characters from > >> there. > >> Capture these 5 characters and write them to a new text file, each 5 > >> characters separated by a comma. > > >> I appreciate your help! > > > Did you even TRY this? ?Your task reads like pseudocode that translates > > virtually line-for-line to Python code. > > > ? fout = open('outputfile.txt','w') > > ? for line in open('inputfile.txt'): > > ? ? ? if line[24] == 'T': > > ? ? ? ? ? fout.write( line[34:39] + ',' ) > > Should the last line be ... > > fout.write(','.join(line[34:39]) > > -- > Kam-Hung Soh Software Salariman each 5 characters need to be delimited by a comma, your statement would have a comma between each of the 5 characters. From auch-ich-m at g-kein-spam.com Thu Jun 19 15:46:50 2008 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Thu, 19 Jun 2008 21:46:50 +0200 Subject: regex \b behaviour in python References: Message-ID: <24284438.YDfgAvrJ06@news.perlig.de> * Walter Cruz wrote: > irb(main):001:0>"walter ' cruz".split(/\b/) > => ["walter", " ' ", "cruz"] > > and in php: > > Array > ( > [0] => > [1] => walter > [2] => ' > [3] => cruz > [4] => > ) > > > But in python the behaviour of \b is differente from ruby or php. My python here does the same, actually: $ cat foo.py import re x = "walter ' cruz" s = 0 r = [] for m in re.finditer(r'\b', x): p = m.start() if s != p: r.append(x[s:p]) s = p print r $ python2.4 foo.py ['walter', " ' ", 'cruz'] $ python2.5 foo.py ['walter', " ' ", 'cruz'] $ nd -- $_=q?tvc!uif)%*|#Bopuifs!A`#~tvc!Xibu)%*|qsjou#Kvtu!A`#~tvc!KBQI!)*|~ tvc!ifmm)%*|#Qfsm!A`#~tvc!jt)%*|(Ibdlfs(~ # What the hell is JAPH? ; @_=split/\s\s+#/;$_=(join''=>map{chr(ord( # Andr? Malo ; $_)-1)}split//=>$_[0]).$_[1];s s.*s$_see; # http://pub.perlig.de/ ; From CracKPod at googlemail.com Sat Jun 28 02:55:01 2008 From: CracKPod at googlemail.com (CracKPod) Date: Fri, 27 Jun 2008 23:55:01 -0700 (PDT) Subject: More on Urllib, and Urllib2 References: Message-ID: On 28 Jun., 01:42, Alex Bryan wrote: > Okay, so I am having issues figuring anything out about this and have ? > read the "missing manual" about it so please don't send me that link ? > again. To put it simply I want to be able to input a word and get the ? > definition from dictionary.com. Now I found a work-around for ? > searching for the word, I just make it in the actual address. For ? > example I want to search for cheese, I can just do a: > > urllib2.urlopen("http://dictionary.reference.com/browse/cheese") > > However, the actual definition is in javascript on the page. I used ? > firebug to see it, and the first def, looks like this: > > > > > > > > the problem being that if I use code like this to get the html of that ? > page in python: > > response = urllib2.urlopen("the webiste....") > html = response.read() > print html > > I get the html source of the page, but no table with my definitions. ? > So what can I do? Also, is there a book or a better tutorial or ? > explanation of this urllib2, and urllib? If so, PLEASE let me know ? > about it; I will be eternally grateful. It would probably be a good idea to take a look at mechanize: http://wwwsearch.sourceforge.net/mechanize/ and at BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/ Greetz, CracKPod From cricket.keith at gmail.com Wed Jun 11 12:46:31 2008 From: cricket.keith at gmail.com (Keith Nation) Date: Wed, 11 Jun 2008 11:46:31 -0500 Subject: Reading info from an active file In-Reply-To: <21935b370806110940y3c4f4a33l8fd06ad679fb6863@mail.gmail.com> References: <21935b370806110940y3c4f4a33l8fd06ad679fb6863@mail.gmail.com> Message-ID: <21935b370806110946g7c8c1115p5b1a8ff1d914ec4f@mail.gmail.com> I have a program that writes a log file as it is running to give status of the job. I would like to read that file, pull certain lines of text from it, and write to a new file. Because I am such a novice user, I was hoping someone had covered this before and could let me know of your methods. If I open and close the file repeatedly to get refreshed information, I assume it would slow the system down. Any thoughts? Keith Nation -------------- next part -------------- An HTML attachment was scrubbed... URL: From larry at portcommodore.com Sun Jun 29 23:47:01 2008 From: larry at portcommodore.com (larry at portcommodore.com) Date: Sun, 29 Jun 2008 20:47:01 -0700 (PDT) Subject: help debugging noob code - converting binary data to images... References: <56955a42-155c-4c37-9bf6-5a99cadb5c79@l42g2000hsc.googlegroups.com> <8a9b4e80-45cf-4145-85c0-94d2f2a04aa4@j22g2000hsf.googlegroups.com> Message-ID: success, had to fill in a few blanks with some more googling, here is the finished script (used all for loops this time, saved a few more lines): ========== #!/usr/local/bin/python import string import Image, ImageDraw size = 2 im = Image.new("1",[8*size,8*size],1) draw = ImageDraw.Draw(im) cset = open("chargen","r") for cchar in range(0, 512, 1): for charline in range(0, 8, 1): x = cset.read(1) ch = ord(x) for position in range(0, 8, 1): if ch & ( 2 ** position ): xp = (7-position)*size yp = charline*size draw.rectangle(((xp,yp),(xp+size-1,yp+size-1)), fill=0 ) outfile = "/home/mydir/work/char"+string.zfill(cchar,3)+".png" im.save(outfile,"png") draw.rectangle(((0,0),(size*8,size*8)),fill=1) im.show() ========== It does the variable sizes like I wanted and it now sure is fast. If I wanted to display an image without saving how do I do that, on the image module it does not pop up a canvas.. the im.show() on the bottom does not seem to work. Thanks again! From hat at se-162.se.wtb.tue.nl Wed Jun 25 06:37:43 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 25 Jun 2008 12:37:43 +0200 Subject: insertion sorts... References: <06adb999-c7e2-4475-a49f-dbfbe042f4fd@r66g2000hsg.googlegroups.com> <5f0111a3-c1b9-4864-bae3-32fa324c4e5e@j22g2000hsf.googlegroups.com> <841dd5b8-d99d-4a60-ad39-b7c9563fca1d@d1g2000hsg.googlegroups.com> Message-ID: On 2008-06-25, python_newbie wrote: > On 24 Haziran, 04:33, Terry Reedy wrote: > Thanks for all answers. At the end i ve only one point. If a decide to > copy list to iterate when will i have to do this ? Before the > iteration ? And then iterate through one list and change value of the > other ? Before starting the iteration would be a good point.... I usually do in such cases: for x in mylist[:]: ... making a copy just before the for loop starts. Lately, I have started avoiding in-place modification of lists. Instead, I construct a new list from scratch inside the for-loop, and replace the old list with the newly constructed list afterwards like: new_list = [] for x in mylist: .... new_list.append(x) mylist = new_list by appending a different value than the original or by not appending, you can influence the contents of the new list. I find this solution nicer than in-place modification of an existing list. Sincerely, Albert From dyamins at gmail.com Fri Jun 13 19:01:56 2008 From: dyamins at gmail.com (Dan Yamins) Date: Fri, 13 Jun 2008 19:01:56 -0400 Subject: A package import question Message-ID: <15e4667e0806131601r14759c54jac431a8fc531414d@mail.gmail.com> I'm having a problem importing a package in python, deleting some of what's been imported, and then reimporting. (I'm the sure the problem is trivial, but I just don't understand it.) I have a directory of python modules called Operations. It contains a python module called archive.py. Here's a import of the archive module via package import: Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import Operations.archive >>> Operations.archive So far, so good. But now, suppose I want to delete Operations.archive. then, I can't reimport it. instead, I >>> del Operations.archive >>> import Operations.archive >>> dir() ['Operations', '__builtins__', '__doc__', '__name__'] >>> Instead of getting 'Operations.archive', I just seem to get 'Operations'. I can't seem to be able to import Operations.archive without quitting the python interpreter and starting again. What's going on here, and how do I fix it? Thanks, Dan -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Mon Jun 30 20:24:18 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 30 Jun 2008 17:24:18 -0700 (PDT) Subject: Looping-related Memory Leak References: <94312edc-babb-4c1b-8db1-233404aa4a02@i76g2000hsf.googlegroups.com> <0abf2145-231c-4189-a8ca-b1f327a735dd@a1g2000hsb.googlegroups.com> <1e36866c-4a94-40b6-9780-81e104286862@d1g2000hsg.googlegroups.com> Message-ID: On Jun 30, 1:55 pm, Tom Davis wrote: > On Jun 26, 5:38 am, Carl Banks wrote: > > > > > On Jun 26, 5:19 am, Tom Davis wrote: > > > > I am having a problem where a long-running function will cause a > > > memory leak / balloon for reasons I cannot figure out. Essentially, I > > > loop through a directory of pickled files, load them, and run some > > > other functions on them. In every case, each function uses only local > > > variables and I even made sure to use `del` on each variable at the > > > end of the loop. However, as the loop progresses the amount of memory > > > used steadily increases. > > > Do you happen to be using a single Unpickler instance? If so, change > > it to use a different instance each time. (If you just use the module- > > level load function you are already using a different instance each > > time.) > > > Unpicklers hold a reference to everything they've seen, which prevents > > objects it unpickles from being garbage collected until it is > > collected itself. > > > Carl Banks > > Carl, > > Yes, I was using the module-level unpickler. I changed it with little > effect. I guess perhaps this is my misunderstanding of how GC works. > For instance, if I have `a = Obj()` and run `a.some_method()` which > generates a highly-nested local variable that cannot be easily garbage > collected, it was my assumption that either (1) completing the method > call or (2) deleting the object instance itself would automatically > destroy any variables used by said method. This does not appear to be > the case, however. Even when a variable/object's scope is destroyed, > it would seem t hat variables/objects created within that scope cannot > always be reclaimed, depending on their complexity. > > To me, this seems illogical. I can understand that the GC is > reluctant to reclaim objects that have many connections to other > objects and so forth, but once those objects' scopes are gone, why > doesn't it force a reclaim? Are your objects involved in circular references, and do you have any objects with a __del__ method? Normally objects are reclaimed when the reference count goes to zero, but if there are cycles then the reference count never reaches zero, and they remain alive until the generational garbage collector makes a pass to break the cycle. However, the generational collector doesn't break cycles that involve objects with a __del__method. Are you calling any C extensions that might be failing to decref an object? There could be a memory leak. Are you keeping a reference around somewhere. For example, appending results to a list, and the result keeps a reference to all of your unpickled data for some reason. You know, we can throw out all these scenarios, but these suggestions are just common pitfalls. If it doesn't look like one of these things, you're going to have to do your own legwork to help isolate what's causing the behavior. Then if needed you can come back to us with more detailed information. Start with your original function, and slowly remove functionality from it until the bad behavior goes away. That will give you a clue what's causing it. Carl Banks From bj_666 at gmx.net Wed Jun 4 00:51:34 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 4 Jun 2008 04:51:34 GMT Subject: Q about object identity References: Message-ID: <6amlamF38poe2U1@mid.uni-berlin.de> On Tue, 03 Jun 2008 23:08:46 +0200, Christian Heimes wrote: > vronskij at gmail.com schrieb: >> Hello, >> >> I am testing object identity. >> >> If I do it from the interpreter, I get strange results. >> >>>>> print [] is [] >> False >> >>>>> print id([]), id([]) >> 3083942700 3083942700 >> >> >> >> Why is that? Isn't this an error? > > No, it's not an error. You are getting this result because the list > implementation keeps a bunch of unused list objects in a free list. It's > an optimization trick. Python has to create two different list objects > for "[] is []" while it can reuse the same list object for id([]) == id([]). I don't think you need optimization tricks for the explanation. In ``[] is []`` there need to be two lists that exist at the same time to be compared by the ``is`` operator. With ``id([]) == id([])`` just the id numbers have to exist at the same time, so the execution may look like this: ? create empty list ? call `id()` with it ? remember first id number ? when `id()` returns, the list is not referenced anymore and can be garbage collected ? create empty list, and here the list object might get allocated at the same memory location as the first empty list ? same id. ? call `id()` with it ? remember second id number ? garbage collect second empty list ? compare both numbers Ciao, Marc 'BlackJack' Rintsch From arslanburney at gmail.com Fri Jun 13 02:15:36 2008 From: arslanburney at gmail.com (arslanburney at gmail.com) Date: Thu, 12 Jun 2008 23:15:36 -0700 (PDT) Subject: Creating a st line after a specific point in Gnuplot Message-ID: <226801d7-0987-4020-bb8e-c300a6fff5c0@i76g2000hsf.googlegroups.com> While using gnuplot.py if id want to make a straight line supposingly y = 3 after the point (2,3) (a point on another line) with the same color as that of the line how wud i do that? From pistacchio at gmail.com Wed Jun 25 06:34:23 2008 From: pistacchio at gmail.com (pistacchio) Date: Wed, 25 Jun 2008 03:34:23 -0700 (PDT) Subject: Apache2 + Python WITHOUT mod_pytho References: <4f90e1e5-056e-4f61-866b-015a15030ebf@e39g2000hsf.googlegroups.com> Message-ID: <4b94d5b3-3f8d-4d48-af96-f7bc14ce8f2f@25g2000hsx.googlegroups.com> Solved. Here my new /etc/apache2/sites-available/default __________________________ NameVirtualHost * ServerAdmin webmaster at localhost DocumentRoot /var/www/ Options FollowSymLinks AllowOverride None AddHandler cgi-script .py Options ExecCGI Indexes FollowSymLinks MultiViews #Options All AllowOverride None Order allow,deny allow from all #AddHandler mod_python .py #PythonHandler mod_python.publisher #PythonDebug On ErrorLog /var/log/apache2/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/apache2/access.log combined ServerSignature On Alias /doc/ "/usr/share/doc/" Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 __________________________ On 25 Giu, 11:13, pistacchio wrote: > Hi to all! > How can i configure apache2 so that it processes all .py files with > python _without_ using mod_python? > I'm on Ubuntu 8.4. > > currently my /etc/apache2/sites-available/default file reads: > > __________________________ > NameVirtualHost * > > ? ? ? ? ServerAdmin webmaster at localhost > > ? ? ? ? DocumentRoot /var/www/ > ? ? ? ? > ? ? ? ? ? ? ? ? Options FollowSymLinks > ? ? ? ? ? ? ? ? AllowOverride None > ? ? ? ? > ? ? ? ? > ? ? ? ? ? ? ? ? #Options +ExecCGI Indexes FollowSymLinks MultiViews > ? ? ? ? ? ? ? ? Options All > ? ? ? ? ? ? ? ? AllowOverride None > ? ? ? ? ? ? ? ? Order allow,deny > ? ? ? ? ? ? ? ? Allow from all > ? ? ? ? ? ? ? ? #AddHandler mod_python .py > ? ? ? ? ? ? ? ? #PythonHandler mod_python.publisher > ? ? ? ? ? ? ? ? #PythonDebug On > > ? ? ? ? > > ? ? ? ? ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ > ? ? ? ? > ? ? ? ? ? ? ? ? AllowOverride None > ? ? ? ? ? ? ? ? Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch > ? ? ? ? ? ? ? ? Order allow,deny > ? ? ? ? ? ? ? ? Allow from all > ? ? ? ? > > ? ? ? ? ErrorLog /var/log/apache2/error.log > > ? ? ? ? # Possible values include: debug, info, notice, warn, error, > crit, > ? ? ? ? # alert, emerg. > ? ? ? ? LogLevel warn > > ? ? ? ? CustomLog /var/log/apache2/access.log combined > ? ? ? ? ServerSignature On > > ? ? Alias /doc/ "/usr/share/doc/" > ? ? > ? ? ? ? Options Indexes MultiViews FollowSymLinks > ? ? ? ? AllowOverride None > ? ? ? ? Order deny,allow > ? ? ? ? Deny from all > ? ? ? ? Allow from 127.0.0.0/255.0.0.0 ::1/128 > ? ? > > > __________________________ > > Thanks in advance > Gustavo From pedrof.abranches at gmail.com Sun Jun 22 17:13:33 2008 From: pedrof.abranches at gmail.com (abranches) Date: Sun, 22 Jun 2008 14:13:33 -0700 (PDT) Subject: Regular expression problem Message-ID: <181fe17d-61f0-40f4-89b4-99fe4c483bf7@k30g2000hse.googlegroups.com> Hello everyone. I'm having a problem when extracting data from HTML with regular expressions. This is the source code: You are ready in the next
    12M 48S And I need to get the remaining time. Until here, isn't a problem getting it, but if the remaining time is less than 60 seconds then the source becomes something like this: You are ready in the next
    36S I'm using this regular expression, but the minutes are always None... You are ready in the next.*?(?:>(\d+)M
    )?.*?(?:>(\d+)S) If I remove the ? from the first group, then it will work, but if there are only seconds it won't work. I could resolve this problem in a couple of python lines, but I really would like to solve it with regular expressions. Thanks, Pedro Abranches From __peter__ at web.de Tue Jun 17 03:42:59 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 17 Jun 2008 09:42:59 +0200 Subject: 'string'.strip(chars)-like function that removes from the middle? References: <48569B9E.6030206@admailinc.com> <200806161839.13647.omer@no-log.org> Message-ID: Terry Reedy wrote: > C?dric Lucantis wrote: > >> I don't see any string method to do that > > >>> 'abcde'.translate(str.maketrans('','','bcd')) > 'ae' > > I do not claim this to be better than all the other methods, > but this pair can also translate while deleting, which others cannot. You should mention that you are using Python 3.0 ;) The 2.5 equivalent would be >>> u"abcde".translate(dict.fromkeys(map(ord, u"bcd"))) u'ae' Peter From gagsl-py2 at yahoo.com.ar Thu Jun 12 05:29:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Jun 2008 06:29:41 -0300 Subject: h2py.py bug? References: <484E771D.1050404@arimaz.com> <484F7CDE.9000300@arimaz.com> Message-ID: En Wed, 11 Jun 2008 04:21:03 -0300, Gabriel Rossetti escribi?: > Gabriel Genellina wrote: >> En Tue, 10 Jun 2008 09:44:13 -0300, Gabriel Rossetti >> escribi?: >> >>> I wanted to use the h2py.py script (Tools/scripts/h2py.py) and it >>> didn't like char litterals : >>> >>> Skipping: PC_ERROR = ord() >>> >>> where my *.h file contained : >>> >>> #define PC_ERROR '0' >>> >>> I searched the web and found a post with the same error : >>> >>> http://mail.python.org/pipermail/python-list/2005-September/340608.html >>> >>> but it got no replies, I tried the fix and it works. I have the >>> following questions: >>> >>> 1) Why did it not get any attention, is something wrong with it? >>> 2) If nothing is wrong, did the fix not get applied because a bug >>> report wasn't filed? >> >> Very probably - bug reports outside the tracker are likely to go >> unnoticed or forgotten. >> > Ok, I'll file one then. >>> 3) Isn't turning a char literal into the ordinal value not contrary to >>> what a C programmer had in mind when he/she defined it? I mean if you >>> define a char literal then in python you would have used a string >>> value : >>> >>> #define PC_ERROR '0' >>> >>> would become : >>> >>> PC_ERROR = '0' >>> >>> in python, and if you intended to use the char type for an 8 bit >>> numerical value you would have done : >>> >>> #define PC_ERROR 0x30 >>> >>> where 0x30 is the '0' ascii hex value, so shouldn'it the line in the >>> diff (see the post) be : >>> >>> body = p_char.sub("'\\1'", body) >>> >>> instead of : >>> >>> body = p_char.sub("ord('\\1')", body) >> >> It's not so clear what's the intended usage - chars are also integers >> in C. (I prefer the current behavior, but certainly it may be wrong in >> several places). >> > Yes, true, but if you intend to use it as an integer, wouldn't you use a > numeric value instead of a character literal? Not always. Using characters as ordinal numbers is very common in that language. A small example: #define FIRST 'A' #define LAST 'Z' #define index(letter) ((letter)-FIRST) int accum[LAST-FIRST+1]; ... char x = some_word[0]; accum[index(x)]++; accum is an array of 26 integers, element 0 corresponding to letter 'A'. If one has to reproduce the exact same structure, in Python it would be: FIRST = ord('A') LAST = ord('Z') def index(letter): return ord(letter)-FIRST accum = [0 for i in range(LAST-FIRST+1)] x = some_word[0] accum[index(x)] += 1 Of course, in other cases, character constants are intended to be used as character data, so ord(...) is not the appropiate thing to do when converting to Python. But I don't think my example above is very contrived or uncommon - chars *are* integers from the C point of view, and some people isn't worried too much about the distinction, specially those who use C as their main or only language. -- Gabriel Genellina From robert.kern at gmail.com Wed Jun 11 17:58:02 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 11 Jun 2008 16:58:02 -0500 Subject: Numpy array to gzip file In-Reply-To: References: Message-ID: Sean Davis wrote: > I have a set of numpy arrays which I would like to save to a gzip > file. Here is an example without gzip: > > b=numpy.ones(1000000,dtype=numpy.uint8) > a=numpy.zeros(1000000,dtype=numpy.uint8) > fd = file('test.dat','wb') > a.tofile(fd) > b.tofile(fd) > fd.close() > > This works fine. However, this does not: > > fd = gzip.open('test.dat','wb') > a.tofile(fd) > > Traceback (most recent call last): > File "", line 1, in > IOError: first argument must be a string or open file As drobinow says, the .tofile() method needs an actual file object with a real FILE* pointer underneath it. You will need to call fd.write() on strings (or buffers) made from the arrays instead. If your arrays are large (as they must be if compression helps), then you will probably want to split it up. Use numpy.array_split() to do this. For example: In [13]: import numpy In [14]: a=numpy.zeros(1000000,dtype=numpy.uint8) In [15]: chunk_size = 256*1024 In [17]: import gzip In [18]: fd = gzip.open('foo.gz', 'wb') In [19]: for chunk in numpy.array_split(a, len(a) // chunk_size): ....: fd.write(buffer(chunk)) ....: > In the bigger picture, I want to be able to write multiple numpy > arrays with some metadata to a binary file for very fast reading, and > these arrays are pretty compressible (strings of small integers), so I > can probably benefit in speed and file size by gzipping. File size perhaps, but I suspect the speed gains you get will be swamped by the Python-level manipulation you will have to do to reconstruct the array. You will have to read in (partial!) strings and then put the data into an array. If you think compression will really help, look into PyTables. It uses the HDF5 library which includes the ability to compress arrays with gzip and other compression schemes. All of the decompression happens in C, so you don't have to do all of the manipulations at the Python level. If you stand to gain anything from compression, this is the best way to find out and probably the best way to implement it, too. http://www.pytables.org If you have more numpy questions, you will probably want to ask on the numpy mailing list: http://www.scipy.org/Mailing_Lists -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From omer at no-log.org Sun Jun 15 12:20:48 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Sun, 15 Jun 2008 18:20:48 +0200 Subject: problem with Py_BuildValue In-Reply-To: References: Message-ID: <200806151820.48809.omer@no-log.org> > Thank you. At least I can exclude another few error sources, now. > > >> I see nothing wrong with your code so I'd say it is somewhere else (did >> you snip any code between the end of the loop and the return?). >No. (Apart from freeing allocated memory.) I'm pretty sure we'll find something interesting here :) > > and if it doesn't help trace the content of your list > > after each iteration to see when the bad things happen (you can check the > > reference count of an object with obj->ob_refcnt). > > Seems ok. What I did to check this was placing this after building the > list: > > for (i=0; i < limit; i++) { > dummy = PyList_GetItem(python_return_value, i); > printf("%f\n", PyFloat_AsDouble(dummy)); > Py_CLEAR(dummy); > } PyList_GetItem returns a borrowed reference so you shoud _not_ unref it (this explains the refcnt -1 I think) Here's the code producing your message (from Objects/object.c in the python sources) : /* Implementation of PyObject_Print with recursion checking */ static int internal_print(PyObject *op, FILE *fp, int flags, int nesting) { if (op->ob_refcnt <= 0) /* XXX(twouters) cast refcount to long until %zd is universally available */ fprintf(fp, "", (long)op->ob_refcnt, op); } } I don't really understand its purpose, but it confirms that it's a ref count problem. Maybe the full source of your function could help ? -- C?dric Lucantis From hongfeng02 at gmail.com Wed Jun 18 13:16:33 2008 From: hongfeng02 at gmail.com (hongfeng02 at gmail.com) Date: Wed, 18 Jun 2008 10:16:33 -0700 (PDT) Subject: www.nikeadishoes.com Message-ID: <0caec560-47ca-4cd4-9f30-dbc2abb11cc2@j1g2000prb.googlegroups.com> because our company open no long time,and we have some pro in deals with oredr please make you new order to us ,i think we will have a good beginning !! Our website: www.nikeadishoes.com Choose your favorite products please trust us ,have a good beginning Email:shoesec at yahoo.com.cn MSN:shoes-ec at hotmail.com From eric.talevich at gmail.com Sun Jun 1 01:00:19 2008 From: eric.talevich at gmail.com (etal) Date: Sat, 31 May 2008 22:00:19 -0700 (PDT) Subject: Merging ordered lists Message-ID: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> Here's an algorithm question: How should I efficiently merge a collection of mostly similar lists, with different lengths and arbitrary contents, while eliminating duplicates and preserving order as much as possible? My code: def merge_to_unique(sources): """Merge the unique elements from each list in sources into new list. Using the longest input list as a reference, merges in the elements from each of the smaller or equal-length lists, and removes duplicates. @return: Combined list of elements. """ sources.sort(None, len, True) # Descending length ref = sources[0] for src in sources[1:]: for i, s in enumerate(src): if s and (ref[i] != s) and s not in ref: ref.insert(ref.index(src[i-1])+1, s) # Remove duplicates return [r for i, r in enumerate(ref) if r and r not in ref[i+1:]] This comes up with using the CSV module's DictWriter class to merge a set (list, here) of not-quite-perfect CSV sources. The DictWriter constructor needs a list of field names so that it can convert dictionaries into rows of the CSV file it writes. Some of the input CSV files are missing columns, some might have extras -- all of this should be accepted, and the order of the columns in the merged file should match the order of the input files as much as possible (not alphabetical). All of the list elements are strings, in this case, but it would be nice if the function didn't require it. Speed actually isn't a problem yet; it might matter some day, but for now it's just an issue of conceptual aesthetics. Any suggestions? From evidentemente.yo at gmail.com Tue Jun 24 05:50:46 2008 From: evidentemente.yo at gmail.com (evidentemente.yo) Date: Tue, 24 Jun 2008 02:50:46 -0700 (PDT) Subject: calling a .exe from Python Message-ID: Hi, i am trying to call a .exe from my .py file, i have found the exec function, but i'm not sure of how to use it:S would it be f.e.: execl (mypath/myfile.exe,myfile,arg1,arg2,...) ???? Another question is, when i call my .exe with exec, i understand that my .py file will stop running, and instead the new process will be launched instead of it. Is it true? Is there a way to launch my .exe without finishing my .py file?? thank you very much:) From a.harrowell at gmail.com Tue Jun 17 13:44:08 2008 From: a.harrowell at gmail.com (TYR) Date: Tue, 17 Jun 2008 10:44:08 -0700 (PDT) Subject: Making wxPython a standard module? References: <6bidd7F3bg8usU1@mid.uni-berlin.de> <87fxrfx0h0.fsf@physik.rwth-aachen.de> <48e9a145-d0f4-4ec3-9874-97d2cff1a91b@27g2000hsf.googlegroups.com> Message-ID: >" b = wx.Button(label="Click Me", action=myCallable) > Instead you used to have to create a button and then call > some utility function in some other object to bind that > button to a callable (IIRC this was one place where Window > IDs could be used). Now, the button actually has a method > you can use. It's still an extra step... That looks quite a lot like the behaviour of PythonForS60's appuifw class. Frex, a menu: appuifw.app.menu = [(u'Octopus', getfish(octopus)), (u'Cuttlefish', getfish(cuttlefish)), (u'Squid', ((u'Humboldt', getfish(humboldt)), (u'Giant', getfish(giantsquid)), (u'Colossal', getfish(colossal)))] gives you a menu with three options, the last of which has three sub- options, all of which call your getfish() function with their value. From grante at visi.com Sat Jun 14 15:26:24 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 14 Jun 2008 14:26:24 -0500 Subject: Creating a TCP/IP connection on already-networked computers References: <4853f269$0$11615$607ed4bc@cv.net> <4854123f$0$5017$607ed4bc@cv.net> <485413d0$0$4997$607ed4bc@cv.net> Message-ID: On 2008-06-14, John Salerno wrote: > John Salerno wrote: > >> ----- >> #!/usr/bin/env python >> >> from socket import * >> from time import ctime >> >> HOST = '192.168.1.100' > > >> ----- >> #!/usr/bin/env python >> >> from socket import * >> >> HOST = '192.168.1.100' > > A question about this. Is the "HOST" referring to the IP > address of the server computer in both of these cases? Yes. > Because when I ran the program and got to the part where it > says "connected from:" on the server side, it shows this same > IP address. Then you must have been either running the client program on the same machine as the server program or you've got some sort of NAT/port-forwarding going on. > Shouldn't it be something different, since the requests are > coming from a different computer than the server computer? Works fine for me. When I run the client program on a machine different than the server program, the server program prints out "connected from:" and then the client machine's IP address. -- Grant Edwards grante Yow! Maybe I should have at asked for my Neutron Bomb visi.com in PAISLEY -- From ironfroggy at socialserve.com Tue Jun 17 15:05:08 2008 From: ironfroggy at socialserve.com (Calvin Spealman) Date: Tue, 17 Jun 2008 15:05:08 -0400 Subject: Static memory allocation in Python In-Reply-To: <5868cf920806171134n33af0512j8ad93fc300fe015a@mail.gmail.com> References: <5868cf920806171134n33af0512j8ad93fc300fe015a@mail.gmail.com> Message-ID: On Jun 17, 2008, at 2:34 PM, Eduardo Henrique Tessarioli wrote: > Hi, > > I am running a very simple python application and I noted that the > memory allocation is something like 4,5M. > This is a problem in my case, because I have to run 2 thousand > process at the same time. > The memory I need is 100k or less. Is there any way to set this for > the python process? The runtime itself isn't as light as, say, the C stdlib. Now, there are a lot of shared libraries here, so you should measure not just a single instance, but how much it actually grows in overall system memory usage as you run more simultaneous python interpreters. > Regards, > Eduardo > -- > http://mail.python.org/mailman/listinfo/python-list From johnjsal at NOSPAMgmail.com Tue Jun 10 09:15:34 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 10 Jun 2008 09:15:34 -0400 Subject: chm file for download? Message-ID: <038f1951$0$3232$c3e8da3@news.astraweb.com> Is the chm doc file available for download from the Python website? I can't seem to find it. It would be nice to read through while I'm at work (where I don't have Python installed). Also, is it possible to use a chm file on Linux? Thanks. From sluggoster at gmail.com Wed Jun 11 16:09:38 2008 From: sluggoster at gmail.com (Mike Orr) Date: Wed, 11 Jun 2008 13:09:38 -0700 (PDT) Subject: ClassName.attribute vs self.__class__.attribute References: Message-ID: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> On Jun 5, 8:40 am, Gabriel Rossetti wrote: > Hello everyone, > > I had read somewhere that it is preferred to use > self.__class__.attribute over ClassName.attribute to access class (aka > static) attributes. I had done this and it seamed to work, until I > subclassed a class using this technique and from there on things started > screwing up. I finally tracked it down to self.__class__.attribute! What > was happening is that the child classes each over-rode the class > attribute at their level, and the parent's was never set, That's a misunderstanding of classes vs instances. If you have an instance of MyClass(Superclass), there is one instance but several classes. The instance is of MyClass; there is no instance of Superclass. 'self' has a .__class__ attribute because it's an instance, but MyClass and Superclass do not because they're already classes. Going further, self.a retrieves the instance attribute if it exists, or or MyClass.a if it doesn't, or Superclass.a if that doesn't. But assigning to self.a always assigns to an instance attribute. To assign a class attribute you must use .__class__ or TheClass. Likewise, to retrieve a class attribute that has been overridden by a subclass or instance, you must use .__class__ or TheClass. There's a very good reason to use self.__class__: it makes it possible to subclass your class. In Jason Orendorff's path.py, some path methods return new path objects. He uses 'path()' rather than self.__class__ to construct these. So if you subclass 'path' to extend it, these methods return path objects rather than your subclass objects. In my Unipath package which was written later, I use self.__class__ in these cases to allow users to extend my class. It's a little annoying that if you want to print a class's name in some unknown object, you have to use obj.__class__.__name__ if it's an instance, and obj.__name__ if it's a class. I sometimes wish classes had a .__class__ attribute that's the class itself, but I can see how that would cause its own confusion (and recursion). -- Mike Orr From markc.westwood at gmail.com Fri Jun 13 04:29:48 2008 From: markc.westwood at gmail.com (Mark Westwood) Date: Fri, 13 Jun 2008 01:29:48 -0700 (PDT) Subject: Point Of intersection between two plotted functions References: <2fd19881-27f8-48f3-bfa9-2d8a26f31920@26g2000hsk.googlegroups.com> Message-ID: Hi Let your 2 functions be f(x) and g(x). Then you have to solve the equation f(x) = g(x). For some functions it will be easier to determine intervals of the real line where f(x)-g(x) > 0 and where f(x)-g(x) < 0 and to find an interval in which the 2 intersect, which would probably be good enough for plotting. How straightforward any of this is depends entirely on the nature of your functions. Regards Mark On Jun 13, 7:34 am, arslanbur... at gmail.com wrote: > Is there anyway one could find ot the point of intersection between > any two plotted functions and also display them using gnuplot.py?? From tjreedy at udel.edu Sun Jun 8 04:19:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 8 Jun 2008 04:19:49 -0400 Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net><484ad07b$0$25721$607ed4bc@cv.net> <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> Message-ID: "Mensanator" wrote in message news:8d7c0912-422f-4480-a034-078f9dbcae24 at 2g2000hsn.googlegroups.com... | On Jun 7, 6:43?pm, "Terry Reedy" wrote: | > zip(range(9,2000000000), iterable) | | Oh, dear. You didn't actually try this, did you? Works fine in Py3, which is what I use now. From bruno.42.desthuilliers at websiteburo.invalid Mon Jun 23 11:53:40 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 23 Jun 2008 17:53:40 +0200 Subject: Passing arguments to subclasses In-Reply-To: <7pgv54l0pfaa2l05c4l8f3bld1rskd4dtf@4ax.com> References: <7pgv54l0pfaa2l05c4l8f3bld1rskd4dtf@4ax.com> Message-ID: <485fc702$0$22189$426a74cc@news.free.fr> John Dann a ?crit : > May I ask a simple newbie question, which I presume is true, but for > which I can't readily find confirmation: > > Let's say I have a parent class with an __init__ method explicitly > defined: > > class ParentClass(object): > def __init__(self, keyword1, keyword2): > etc > > and I subclass this: > > class ChildClass(ParentClass): > # No __init__ method explicitly defined > > Now I presume that I can instantiate a child object as: > > child = ChildClass(arg1, arg2) > > and arg1, arg2 will be passed through to the 'constructor' of the > antecedent ParentClass (there being no overrriding __init__ method > defined for ChildClass) and mapping to keyword1, keyword2 etc. > > Have I understood this correctly? Yes. But you could have checked by yourself: bruno at bruno:~$ python Python 2.5.1 (r251:54863, Mar 7 2008, 03:41:45) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Parent(object): ... def __init__(self, kw1, kw2): ... print self, kw1, kw2 ... self.kw1, self.kw2 = kw1, kw2 ... >>> class Child(Parent): pass ... >>> c = Child("arg1", "arg2") <__main__.Child object at 0xb7ddeccc> arg1 arg2 >>> c.kw1 'arg1' >>> c.kw2 'arg2' >>> HTH From spoier at gmail.com Thu Jun 5 20:05:04 2008 From: spoier at gmail.com (Skye) Date: Thu, 5 Jun 2008 17:05:04 -0700 (PDT) Subject: Newb question: underscore Message-ID: What is this doing? print >> fd, _(__doc__) I'm guessing line-splitting __doc__ into a list, but what's that leading underscore do? Thanks! From mishok13 at gmail.com Wed Jun 18 03:31:34 2008 From: mishok13 at gmail.com (Andrii V. Mishkovskyi) Date: Wed, 18 Jun 2008 10:31:34 +0300 Subject: How do I create user-defined warnings? In-Reply-To: <1213749985.25016.8.camel@generator> References: <1213749985.25016.8.camel@generator> Message-ID: <192840a00806180031p6dc001f6sc8831004ad38c7a8@mail.gmail.com> 2008/6/18 Clay Hobbs : > I already know how to make user-defined exceptions, like this one: > > class MyException(Exception): > pass > > But for a module I'm making, I would like to make a warning (so it just > prints the warning to stderr and doesn't crash the program). I have > tried this: > > class MyWarning(Warning): > pass > > And it behaves like a normal error. Please help me, I can't figure out > what I'm doing wrong. Use 'warnings' module. http://docs.python.org/lib/module-warnings.html > > -- > Ratfink > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Wbr, Andrii Mishkovskyi. He's got a heart of a little child, and he keeps it in a jar on his desk. From d3vvnull at gmail.com Tue Jun 10 11:34:19 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Tue, 10 Jun 2008 10:34:19 -0500 Subject: Building 64-bit Python on AIX Message-ID: <170543c70806100834x5a7d33b4n15e19237bd0f2ca9@mail.gmail.com> Hi all. I am trying to rebuild Python on our AIX system in 64 bit so I can use our installed 64-bit UnixODBC library. Has anyone successfully done this and can they share the configure options they used? Thanks. Mike -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From h.goebel at goebel-consult.de Tue Jun 10 08:28:50 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Tue, 10 Jun 2008 14:28:50 +0200 Subject: ANN: pdfposter 0.4.2 Message-ID: I'm pleased to announce pdfposter 0.4.2, a tool to scale and tile PDF images/pages to print on multiple pages. http://pdfposter.origo.ethz.ch/download/ This version fixes a view minor bugs - some media-/poster-sizes (eg. Letter) have not beeb recogniced - some PDF files crashed the tool. Download --------------- :Quick Installation: easy_install -U pdfposter :Tarballs: http://pdfposter.origo.ethz.ch/download/ What is pdfposter? -------------------- Scale and tile PDF images/pages to print on multiple pages. ``Pdfposter`` can be used to create a large poster by building it from multple pages and/or printing it on large media. It expects as input a PDF file, normally printing on a single page. The output is again a PDF file, maybe containing multiple pages together building the poster. The input page will be scaled to obtain the desired size. This is much like ``poster`` does for Postscript files, but working with PDF. Since sometimes poster does not like your files converted from PDF. :-) Indeed ``pdfposter`` was inspired by ``poster``. For more information please refere to the manpage or visit the `project homepage `_. :Author: Hartmut Goebel :Copyright: GNU Public Licence v3 (GPLv3) :Homepage: http://pdfposter.origo.ethz.ch/ From frank at chagford.com Wed Jun 11 05:48:33 2008 From: frank at chagford.com (Frank Millman) Date: Wed, 11 Jun 2008 02:48:33 -0700 (PDT) Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: Thanks to all for the various replies. They have all helped me to refine my ideas on the subject. These are my latest thoughts. Firstly, the Decimal type exists, it clearly works well, it is written by people much cleverer than me, so I would need a good reason not to use it. Speed could be a good reason, provided I am sure that any alternative is 100% accurate for my purposes. My approach is based on expressing a decimal number as a combination of an integer and a scale, where scale means the number of digits to the right of the decimal point. Therefore 0.04 is integer 4 with scale 2, 1.1 is integer 11 with scale 1, -123.456 is integer -123456 with scale 3. I am pretty sure that any decimal number can be accurately represented in this form. All arithmetic is carried out using integer arithmetic, so although there may be rounding differences, there will not be the spurious differences thrown up by trying to use floats for decimal arithmetic. I use a class called Number, with two attributes - an integer and a scale. My first attempt required these two to be provided every time an instance was created. Then I realised that this would cause loss of precision if I chain a series of instances together in a calculation. The constructor can now accept any of the following forms - 1. A digit (either integer or float) and a scale. It uses the scale factor to round up the digit to the appropriate integer. 2. Another Number instance. It takes the integer and scale from the other instance. 3. An integer, with no scale. It uses the integer, and assume a scale of zero. 4. A float in string format (e.g. '1.1') with no scale. It uses the number of digits to the right as the scale, and scales the number up to the appropriate integer. For addition, subtraction, multiplication and division, the 'other' number can be any of 2, 3, or 4 above. The result is a new Number instance. The scale of the new instance is based on the following rule - For addition and subtraction, the new scale is the greater of the two scales on the left and right hand sides. For multiplication, the new scale is the sum of the two scales on the left and right hand sides. For division, I could not think of an appropriate rule, so I just hard- coded a scale of 9. I am sure this will give sufficient precision for any calculation I am likely to encounter. My Number class is now a bit more complicated than before, so the performance is not as great, but I am still getting a four-fold improvement over the Decimal type, so I will continue running with my version for now. My main concern is that my approach may be naive, and that I will run into situations that I have not catered for, resulting in errors. If this is the case, I will drop this like a hot potato and stick to the Decimal type. Can anyone point out any pitfalls I might be unaware of? I will be happy to show the code for the new Number class if anyone is interested. Thanks Frank From desothier at yahoo.com Wed Jun 25 05:55:16 2008 From: desothier at yahoo.com (antar2) Date: Wed, 25 Jun 2008 02:55:16 -0700 (PDT) Subject: python -regular expression - list element Message-ID: <62e21ec1-18f3-4572-b223-1b8a5c40688c@f63g2000hsf.googlegroups.com> Hello, I am a beginner in Python and am not able to use a list element for regular expression, substitutions. list1 = [ 'a', 'o' ] list2 = ['star', 'day', 'work', 'hello'] Suppose that I want to substitute the vowels from list2 that are in list1, into for example 'u'. In my substitution, I should use the elements in list1 as a variable. I thought about: for x in list1: re.compile(x) for y in list2: re.compile(y) if x in y: z = re.sub(x, 'u', y) but this does not work From bruno.42.desthuilliers at websiteburo.invalid Thu Jun 12 05:17:49 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 12 Jun 2008 11:17:49 +0200 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> References: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> Message-ID: <4850e95d$0$10444$426a74cc@news.free.fr> Mike Orr a ?crit : (snip) > 'self' has a .__class__ attribute because it's an > instance, but MyClass and Superclass do not because they're already > classes. Not true for new-style classes: >>> class Toto(object): pass ... >>> Toto.__class__ (snip) > I sometimes wish classes > had a .__class__ attribute that's the class itself, newstyle classes do have a class attribute, that refers to the metaclass. > but I can see how > that would cause its own confusion (and recursion). FWIW, metaclasses do have a class attribute that refers to itself !-) From larry.bates at websafe.com` Wed Jun 4 12:37:30 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 04 Jun 2008 11:37:30 -0500 Subject: [XP] Batch-print bunch of RTF files? In-Reply-To: References: Message-ID: nospam at nospam.com wrote: > Hello, > > I have about two hundred individual RTF files to print from an > XP host. Word 2000 doesn't seem to have this feature, so I'm looking > for a way to print those RTF files from an ActivePython script. Would > someone have some working code handy? > > Thank you. Sure it does, just not the way you think. - Click on Start-Settings-Printer and Faxes - Double-click the printer you want to print to - Open folder where your 200 RTF files are stored. - Drag and drop the file on to the printer window and your machine will launch and print each of thes in Word. -Larry From gherron at islandtraining.com Sun Jun 22 14:59:17 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 22 Jun 2008 11:59:17 -0700 Subject: -1/2 In-Reply-To: References: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> Message-ID: <485EA105.9090706@islandtraining.com> Christian Heimes wrote: > Serve Lau wrote: > >> What is the expected result of -1/2 in python? >> > > 0 > > No. That's not right. (It would be in C/C++ and many other languages.) See my other response for the correct answer. Gary Herron > Christian > > -- > http://mail.python.org/mailman/listinfo/python-list > From atrophier at uno.net Sun Jun 22 00:15:10 2008 From: atrophier at uno.net (Atrophier Bigarrés) Date: 22 Jun 2008 04:15:10 GMT Subject: Ryhmän sfnet.tietoliikenne.yhteydentarjoajat virallinen kuvaus References: Message-ID: <1213555441_2169@250.130.139.19> MTV 3. 07.06.2008. "Norjassa tuulivoima my?t?tuulessa. Norjan energiatarpeista PUOLET voidaan kattaa tuulivoimalla, kun nykysuunnitelmat toteutetaan! Kaiken kaikkiaan 130 tuulivoimalapuistohanketta on haettu rakennuslupaa Norjan energiavirastolta. Jos kaikille halukkaille my?nnet??n lupa energiantuotanto kasvaisi 56 terawatttitunnilla, mik? on noin puolet maan nykytuotannosta. N?iden lis?ksi 19 tuulihanketta on saanut rakennusluvan, mutta rakentamista ei ole viel? alettu." *Niin.. ..MYKIST?V??! .. On jo p?iv?n selv??, ett? Tanskan ja Saksan uskaliaat uudisenergiairtiotot ovat saamassa arvoisensa triumfin. Maailman energiaj?tit alkavat k??nty? ennenn?kem?tt?m?n massiivisesti pois ydinmenneisyydest? ja suuntaavat tuhdisti turpoaville uudisenergiasektoreille. Erityisherkkuna on nimenomaan toimivimman offshoremerituuliosuuden aukeaminen. Kun jopa Englannin kaltaiseen pataydintaantumusvaltioon rakennetaan parhaillaan maailman masiivisinta Loviisaluokan ofshoretuuloipuistoa, ydinalan korttipeli p??ttyi t?yskaatoon. Ja kohta s?hk?verkot my?s kautta Pohjolan suorastaan notkuvat tuskin en?? kymmenesosaa ydins?hk?kustannuksesta maksavaa 100% saasteetonta bulkkiekoenergiaa. 100% s??dett?v?t ja puolisen vuotta sitten Norjan Trondheimissa mitatut k?sitt?m?tt?m?n hyv?t tuulivoiman ***99% vuosipysyvyyshy?tysuhteet NELJ? kertaa paremmat kuin ydinreaktorirumiluksilla ajetut enemm?n kuin vakuuttivat.*** T?ss? on tulossa sellaiset energiantuotannon poistumat ydinvoiman kaltaisista uudiskyvytt?mist? vektoreista, ett? ydinvoiman mustapekka sopeutumiskyvytt?m?lle Suomelle on varmentumassa. T?h?n settiin kun Viro julkaisee tuuliaikeensa ja saadaan ilman muuta Ruotsi mukaan, niin ydinsuomi sotketaan mukavasti ydinsuohonsa, jopa omilla s?hk?markkinoillaan. KUKAAN EI TARVITSE sikakallista s??t?kyvyt?nt? ja EU:ssa maineensa mokanutta ydinvoimaa. Tulemme n?kem??n sellaisen ydinvastarinnan n?emm? MY?S talousmiesten jaloin ??nestyksin, ettei mit??n jakoa. HIENOA!)) From ladasky at my-deja.com Tue Jun 3 20:57:07 2008 From: ladasky at my-deja.com (John Ladasky) Date: Tue, 3 Jun 2008 17:57:07 -0700 (PDT) Subject: Import, site packages, my modules, Windows vs. Linux Message-ID: <4993bd3d-22aa-4e0d-a593-38c0f5e2d69a@m44g2000hsc.googlegroups.com> Hi folks, Running Python 2.5 on both a Windows XP laptop, and an Ubuntu Linux 7.04 desktop. I've gotten tired of maintaining multiple copies of my personal modules that I use over and over. I have copies of these files in the same directory as the main program I happen to be working on at the time. I've also downloaded FANN, and want to use its Python bindings. FANN does not seem to build automatically, like wxWidgets did. These two issues have led me to examine exactly how the import statement works, how the PYTHONPATH environment variable is constructed, and how to change it. On Windows I found a solution that works, but which may be a kludge. In the Python "site-packages" folder, I added a sub-folder called "my- packages". Then I created a text file, "my-packages.pth", containing the single line, "my-packages." Finally, I moved my common personal modules into the my-packages folder and deleted all of my clumsy duplicates. Import statements now work for all of my files on the Windows box, great! I then tried to use this same strategy in Linux, and saw that I don't automatically have the privileges needed to alter the site-packages folder. On my Windows box, my default account has Administrator privileges. On Linux I can, of course, use sudo to modify the site- packages folder. But the fact that I would have to use sudo has me asking -- is there something inappropriate, or unsafe in my approach? I want to know what is the *recommended* way to integrate my own personal modules with Python. Thanks! From a.harrowell at gmail.com Fri Jun 20 07:01:39 2008 From: a.harrowell at gmail.com (TYR) Date: Fri, 20 Jun 2008 04:01:39 -0700 (PDT) Subject: Strange re problem Message-ID: <2a0a6f87-f72e-4190-85f8-6e43821e313a@r66g2000hsg.googlegroups.com> OK, this ought to be simple. I'm parsing a large text file (originally a database dump) in order to process the contents back into a SQLite3 database. The data looks like this: 'AAA','PF',-17.416666666667,-145.5,'Anaa, French Polynesia','Pacific/ Tahiti','Anaa';'AAB','AU',-26.75,141,'Arrabury, Queensland, Australia','?','?';'AAC','EG',31.133333333333,33.8,'Al Arish, Egypt','Africa/Cairo','El Arish International';'AAE','DZ', 36.833333333333,8,'Annaba','Africa/Algiers','Rabah Bitat'; which goes on for another 308 lines. As keen and agile minds will no doubt spot, the rows are separated by a ; so it should be simple to parse it using a regex. So, I establish a db connection and cursor, create the table, and open the source file. Then we do this: f = file.readlines() biglist = re.split(';', f) and then iterate over the output from re.split(), inserting each set of values into the db, and finally close the file and commit transactions. But instead, I get this error: Traceback (most recent call last): File "converter.py", line 12, in biglist = re.split(';', f) File "/usr/lib/python2.5/re.py", line 157, in split return _compile(pattern, 0).split(string, maxsplit) TypeError: expected string or buffer Is this because the lat and long values are integers rather than strings? (If so, any ideas?) From bruno.42.desthuilliers at websiteburo.invalid Thu Jun 19 03:57:32 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 19 Jun 2008 09:57:32 +0200 Subject: Function argument conformity check In-Reply-To: <0efa09ce-dbf9-4699-b87c-34c2c3b271f0@34g2000hsh.googlegroups.com> References: <0efa09ce-dbf9-4699-b87c-34c2c3b271f0@34g2000hsh.googlegroups.com> Message-ID: <485a1167$0$17213$426a74cc@news.free.fr> dlists.cad at gmail.com a ?crit : > Hi. I am looking for a way to check if some given set of (*args, > **kwds) conforms to the argument specification of a given function, > without calling that function. import inspect help(inspect.getargspec) From aweraw at gmail.com Fri Jun 13 05:01:01 2008 From: aweraw at gmail.com (Aidan) Date: Fri, 13 Jun 2008 19:01:01 +1000 Subject: Comments on my first script? In-Reply-To: References: <7e3a7c92-6204-46dd-8df8-90218f2fb314@26g2000hsk.googlegroups.com> <4016716e-0ff7-41aa-951a-ed9562ff2ac8@m44g2000hsc.googlegroups.com> <7bb26acf-8b58-4d29-8e64-05a75eb5e584@d45g2000hsc.googlegroups.com> Message-ID: Chris wrote: > On Jun 13, 9:38 am, Phillip B Oldham wrote: >> Thanks guys. Those comments are really helpful. The odd semi-colon is >> my PHP background. Will probably be a hard habbit to break, that >> one! ;) If I do accidentally drop a semi-colon at the end of the line, >> will that cause any weird errors? >> >> Also, Chris, can you explain this: >> a, b = line.split(': ')[:2] >> >> I understand the first section, but I've not seen [:2] before. > > That's slicing at work. What it is doing is only taking the first two > elements of the list that is built by the line.split. slicing is a very handy feature... I'll expand on it a little OK so, first I'll create a sequence of integers >>> seq = range(10) >>> seq [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] "take element with index 4 and everything after it" >>> seq[4:] [4, 5, 6, 7, 8, 9] "take everything up to, but not including, the element with index 4" >>> seq[:4] [0, 1, 2, 3] "take the element with index 3 and everything up to, but not including, the element with index 6" >>> seq[3:6] [3, 4, 5] then there's the step argument "take every second element from the whole sequence" >>> seq[::2] [0, 2, 4, 6, 8] "take every second element from the element with index 2 up to, but not including, the element with index 8" >>> seq[2:8:2] [2, 4, 6] Hope that helps. From grflanagan at gmail.com Sun Jun 29 16:01:01 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Sun, 29 Jun 2008 13:01:01 -0700 (PDT) Subject: Docutils rst2html.py gives Unknown Directive type "toctree" References: Message-ID: On Jun 19, 11:19?pm, "Calvin Cheng" wrote: > Hi, > > I am attempting to convert a bunch of .txt files into html using the > docutils package. > > It works for most of the txt files except for the index.txt file which > gives 2 errors: > (1) Unknown Directive type "toctree" > (2) (ERROR/3) Unknown interpreted text role "ref". > > Any idea how I can fix this? > > Would be glad if someone who is familiar with docutils could point me > in the right direction. "toctree" is a directive specific to the sphinx documentation system: http://sphinx.pocoo.org/concepts.html#the-toc-tree You must have something like: .. toctree:: in your file. docutils won't recognise this. G. From cwitts at gmail.com Fri Jun 13 10:29:15 2008 From: cwitts at gmail.com (Chris) Date: Fri, 13 Jun 2008 07:29:15 -0700 (PDT) Subject: Create list from string References: Message-ID: <7e8cd275-67a6-4fb4-b618-180a38528cad@z72g2000hsb.googlegroups.com> On Jun 13, 4:15?pm, ericdaniel wrote: > Hi, > > I'm new to Python and I need to do the following: > > from this: ? s = "978654321" > to this : ? ? ?["978", "654", "321"] > > Any help is appreciated > > Thanks, > > Eric What you could do is iterate over the string appending the characters 1 at a time to a new string and when you hit the point you want to place it in your output list you can append it there and clear the temp string eg. length = 3 tmp_string = '' results = [] for i,character in enumerate(s): if not (i+1) % length: results.append(tmp_string) else: tmp_string += character I don't like this approach as you create to many temp items and fairly ugly. What you could do is to rather use slicing to build it. results = [] length = 3 for i in xrange(0,len(s),length): results.append(s[i:i+length]) And then the neatest approach would be to put that into a list comprehension instead s = "978654321" step = 3 output = [s[start:start+step] for start in xrange(0,len(s),step)] Those are just some ways to do it. Hope that helps From auch-ich-m at g-kein-spam.com Wed Jun 4 06:01:44 2008 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Wed, 04 Jun 2008 12:01:44 +0200 Subject: Best way to modify code without breaking stuff. References: Message-ID: <2531546.63WkQjL8G4@news.perlig.de> Jesse Aldridge wrote: > I've got a module that I use regularly. I want to make some extensive > changes to this module but I want all of the programs that depend on > the module to keep working while I'm making my changes. What's the > best way to accomplish this? Don't ;-) If the changes are that extensive it might be considerable to write a new module and switch the depending code to use that new module when you're done and they're ready. As mentioned in another posting revision control is a good thing as well. Not just for that task. nd From grante at visi.com Sun Jun 29 09:39:05 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 29 Jun 2008 08:39:05 -0500 Subject: complex numbers should respect the "I" representation References: <6c674bf8-f16b-40f1-81ef-72c009c08465@w1g2000prd.googlegroups.com> Message-ID: <38idndLnYqrkDfrVnZ2dnUVZ_gydnZ2d@posted.visi> On 2008-06-29, Roy Smith wrote: >> I think complex numbers should respect the "i" or "I" >> representation, instead of "j". No reason being cute and using >> a different character instead of the traditional >> representation? > > Ask any electrical engineer what j means. And ask them what "I" means. -- Grant Edwards grante Yow! HUGH BEAUMONT died at in 1982!! visi.com From Robert.Bossy at jouy.inra.fr Wed Jun 18 11:39:01 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 18 Jun 2008 17:39:01 +0200 Subject: Looking for lots of words in lots of files In-Reply-To: References: Message-ID: <48592C15.1020402@jouy.inra.fr> brad wrote: > Just wondering if anyone has ever solved this efficiently... not > looking for specific solutions tho... just ideas. > > I have one thousand words and one thousand files. I need to read the > files to see if some of the words are in the files. I can stop reading > a file once I find 10 of the words in it. It's easy for me to do this > with a few dozen words, but a thousand words is too large for an RE > and too inefficient to loop, etc. Any suggestions? The quick answer would be: grep -F -f WORDLIST FILE1 FILE2 ... FILE1000 where WORDLIST is a file containing the thousand words, one per line. The more interesting answers would be to use either a suffix tree or an Aho-Corasick graph. - The suffix tree is a representation of the target string (your files) that allows to search quickly for a word. Your problem would then be solved by 1) building a suffix tree for your files, and 2) search for each word sequentially in the suffix tree. - The Aho-Corasick graph is a representation of the query word list that allows fast scanning of the words on a target string. Your problem would then be solved by 1) building an Aho-Corasick graph for the list of words, and 2) scan sequentially each file. The preference for using either one or the other depends on some details of your problems: the expected size of target files, the rate of overlaps between words in your list (are there common prefixes), will you repeat the operation with another word list or another set of files, etc. Personally, I'd lean towards Aho-Corasick, it is a matter of taste; the kind of applications that comes to my mind makes it more practical. Btw, the `grep -F -f` combo builds an Aho-Corasick graph. Also you can find modules for building both data structures in the python package index. Cheers, RB From kyosohma at gmail.com Tue Jun 17 14:43:07 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 17 Jun 2008 11:43:07 -0700 (PDT) Subject: text alignment References: <39d1c620-9923-46e7-999d-ed86c8b465ff@34g2000hsh.googlegroups.com> <114f3f4c-4004-488b-86c5-4bf6416e15bd@l42g2000hsc.googlegroups.com> <8d563101-53f0-41d3-a544-ee0ba1d58db5@m36g2000hse.googlegroups.com> <657c1cb2-cfeb-4806-960c-15b3f25f6575@w7g2000hsa.googlegroups.com> Message-ID: <39ae3cec-c231-4196-8f9a-b567b9a47b5c@c65g2000hsa.googlegroups.com> On Jun 17, 1:20?pm, Gandalf wrote: > since you brought up this issue, please tell me where can I fine > menual for this library? You want the manual for wxPython? Go to the download page on the Official wxPython page and get the Docs & Demos package: http://wxpython.org/download.php That include the wxWidgets Reference. Also see: http://wxpython.org/onlinedocs.php > can i generate dynamic GUI from it? Not sure what you mean by this. If you know how to create a "dynamic GUI" with html/ajax or some such based on the user's interactions with your website, than it should work in the embedded browser just as well as it would in a non-embedded one. > If not, Is there any way to generate dynamic GUI (one that can change > according to the user input) with HTML-CSS- javascript similar > environment? Mike From david at abbottdavid.com Sun Jun 29 22:54:25 2008 From: david at abbottdavid.com (David) Date: Sun, 29 Jun 2008 22:54:25 -0400 Subject: How to invoke the Python idle In-Reply-To: <12ca7dc20806291949w34199ac2g9b4d4e88465cb328@mail.gmail.com> References: <08484763-05df-49ee-b308-2dd64b7e2379@e39g2000hsf.googlegroups.com> <48683F65.80906@abbottdavid.com> <12ca7dc20806291949w34199ac2g9b4d4e88465cb328@mail.gmail.com> Message-ID: <48684AE1.8010701@abbottdavid.com> Alon Ben-Ari wrote: > Thank you > > yes I have > This is what I got: > alon at linux:~> idle > bash: idle: command not found > alon at linux:~> > > Any idea > ? > > Alon > > > On Sun, Jun 29, 2008 at 10:05 PM, David > wrote: > > Only-Trouble wrote: > > Hi all > I am running openSUSE 10.3 > I am learning python on my own, it seems like the system has > already > installed a python IDLE > The question is how to invoke it? > > > Thanks > > Only-Trouble > -- > http://mail.python.org/mailman/listinfo/python-list > > > > > Did you try to enter idle in a terminal? > > -- > Powered by Gentoo GNU/LINUX > http://www.linuxcrazy.com > > Could be you need something like this; http://rpmfind.net//linux/RPM/opensuse/updates/10.3/i586/python-idle-2.5.1-39.2.i586.html -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From maric at aristote.info Tue Jun 10 02:52:48 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 10 Jun 2008 08:52:48 +0200 Subject: Can I find out (dynamically) where a method is defined? In-Reply-To: References: Message-ID: <200806100852.48792.maric@aristote.info> Le Monday 09 June 2008 19:03:18 allendowney at gmail.com, vous avez ?crit?: > Thanks Maric! That's very close to what I want, although using dir() > can be misleading because if you invoke it on class B you get all of > class A's methods as well. I took your idea and wrote it up like > this: > > def find_defining_class(obj, meth_name): > """find and return the class object that will provide > the definition of meth_name (as a string) if it is > invoked on obj. > """ > for ty in type(obj).mro(): > if meth_name in ty.__dict__: > return ty > return None > > Cheers, > Allen > Oh ! you're just right, my first writing of this was : for m in 'a', 'b', 'c' : print [ t for t in type(i).mro() if m in t.__dict__ ] which I carelessly ad wrongly rewrote using dir while posting. Sorry. -- _____________ Maric Michaud From larudwer at freenet.de Thu Jun 5 15:25:28 2008 From: larudwer at freenet.de (Rüdiger Werner) Date: Thu, 5 Jun 2008 21:25:28 +0200 Subject: Interesting Math Problem References: Message-ID: "BEES INC" schrieb im Newsbeitrag news:mailman.105.1212653740.1044.python-list at python.org... ... Problem: Star Ratings People can rate cheeseburgers on my website with a star rating of 0-5 stars (whole stars only), 5 being mighty tasty and 0 being disgusting. I would like to show the average of everyone's ratings of a particular cheeseburger to the nearest half star. I have already calculated the average rating as a float (star_sum) and the total number of people that rated the particular cheeseburger (num_raters). The result should be stored as a float in a variable named "stars." My Solution (in Python): Well seems this is a typical half even rounding problem. See http://mail.python.org/pipermail/python-list/2008-April/485889.html for a long discussion However since your problem looks like a typical homework problem i made my example buggy by intention. However the result should be correct. have fun! def myround(x): d, m = divmod(x, 2) return 2*d + round(m - 1) + 1 num = 1.5 for _i in xrange(30): print num, ' -> ', myround(num * 2)/2 num -= 0.1 >pythonw -u "test18.py" 1.5 -> 1.5 1.4 -> 1.5 1.3 -> 1.5 1.2 -> 1.0 1.1 -> 1.0 1.0 -> 1.0 0.9 -> 1.0 0.8 -> 1.0 0.7 -> 0.5 0.6 -> 0.5 0.5 -> 0.5 0.4 -> 0.5 0.3 -> 0.5 0.2 -> 0.0 0.1 -> 0.0 -1.94289029309e-016 -> 0.0 < --- hint for bug -0.1 -> 0.0 -0.2 -> 0.0 -0.3 -> -0.5 -0.4 -> -0.5 -0.5 -> -0.5 -0.6 -> -0.5 -0.7 -> -0.5 -0.8 -> -1.0 -0.9 -> -1.0 -1.0 -> -1.0 -1.1 -> -1.0 -1.2 -> -1.0 -1.3 -> -1.5 -1.4 -> -1.5 >Exit code: 0 to avoid the bug have a look at: http://mail.python.org/pipermail/python-list/2008-April/485934.html and try this example: num = 3 for _i in xrange(num * 10,-num *10, -1): if myround(float(_i)/10) != myround(num): print num, " -> ", myround(num ), " --- ", myround(float(_i)/10) print "-----" num -= 0.1 From salmoni at gmail.com Thu Jun 12 23:00:17 2008 From: salmoni at gmail.com (Alan J. Salmoni) Date: Thu, 12 Jun 2008 20:00:17 -0700 (PDT) Subject: Notify of change to list Message-ID: <8b34cc2b-aa3a-4788-b849-1f926284c7ca@m36g2000hse.googlegroups.com> Hello everyone, I searched through groups to find an appropriate answer to this one but could only find these which didn't meet my program's needs: http://groups.google.com/group/comp.lang.python/browse_thread/thread/53a0bfddeedf35b2/5e4b7119afa5f8df?lnk=gst&q=monitor+change+in+mutable#5e4b7119afa5f8df, http://groups.google.com/group/comp.lang.python/browse_thread/thread/b7e0bb2cf9e2f5cd/bccfd49a5c8a56e2?lnk=gst&q=monitor+change+in+object#bccfd49a5c8a56e2. My question is how can my program be notified of a change to a class attribute that is a list? I have a class defined that has a list as an attribute and the program needs to know when the user changes this attribute either completely or elementwise via an interpreter built-in to the program. Using __setattr__ I can be informed whenever it is rebound (x.attr = [2,3,4]) but not when changes are made elementwise (x.attr[1] = 99). I tried using properties to get changes but again the same result occurs. class c(object): def __init__(self): self._x = 0 def getx(self): return self._x def setx(self, x): print "setting x: ", x self._x = x x = property(getx, setx) # all of the following need to be caught a.x = [1,2,3] # is rebound from 0 so is caught a.x[1] = 99 # element-wise change only which isn't caught a.x = [4,5,6] # is rebound so is caught a.x[0:3] = [11,12,13] # though a "complete" change in terms of elements, this is element-wise and is not rebound and is thus not caught >>> setting x: [1, 2, 3] setting x: [4, 5, 6] >From what I understand, changes will only be caught if the attribute is completely rebound (ie, completely re-assigned), but I cannot force my users to do this. Short of hacking around with the interpreter to catch element-wise reassignments (possible, but I'd rather avoid), can anyone suggest a way to do this? Alan From news at prodata.co.uk Tue Jun 17 07:28:08 2008 From: news at prodata.co.uk (John Dann) Date: Tue, 17 Jun 2008 12:28:08 +0100 Subject: Numeric type conversions Message-ID: I'm new to Python and can't readily find the appropriate function for the following situation: I'm reading in a byte stream from a serial port (which I've got working OK with pyserial) and which contains numeric data in a packed binary format. Much of the data content occurs as integers encoded as 2 consecutive bytes, ie a 2-byte integer. I'm guess that there should be a function available whereby I can say something like: My2ByteInt = ConvertToInt(ByteStream[12:13]) to take a random example of the 2 bytes occurring at positions 12 and 13 in the byte stream. Can anyone point me in the right direction towards a suitable function please? NB I don't know without further checking exactly how the bytes are encoded, but I'm just transcribing some code across from a Windows VB.Net program and these same bytes could be read straight into a standard 2-byte signed short int, so I can be confident that it's a fairly standard Windows-compatible encoding. From sjmachin at lexicon.net Sat Jun 21 10:06:06 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 21 Jun 2008 07:06:06 -0700 (PDT) Subject: Getting column names from a cursor using ODBC module? References: Message-ID: <386e874a-ed66-4f1e-8eed-bf88e1b561c9@i18g2000prn.googlegroups.com> On Jun 21, 11:58 pm, dana... at yahoo.com wrote: > Is there any way to retrieve column names from a cursor using the ODBC > module? Or must I, in advance, create a dictionary of column position > and column names for a particular table before I can access column > values by column names? I'd prefer sticking with the ODBC module for > now because it comes standard in Python. > > I'm using Python 2.4 at the moment. > > Thanks. From mr.edel at gmx.at Tue Jun 3 12:28:04 2008 From: mr.edel at gmx.at (Matt) Date: Tue, 03 Jun 2008 16:28:04 +0000 Subject: ctypes, function pointers and a lot of trouble References: <832f57f4-7d26-44a5-8abe-567165cc532f@f36g2000hsa.googlegroups.com> Message-ID: > The docs say CFUNCTYPE(restype, *argtypes), so: > > cstreamopen = CFUNCTYPE(c_uint, c_ushort, c_uint) > > is saying that the result type is c_uint, not void. I think you need: > > cstreamopen = CFUNCTYPE(None, c_uint, c_ushort, c_uint) > > instead. Hm, thanks, now I can access my data in the functions and also write them but the program keeps terminating right at the point when the "open" function finishes. Unfortunately everything closes and I get no error messages. I did some additional work in the meantime and changed my code so it has the correct datatypes now: --------------------------CODE-------------------------------------------- def pystreamopen (contextH, mode, pErr): print "opening..." print contextH.contents.dwBufferSize #just to check the structure print mode #tells about what the DLL wants to do with this stream contextH.contents.mode = c_byte(5) #5=Permission to read and write contextH.contents.lPos = c_uint(0) #start position print pErr.contents pErr.contents = c_uint(0) cstreamopen = CFUNCTYPE(None, POINTER(MemStreamData), c_ushort, POINTER(c_uint)) def pystreamclose (contextH, pErr): print "closing..." pass cstreamclose = CFUNCTYPE(None, POINTER(MemStreamData), POINTER(c_uint)) def pystreamread (contextH, pBuf, pBufsize, pErr): print "reading..." pass cstreamread = CFUNCTYPE(None, POINTER(MemStreamData), c_uint, c_uint, POINTER(c_uint)) def pystreamtell (contextH, pErr): print "telling... . . .etc... --------------------------/CODE-------------------------------------------- and the function call: --------------------------CODE-------------------------------------------- errorcode = cdsdk.CDGetReleasedData(devicehandle, byref(cbfunct), c_uint(0), c_uint(0), byref(datainfo), POINTER(cdStgMedium)(data)) --------------------------/CODE-------------------------------------------- while it's running my program prints the following and then exits/terminates: >>> opening...990001 >>> 2 >>> c_ulong(0L) >>> Script terminated. ##This is a message by my editor (SPE) I also tried different editors, but get the same result... Anyway, meanwhile decided to try a different approach. Maybe I have more luck by having the function write the data directly into a file on the HDD. Doe anyone know how to translate the following into Python/ctypes? I googled quite a lot before but all topic-related I found was my own posting here in this NG :S --------------------------CODE-------------------------------------------- pFilStrm->hFile = CreateFile( pFilStrm->szFileName, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL ); --------------------------/CODE-------------------------------------------- This function is obviously a default C-function that generates a file and returns a c-handle to that file. In my case I'd need exactly such a handle to get things working... Furthermore there's a writefile function I'd need to translate too: --------------------------CODE-------------------------------------------- WriteFile( pFilStrm->hFile, pBuf, dwNumberOfBytesToWrite, pBufsize, NULL ); --------------------------/CODE-------------------------------------------- Ideas? Thanks and best wishes, Matt From patrickstinson.lists at gmail.com Thu Jun 5 14:36:15 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Thu, 5 Jun 2008 10:36:15 -0800 Subject: Please unregister this mail-address out of mailing-list. In-Reply-To: <48482EF4.2060801@gmail.com> References: <48482EF4.2060801@gmail.com> Message-ID: <6214d7a20806051136t5a9bbac2l5008ba3c1794b53e@mail.gmail.com> you can unsubscribe yourself at the list info page (the same page you subscribed from) On Thu, Jun 5, 2008 at 10:22 AM, Hank @ITGroup wrote: > Dear Python Staff, > I am writing this letter to unsubscribe this mail-address from python > mail-list. One problem is that this python community is so active that I > always lost myself to find my business emails. So, I want to quit this > mail-address from you, and want to set up a specific mail-box to receive all > python mails. > Since could find a way to unsubscribe the mails, I need to write this letter > to you. Please help. > > BTW, python is indeed great, thank you all for any supports. > > Hank. > > -- > http://mail.python.org/mailman/listinfo/python-list > From bj_666 at gmx.net Tue Jun 3 01:05:55 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Jun 2008 05:05:55 GMT Subject: php vs python References: Message-ID: <6ak1pjF379qfdU2@mid.uni-berlin.de> On Mon, 02 Jun 2008 18:21:26 -0700, Joel Koltner wrote: > "Arnaud Delobelle" wrote in message > news:m2y75oa1xp.fsf at googlemail.com... >> This is wrong, because if you know well one language only, you tend to >> think that the principles that underpin it are universal. So you will >> try to shoehorn these principles into any other language you use. > > Fair point, although I guess I was assuming the language you were good in was > something that covers, say, 90% of contemporary programming practices, e.g., > something like C++ : If you're truly good at C++ (and percentage-wise of all > programmers, relatively few are), there are not many things that I'm aware of > that are tremendously different in any other programming language. Function > decorators from Java and some of the function programming stuff from Lisp, > perhaps, but those are pretty small additions (well within the "10%"). I think you are talking about something a little different than Arnaud. You are talking about the 10% that's new in another language that has to be learned additionally and Arnaud is talking about the stuff the programmer already knows about the old language that somewhat works in the new one but is all but optimal and thus has to be *unlearned*. From C++ to Python or Java this is RAII and deterministic destructors for instance. Other old habits from people coming to Python are: using indexes where they are not needed, trivial getters and setters, putting *everything* into classes and every class into a module, and so on. Another difference are internal versus external iterators. In Python you write the loop outside the iterable and pull the items out of it. In other languages (Ruby, Io, ?) iterables do internal iteration and you give them a function where all item are "pushed" into one at a time. > Perhaps I should reduce my claim to those good at programming in any "first > class" language like C++ are generally going to write at least above-average > code in any other language. :-) What makes C++ a "first class" language? And did you quote "first class" for the same reason than I did? ;-) Ciao, Marc 'BlackJack' Rintsch From martin at v.loewis.de Sun Jun 22 14:33:14 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 22 Jun 2008 20:33:14 +0200 Subject: Bind compiled code to name? In-Reply-To: References: Message-ID: <485e9aea$0$637$9b622d9e@news.freenet.de> > If string `source_code` contains Python source code, how can I execute > that code, and bind it to some name? I tried compiling with: > > code_object = compile(source_code, 'errorfile', 'exec') > > but then what to do with `code_object`? > > P.S. > If my intentions aren't that clear, this is what I'm trying to do. I want > to emulate this: > > import some_module as some_name > > but with my code in `some_module` string, and not in file. > d = {} exec source_code in d some_name = d['some_name'] HTH, Martin From alexnbryan at gmail.com Tue Jun 10 14:57:48 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 10 Jun 2008 11:57:48 -0700 (PDT) Subject: problems with opening files due to file's path In-Reply-To: <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> Message-ID: <17762276.post@talk.nabble.com> That would work, but not for what I want. See the file could be anywhere on the user's system and so the entire path will be unique, and that didn't work with a unique path. What is the subprocess module you are talking about? Mike Driscoll wrote: > > On Jun 10, 1:25?pm, "Thomas Morton" > wrote: >> maybe try string substitution... not sure if that's really the BEST way >> to >> do it but it should work >> >> startfile(r"%s"%variable) > > > I concur. That should work. A slightly more in depth example (assuming > Windows): > > os.startfile(r'C:\Documents and Settings\%s\Desktop\myApp.exe' % > username) > > or > > os.startfile(r'C:\Program Files\%s' % myApp) > > Hopefully this is what you are talking about. If you were referring to > passing in arguments, than you'll want to use the subprocess module > instead. > > >> >> -------------------------------------------------- >> From: "Alexnb" >> Sent: Tuesday, June 10, 2008 7:05 PM >> To: >> Subject: Re: problems with opening files due to file's path >> >> >> >> > Well, now i've hit another problem, this time being that the path will >> be >> > a >> > variable, and I can't figure out how to make startfile() make it raw >> with >> > a >> > variable, if I put startfile(r variable), it doesn't work and >> > startfile(rvariable) obviously won't work, do you know how to make that >> > work >> > or better yet, how to take a regular string that is given and make >> every >> > single "\" into a double "\\"? >> > > > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17762276.html Sent from the Python - python-list mailing list archive at Nabble.com. From bob at mellowood.ca Mon Jun 16 18:02:56 2008 From: bob at mellowood.ca (bvdp) Date: Mon, 16 Jun 2008 15:02:56 -0700 Subject: Simple and safe evaluator References: <1de31143-7d8e-42e9-ae9d-8b0a0274ddc3@e53g2000hsa.googlegroups.com> Message-ID: George Sakkis wrote: > On Jun 16, 4:47 pm, bvdp wrote: > >> 2. I thought I'd be happy with * / + -, etc. Of course now I want to add >> a few more funcs like int() and sin(). How would I do that? > > For the builtin eval, just populate the globals dict with the names > you want to make available: > > import math > > globs = {'__builtins__' : None} > > # expose selected builtins > for name in 'True False int float round abs divmod'.split(): > globs[name] = eval(name) > > # expose selected math constants and functions > for name in 'e pi sqrt exp log ceil floor sin cos tan'.split(): > globs[name] = getattr(math,name) > > return eval(s, globs, {}) > Thanks. That was easy :) > The change to the _ast version is left as an exercise to the reader ;) And I have absolutely no idea on how to do this. I can't even find the _ast import file on my system. I'm assuming that the _ast definitions are buried in the C part of python, but that is just a silly guess. Bob. From miller.paul.w at gmail.com Thu Jun 19 18:14:21 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Thu, 19 Jun 2008 15:14:21 -0700 (PDT) Subject: Google-like "Did you mean... ?" search algorithm Message-ID: <7a8313a1-1536-4754-ab4d-9cce4fa1b31a@y38g2000hsy.googlegroups.com> This is a wee bit OT, but I am looking for algorithms to implement search suggestions, similar to Google's "Did you mean... ?" feature. Can anyone point me to web pages, journal articles, implementations (preferably in Python!), or any other resources in this area? Thanks! From mnordhoff at mattnordhoff.com Sat Jun 14 05:59:55 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sat, 14 Jun 2008 09:59:55 +0000 Subject: write Python dict (mb with unicode) to a file In-Reply-To: References: Message-ID: <4853969B.6050909@mattnordhoff.com> dmitrey wrote: > hi all, > what's the best way to write Python dictionary to a file? > > (and then read) > > There could be unicode field names and values encountered. > Thank you in advance, D. pickle/cPickle, perhaps, if you're willing to trust the file (since it's basically eval()ed)? Or JSON (use simplejson or the enhanced version of cjson), though I doubt it would be super-fast. -- From __peter__ at web.de Sun Jun 15 07:48:23 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Jun 2008 13:48:23 +0200 Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> Message-ID: ram.rachum at gmail.com wrote: > Quick question: > I have python code that does a lot of floating point arithmetic. How > do I make it do the arithmetic in 64 bit? (I have a 64 bit CPU.) If > I'll install a 64-bit operating system, will that do the trick? The Python float type uses a C double internally which is 64 bit even on 32 bit CPUs. Peter From tgrav at mac.com Fri Jun 6 17:15:42 2008 From: tgrav at mac.com (Tommy Grav) Date: Fri, 6 Jun 2008 17:15:42 -0400 Subject: Q about object identity In-Reply-To: <48499D95.50006@stoneleaf.us> References: <48499D95.50006@stoneleaf.us> Message-ID: <4FF2364B-9F3C-4F15-A655-C86DB22C926E@mac.com> On Jun 6, 2008, at 4:27 PM, Ethan Furman wrote: > vronskij at gmail.com wrote: >> Hello, >> I am testing object identity. >> If I do it from the interpreter, I get strange results. >>>>> *print [] is []* >> *False* >>>>> print id([]), id([]) >> 3083942700 3083942700 >> Why is that? Isn't this an error? in the first statement the two []'s are in memory at the same time and have different id() signatures. For the second statement the first id([]) is evaluated and release from memory and then the second id([]) is evaluated and release from memory. Since only one of them exist at a time they can have the same id() signature. Cheers Tommy From kyosohma at gmail.com Mon Jun 9 10:42:49 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 9 Jun 2008 09:42:49 -0500 Subject: How to get full path to script? In-Reply-To: References: Message-ID: On Mon, Jun 9, 2008 at 12:37 AM, bukzor wrote: > On Jun 8, 12:52 pm, kj wrote: >> In "Mark Tolonen" writes: >> >> >import os >> >print os.path.abspath(__file__) >> >> Great. Thanks! >> >> Kynn >> >> -- >> NOTE: In my address everything before the first period is backwards; >> and the last period, and everything after it, should be discarded. > > Note that this doesn't quite work for symbolic links or compiled > scripts, depending on your requirements. > -- > http://mail.python.org/mailman/listinfo/python-list > For my compiled scripts, I usually use this variation: path = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))) It's always worked for me. Mike From kris at FreeBSD.org Tue Jun 24 11:31:17 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Tue, 24 Jun 2008 17:31:17 +0200 Subject: Bit substring search In-Reply-To: <5135a9f6-d8a5-4812-88b5-bc5fa28ece71@25g2000hsx.googlegroups.com> References: <5043fee7-444b-41dd-a419-77550595d273@79g2000hsk.googlegroups.com> <5135a9f6-d8a5-4812-88b5-bc5fa28ece71@25g2000hsx.googlegroups.com> Message-ID: <48611345.1070308@FreeBSD.org> bearophileHUGS at lycos.com wrote: > Kris Kennaway: >> Unfortunately I didnt find anything else useful here yet :( > > I see, I'm sorry, I have found hachoir quite nice in the past. Maybe > there's no really efficient way to do it with Python, but you can > create a compiled extension, so you can see if it's fast enough for > your purposes. > To create such extension you can: > - One thing that requires very little time is to create an extension > with ShedSkin, once installed it just needs Python code. > - Cython (ex-Pyrex) too may be okay, but it's a bit trikier on Windows > machines. > - Using Pyd to create a D extension for Python is often the faster way > I have found to create extensions. I need just few minutes to create > them this way. But you need to know a bit of D. > - Then, if you want you can write a C extension, but if you have not > done it before you may need some hours to make it work. Thanks for the pointers, I think a C extension will end up being the way to go, unless someone has beaten me to it and I just haven't found it yet. Kris From nospam at nospam.com Sun Jun 1 12:16:33 2008 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 01 Jun 2008 18:16:33 +0200 Subject: [Business apps for Windows] Good grid + calendar, etc.? References: <0fcd01c8c3e7$54919d70$0203a8c0@MOUSE> Message-ID: On Sun, 01 Jun 2008 11:24:17 -0400, python at bdurham.com wrote: >Instead of the COM approach, have you considered using a local, client >based Python server as a container for your business logic and GUI >(DHTML, AJAX)? But web-based apps are even worse, since the set of widgets is even more basic, and web programming is hell. That's why I don't bother, and write fat apps instead. It'd be awesome if someone came up with a commercial offer of widgets that are either missing or not feature-rich enough in wxPython for real business apps. From paddy3118 at googlemail.com Fri Jun 13 10:49:48 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 13 Jun 2008 07:49:48 -0700 (PDT) Subject: Summing a 2D list References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <878wx9leiv.fsf@ara.blue-cable.net> Message-ID: <26b1f5cb-54cf-4ab2-9630-054fa8a39acb@z72g2000hsb.googlegroups.com> On Jun 13, 1:12 pm, Karsten Heymann wrote: > Hi Mark, > > > > Mark writes: > > I have a scenario where I have a list like this: > > > User Score > > 1 0 > > 1 1 > > 1 5 > > 2 3 > > 2 1 > > 3 2 > > 4 3 > > 4 3 > > 4 2 > > > And I need to add up the score for each user to get something like > > this: > > > User Score > > 1 6 > > 2 4 > > 3 2 > > 4 8 > > > Is this possible? If so, how can I do it? I've tried looping through > > the arrays and not had much luck so far. > > Although your problem has already been solved, I'd like to present a > different approach which can be quite a bit faster. The most common > approach seems to be using a dictionary: > > summed_up={} > for user,vote in pairs: > if summed_up.has_key(user): > summed_up[user]+=vote > else: > summed_up[user]=vote > > But if the list of users is compact and the maximum value is known > before, the using a list and coding the user into the list position is > much more elegant: > > summed_up=list( (0,) * max_user ) > for user,vote in pairs: > summed_up[user] += vote > > I've run a quick and dirty test on these approaches and found that the > latter takes only half the time than the first. More precisely, with > about 2 million pairs, i got: > > * dict approach: 2s > (4s with "try: ... except KeyError:" instead of the "if") > * list approach: 0.9s > > BTW this was inspired by the book "Programming Pearls" I read some > years ago where a similar approach saved some magnitudes of time > (using a bit field instead of a list to store reserved/free phone > numbers IIRC). > > Yours, > Karsten How does your solution fare against the defaultdict solution of: d = collections.defaultdict(int) for u,s in zip(users,score): d[u] += s - Paddy From kaaveland at gmail.com Thu Jun 12 17:58:36 2008 From: kaaveland at gmail.com (=?iso-8859-1?q?Robin_K=E5veland?= Hansen) Date: Thu, 12 Jun 2008 21:58:36 +0000 (UTC) Subject: Python noob's simple config problem References: Message-ID: On Thu, 12 Jun 2008 21:32:34 +0000, kj wrote: > I'm sure this is a simple, but recurrent, problem for which I can't hit > on a totally satisfactory solution. > > As an example, suppose that I want write a module X that performs some > database access. I expect that 99.999% of the time, during the > foreseeable future, the database connection parameters will remain > unchanged. The only exception that I envision for this would be during > testing or debugging. > > Given all this, I am tempted to turn these connection parameters into > hard-coded module attributes that I can always override (i.e. overwrite) > when necessary. > > But for as long as I can remember the dogma has been that hard-coded > values are bad, and that one should use other techniques, such as > configuration files, or parameters to a suitable constructor, etc. > > This is where I begin to get confused: whose responsibility is it to > know of and read the config file? I can think of two distinct > scenarios: 1) module X is being used by a large, full-fledged > application A that already uses a config file for its own configuration; > 2) module X is being used by a simple script that has no need for a > config file. In case 1 I'd be glad to let application A set module X's > connection parameters using values read from its own (i.e. A's) config > file; this minimizes the number of config files that need to be > maintained. In case 2, however, it would be preferable for module X to > read its connection params from its own (i.e. X's) config file. In this > way the script won't have to bother setting some parameters that are in > fact practically constant... > > After going round and round on this, my original idea of hard-coding the > values as module attributes begins to look pretty attractive again. > > How would you handle such situations? > > Thanks! > > kynn I think I would just abstract it away with a "getter" for the connection, a function that takes some optional parameters, if not supplied, it simply fetches them from a default configuration. Ie: def connect(params=None): if params is None: return dblayer.connect(conf["default"]) else: return dblayer.connect(params) Unless I have misunderstood you completely? Now people can change your scripts config file, and if someone wants to use your code, they can use the getter directly. I hope this is of some help. From ThuongqDo at gmail.com Fri Jun 27 16:49:42 2008 From: ThuongqDo at gmail.com (Ryuke) Date: Fri, 27 Jun 2008 13:49:42 -0700 (PDT) Subject: How to get a multicast to wait for all nodes? References: <476d7eed-f0f2-4509-97be-152ea634fb0c@j1g2000prb.googlegroups.com> Message-ID: On Jun 27, 8:09?am, "Colin J. Williams" wrote: > Ryuke wrote: > > I have a code that receives gps information from nodes and gives off > > its own coordinates via radios connected by Ethernet. ?but the code > > continues to run after receiving only 1 set of coordinates, how do i > > get it to wait for multiple nodes to send before continuing > > You might provide wth significant part > of the code you have written. > > Colin W. oops. guess that's important, here's part of it #Get local node network view data from RIB using SNMP over Ethernet mynodeID = snmpget(RIB_HOST, MYNODE_ID) # print '[netge module] MYnode ID =',mynodeID netdict = snmpwalk(RIB_HOST,MIB_BASE) netdict[MYNODE_ID] = mynodeID print '[netge module] MyNode ID = ',netdict[MYNODE_ID] sorted_keys = sorted(netdict) # for key in sorted_keys: print '%s\t\t%s' % (key,netdict[key]) for c in netdict[NODE_LIST][1:]: print '[netge module] NbrNode %d'% ord(c) #Create heart beat data packet for multicast xfer # gpsdata.append(time.ctime()) print '[netge module] mynode location = ',netdict[MYNODE_LOCATION] # netdict[MYNODE_LOCATION] = ' '.join(gpsdata) netdict[MYNODE_LOCATION] = gpsdata print '[netge module] mynode location = ',netdict[MYNODE_LOCATION] heartbeat = ' '.join(netdict[MYNODE_LOCATION]) print '[netge module] heartbeat=',heartbeat #Send mulitcast heart beat packet of local node view of network sock.sendto(heartbeat,(MULTICAST_IP_ADDR, MULTICAST_PORT)) print '[netge module] multicast send' #Receive mulitcast heart beat data #ReceiveHB() print '[netge module] multicast receive=',sock.recv(1024) #Create KMZ file for local node view of network # CreateKMZfile(netdict) node = [] latitude = [] longitude = [] altitude = [] kml_nodes = '' kml_links = '' MAX_NUM = int(netdict[NUMBEROFNODES]) # MAX_NUM = len(netdict[NODE_LIST]) # print MAX_NUM From johnjsal at NOSPAMgmail.com Thu Jun 12 11:13:38 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 12 Jun 2008 11:13:38 -0400 Subject: Making wxPython a standard module? References: <48512f69$0$11262$c3e8da3@news.astraweb.com> <6bcqtpF3btl4sU1@mid.uni-berlin.de> Message-ID: <48513c49$0$11199$c3e8da3@news.astraweb.com> "Diez B. Roggisch" wrote in message news:6bcqtpF3btl4sU1 at mid.uni-berlin.de... > This has been discussed before. While tkInter might not be the greatest > toolkit out there it has two extreme advantages: > > - it is comparably small regarding the footprint. Few external > dependencies, small libraries, small python-wrapping. > > - it is available on a wide range of platforms. > > - it is very stable, not only wrt bugs but also regarding features. > There > is no external pressure to update it frequently. > > - it is easily maintainable. Ok, that was more than two advantages! :) But those are good points. I was wondering about the size of wx too. Probably huge compared to Tkinter. > And on a personal note: I find it *buttugly*. But that has nothing to do > with the reasons given above - nor do I have any weight in the decision to > include it or not... :) You find what ugly? The look of wxPython apps, or the code itself? To me it seems very nice, but what do I know! I also have started using XRC (putting the GUI in an xml file instead of in the program), so I see less of the code clutter my program. From ianb at colorstudy.com Wed Jun 11 12:19:12 2008 From: ianb at colorstudy.com (Ian Bicking) Date: Wed, 11 Jun 2008 09:19:12 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> Message-ID: On Jun 7, 6:30?am, Nick Craig-Wood wrote: > Here is an attempt at a killable thread > > ?http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496960 > > and > > ?http://sebulba.wikispaces.com/recipe+thread2 I use this recipe in paste.httpserver to kill wedged threads, and it works okay. It seems to kill threads that are genuinely wedged, e.g., if you try to read past the end of a socket. It takes surprisingly long, up to a minute to actually send the exception to a thread. But it's just a normal exception and seems to act reasonably. Obviously this is not a great system, but it's better than having a background process hang because of problem code elsewhere in the system. It also isn't any worse than kill -9, which is ultimately what a multiprocess system has to do to misbehaving worker processes. Still, to try to mitigate problems with this I set up a supervisor process and if there is a lot of problems with worker threads I'll have the entire process self-destruct so it can be restarted by the supervisor. The code is rather... organic in its development. But you can see it in the ThreadPool here: http://svn.pythonpaste.org/Paste/trunk/paste/httpserver.py Ian From mccredie at gmail.com Thu Jun 5 16:39:32 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 5 Jun 2008 13:39:32 -0700 (PDT) Subject: Token Error: EOF in multiline statement References: Message-ID: <8d7b532c-9801-4a56-b9fa-ca0e7e152bdf@e39g2000hsf.googlegroups.com> On Jun 5, 12:58 pm, maehhheeyy wrote: > I'm not sure what it means but it always highlights the last line with > nothing on it. My program has 63 lines and it highlights the 64th > line. This keeps popping up whenever I try to run my program. Can you > please help me fix this? You are going to have to post the code or at least the exception text. It sounds like the last line of your code is missing a needed parentheses, but it is impossible to know without more input. Matt From johnjsal at gmailNOSPAM.com Sat Jun 14 14:54:02 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sat, 14 Jun 2008 14:54:02 -0400 Subject: Creating a TCP/IP connection on already-networked computers In-Reply-To: <4854123f$0$5017$607ed4bc@cv.net> References: <4853f269$0$11615$607ed4bc@cv.net> <4854123f$0$5017$607ed4bc@cv.net> Message-ID: <485413d0$0$4997$607ed4bc@cv.net> John Salerno wrote: > ----- > #!/usr/bin/env python > > from socket import * > from time import ctime > > HOST = '192.168.1.100' > ----- > #!/usr/bin/env python > > from socket import * > > HOST = '192.168.1.100' A question about this. Is the "HOST" referring to the IP address of the server computer in both of these cases? Because when I ran the program and got to the part where it says "connected from:" on the server side, it shows this same IP address. Shouldn't it be something different, since the requests are coming from a different computer than the server computer? From fetchinson at googlemail.com Wed Jun 25 04:03:29 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 25 Jun 2008 01:03:29 -0700 Subject: automatically import modules upon interpreter invocation Message-ID: Hi folks, this seems like a very basic thing but I couldn't find a solution. I always do the following after starting the python interpreter (on linux): import rlcompleter import readline readline.parse_and_bind("tab: complete") Is there a way of making python execute the above whenever it starts up so that I don't have to type it all the time? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From i.i at i.i Sun Jun 22 14:35:26 2008 From: i.i at i.i (Josip) Date: Sun, 22 Jun 2008 20:35:26 +0200 Subject: Storing value with limits in object References: <2b0f1f77-98a2-4e1a-9427-7b7936ee7bf0@d77g2000hsb.googlegroups.com> Message-ID: > I bet you didn't even try this, unless your definition of "works" > includes a "RuntimeError: maximum recursion depth exceeded". Here's a > a working version: Actually, the version I'm using is somewhat bigger. I removed docstrings and recklessly stripped away some methods to make it shorter concise and incorrect. > For (most) math.* functions it suffices to define __float__, so the > above works. For making it behave (almost) like a regular number, > you'd have to write many more special methods: > http://docs.python.org/ref/numeric-types.html. > Here's a possible start: > (...) Yes, this is very close to what I was looking for. It implements all the functionality except asssigning values. And speed is not an issue for my application. Thanks. From russblau at hotmail.com Wed Jun 4 13:02:51 2008 From: russblau at hotmail.com (Russell Blau) Date: Wed, 4 Jun 2008 13:02:51 -0400 Subject: re References: <6anvi4F38ei08U1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote in message news:6anvi4F38ei08U1 at mid.uni-berlin.de... > David C. Ullrich schrieb: >> Say I want to replace 'disc' with 'disk', but only >> when 'disc' is a complete word (don't want to change >> 'discuss' to 'diskuss'.) The following seems almost >> right: >> >> [^a-zA-Z])disc[^a-zA-Z] >> >> The problem is that that doesn't match if 'disc' is at >> the start or end of the string. Of course I could just >> combine a few re's with |, but it seems like there should >> (or might?) be a way to simply append a \A to the first >> [^a-zA-Z] and a \Z to the second. > > Why not > > ($|[\w])disc(^|[^\w]) > > I hope \w is really the literal for whitespace - might be something > different, see the docs. No, \s is the literal for whitespace. http://www.python.org/doc/current/lib/re-syntax.html But how about: text = re.sub(r"\bdisc\b", "disk", text_to_be_changed) \b is the "word break" character, it matches at the beginning or end of any "word" (where a word is any sequence of \w characters, and \w is any alphanumeric character or _). Note that this solution still doesn't catch "Disc" if it is capitalized. Russ From pfreixes at gmail.com Thu Jun 19 18:27:37 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Fri, 20 Jun 2008 00:27:37 +0200 Subject: Google-like "Did you mean... ?" search algorithm In-Reply-To: <7a8313a1-1536-4754-ab4d-9cce4fa1b31a@y38g2000hsy.googlegroups.com> References: <7a8313a1-1536-4754-ab4d-9cce4fa1b31a@y38g2000hsy.googlegroups.com> Message-ID: <207312b70806191527j1ba14dd1jb7e558d97273cea2@mail.gmail.com> Do you need a [1] ngram theory, with this you can solve a orthographical problems, suggestion searches and other thinks [1] http://en.wikipedia.org/wiki/N-gram On Fri, Jun 20, 2008 at 12:14 AM, wrote: > This is a wee bit OT, but I am looking for algorithms to implement > search suggestions, similar to Google's "Did you mean... ?" feature. > Can anyone point me to web pages, journal articles, implementations > (preferably in Python!), or any other resources in this area? > > Thanks! > -- > http://mail.python.org/mailman/listinfo/python-list > -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From sri_annauni at yahoo.co.in Fri Jun 20 13:56:38 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Fri, 20 Jun 2008 23:26:38 +0530 (IST) Subject: Execute a script on a remote machine Message-ID: <515422.11724.qm@web7902.mail.in.yahoo.com> This is ok. Is there any other way to find it out? Thanks, Srini ----- Original Message ---- From: Gerhard H?ring To: python-list at python.org Sent: Friday, 20 June, 2008 10:03:30 PM Subject: Re: Execute a script on a remote machine srinivasan srinivas wrote: > Hi, > My requirement is i have to execute a python script on a remote machine as a subprocess from a python script and to get the subprocess pid of the process running the script. Is there anyway to do that?? > I have used subprocess.popen() method to do that. I have done as following: > executable = '/usr/bin/rsh' > args = [executable, hostname, scriptname] > pid = subprocess.popen(args) > It returned the pid of rsh. But i am interested in the pid of the process running the script. > Can anyone help me out here? Using os.getpid() you can find out the pid of the script and communicate it back to the caller. -- Gerhard -- http://mail.python.org/mailman/listinfo/python-list Save all your chat conversations. Find them online at http://in.messenger.yahoo.com/webmessengerpromo.php From Bob.Swithers at comcast.net Sat Jun 7 23:37:15 2008 From: Bob.Swithers at comcast.net (BobAtVandy) Date: Sat, 7 Jun 2008 23:37:15 -0400 Subject: How to get System.Timers.Timer Message-ID: <2KSdncr7xeVoztbVnZ2dnUVZ_qninZ2d@comcast.com> I'll greatly appreciate any help on this. Actually 2 questions: 1. I believe I need to use the Windows timer System.Timers.Timer . The examples I find on the web all access that timer by 'import System' . (That's System with a capital S.) I have pywin32 installed and 'import System' doesn't find System so I gather it's not in that package. Where does one get the package with Windows' System class? 2. The reason I've been looking at System.Timers.Timer is that I've written a windows-display app and I also use a timer from wx.PyTimer. However, I cannot close the window by clicking the X (Close button) at the top right of the window. And, I then tried explicitly capturing an OnClose event and that doesn't fire either. I then discovered that if I disable the wx.PyTimer, the window can be closed, and so I'm looking to try to use System.Timers.Timer under the theory (hope) that will avoid this problem of the window's not being close-able. Can anyone explain why the window won't close? Is System.Timers.Timer likely to solve my problem? If not, what would? Again, MANY thanks to anyone who can steer me in the right direction. From Russ.Paielli at gmail.com Thu Jun 5 21:09:40 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Thu, 5 Jun 2008 18:09:40 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> <4847d203$0$32733$426a74cc@news.free.fr> <87lk1jzgri.fsf@mulj.homelinux.net> Message-ID: <39a7805f-6590-4505-bfa2-0735090d553b@t12g2000prg.googlegroups.com> On Jun 5, 2:57 pm, Hrvoje Niksic wrote: > "Russ P." writes: > > By the way, my recollection is that in C++ access defaults to private > > if nothing is declared explicity. So normally the "private" > > declaration is unnecessary. If it is left out, your little trick won't > > work. > > How about #define class struct I never thought of that one. I wonder what the C++ gurus would say about that. Let me guess. They'd probably say that the access restrictions are for your own good, and bypassing them is bound to do you more harm than good in the long run. And they'd probably be right. Just because you can break into a box labeled "DANGER HIGH VOLTAGE," that doesn't make it a good idea. This just goes to show that the whole idea of using header files as simple text insertions is flaky to start with, and adding the preprocessor just compounds the flakiness. Needless to say, I'm not a big fan of C and C++. From fetchinson at googlemail.com Mon Jun 9 20:23:28 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 9 Jun 2008 17:23:28 -0700 Subject: access variables from one Python session to another on the same machine? In-Reply-To: <6ea6b084-3897-43f9-b8e0-dff52b47f1a0@w1g2000prd.googlegroups.com> References: <6ea6b084-3897-43f9-b8e0-dff52b47f1a0@w1g2000prd.googlegroups.com> Message-ID: > Suppose I have two different command windows going on the same > machine, each running their own Python interpreters. > > Is it possible to access the variables in one of the interpreter- > sessions from the other? > > It turns out I have limited control over one of the sessions (i.e. > cannot control all the code that is run from there), but complete > control over the other. > > I get the feeling this has been asked before, but I'm not sure how to > pose the question in such a way that it would show up on a search. > It's confusing. Depending on what 'limited control' means, the simplest choice would be writing stuff to a plain text file from the master and reading it from the slave. This may or may not work depending on your environment though. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From lajam at caramail.com Fri Jun 27 09:51:52 2008 From: lajam at caramail.com (lajam at caramail.com) Date: Fri, 27 Jun 2008 06:51:52 -0700 (PDT) Subject: where is the error? References: <8f8e1bf7-78b0-4292-9d56-396527b9dfb1@z66g2000hsc.googlegroups.com> <15ea1cb1-76a3-4fd3-8e4c-521b9aefcca2@m3g2000hsc.googlegroups.com> Message-ID: <014f77d9-0d16-4e70-8c6d-b1d728d14dff@25g2000hsx.googlegroups.com> > > I think that you mean that diff_temp will be an array of the numberS > (plural) of the lines (rows?) in values array that met the -2 < x < 2 > criterion. Now you want to be able to use diff_temp to get the > corresponding subset of some other array. Am I getting close? I think that you're getting close. I want to get the lines that met the criterion. Diff_temp is an array containing the values of the lines. So bascially, > Now you want to be able to use diff_temp to get the corresponding > subset of some other array. Am I getting close? yes > Perhaps you need something like other_array.take(diff_temp) ? And my problem was that the commands worked on windows but not on linux. > By the way, shouldn't you be using numpy? I thought numarray was going > away by mid-2008 i.e. now. I know, but i'm not sure that it's the problem. Thanks Cedric From george.sakkis at gmail.com Wed Jun 18 17:05:48 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 18 Jun 2008 14:05:48 -0700 (PDT) Subject: Function argument conformity check References: <0efa09ce-dbf9-4699-b87c-34c2c3b271f0@34g2000hsh.googlegroups.com> <9577cf2e-4440-4d97-b8e8-1dbc00bfca68@34g2000hsh.googlegroups.com> Message-ID: <69945a53-6e27-428a-a92a-5a9eab695134@e53g2000hsa.googlegroups.com> On Jun 18, 3:41?pm, dlists.... at gmail.com wrote: > On Jun 18, 3:13 pm, C?dric Lucantis wrote: > > > > > Hi, > > > Le Wednesday 18 June 2008 20:19:12 dlists.... at gmail.com, vous avez ?crit : > > > > Hi. I am looking for a way to check if some given set of (*args, > > > **kwds) conforms to the argument specification of a given function, > > > without calling that function. > > > > For example, given the function foo: > > > def foo(a, b, c): pass > > > > and some tuple args and some dict kwds, is there a way to tell if i > > > _could_ call foo(*args, **kwds) without getting an exception for those > > > arguments? I am hoping there is a way to do this without actually > > > writing out the argument logic python uses. > > > Each function object is associated to a code object which you can get with > > foo.func_code. Two of this object's attributes will help you: co_argcount and > > co_varnames. The first is the number of arguments of the function, and the > > second a list of all the local variables names, including the arguments > > (which are always the first items of the list). When some arguments have > > default values, they are stored in foo.func_defaults (and these arguments are > > always after non-default args in the co_argnames list). > > > Finally, it seems that some flags are set in code.co_flags if the function > > accepts varargs like *args, **kwargs, but I don't know where these are > > defined. > > > Note that I never found any doc about that and merely guessed it by playing > > with func objects, so consider all this possibly wrong or subject to change. > > > -- > > C?dric Lucantis > > I am aware of these attributes, although you can get them all in a > more organized form using the getfullargspec function in the inspect > module from the standard library. > > The problem is that using these attributes, I would essentially have > to re-write the logic python uses when calling a function with a given > set of arguments. I was hoping there is a way to get at that logic > without rewriting it. Sure; copy it from someone that has already done it ;-) http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/551779 HTH, George From jeff at jmcneil.net Wed Jun 4 16:26:23 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 4 Jun 2008 16:26:23 -0400 Subject: Unable to write output from os.path.walk to a file. In-Reply-To: <125994.42643.qm@web52909.mail.re2.yahoo.com> References: <125994.42643.qm@web52909.mail.re2.yahoo.com> Message-ID: <82d28c40806041326m2a26695t233d019ffa583c8c@mail.gmail.com> What exactly are you trying to accomplish? If you're just looking for the contents of a directory, it would be much easier to simply call os.listdir(dirinput) as that will return a list of strings that represent the entries in dirinput. As it stands, 'os.path.walk' will return None in your example, thus the reason f.writelines is failing, the error says something about a required iterable, no? You ought to look at os.walk anyways, as I believe it is the preferred approach when walking a directory hierarchy. It's a generator that will yield a tuple that contains (dirname, subdirectories, filenames). It seems that is what you're looking for? Thanks, Jeff On Wed, Jun 4, 2008 at 2:54 PM, Paul Lemelle wrote: > I Am trying to output the os.path.walk to a file, but the writelines method complains.... > > Below is the code, any helpful suggestions would be appreciated. > > def visit(arg, dirnames, names): > print dirnames > > > > > dirinput = raw_input("Enter directory to read: ") > > listdir = os.path.walk (dirinput, visit, None) > > f = open("walktxt", "w") > > f.writelines(listdir) > > f.close() > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From ptmcg at austin.rr.com Thu Jun 12 09:45:56 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 12 Jun 2008 06:45:56 -0700 (PDT) Subject: get keys with the same values References: Message-ID: <3fdafa74-2043-4052-bdec-843f69d9e5fa@e39g2000hsf.googlegroups.com> On Jun 12, 6:41?am, David C. Ullrich wrote: > On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader > wrote: > > >Hello, > > >I have a dictionary and will get all keys which have the same values. > > > d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} > > dd = {} > > for key, value in d.items(): > ? try: > ? ? dd[value].append(key) > ? except KeyError: > ? ? dd[value] = [key] > Instead of all that try/except noise, just use the new defaultdict: >>> from collections import defaultdict >>> >>> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} >>> >>> dd = defaultdict(list) >>> for key, value in d.items(): ... dd[value].append(key) ... >>> for k,v in dd.items(): ... print k,':',v ... 1 : ['a', 'e'] 2 : ['c'] 3 : ['b', 'd'] 4 : ['f'] -- Paul From basti.wiesner at gmx.net Tue Jun 10 07:56:21 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Tue, 10 Jun 2008 13:56:21 +0200 Subject: Separators inside a var name References: Message-ID: Rainy at Dienstag 10 Juni 2008 02:53: > Well, I agree, this is terrible. If I were Guido I'd > make a very explicit rule that a certain naming > scheme is preferred and other schemes are very bad. FWIW, there is a preferred naming scheme outlined in PEP 8. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From jaraco at jaraco.com Fri Jun 13 12:28:45 2008 From: jaraco at jaraco.com (Jason R. Coombs) Date: Fri, 13 Jun 2008 10:28:45 -0600 Subject: namedtuple suggestions In-Reply-To: References: <318037bd-e126-4c41-ac65-c2afb9fd768d@w7g2000hsa.googlegroups.com> Message-ID: <750B64C66078B34D918257A1AC004DB20307B0@messiah.jaraco.com> I also agree with your point on concatting. I used that syntax because it seemed more clear, given the already awkward syntax. And while the original motivation of namedtuple might be to avoid having to make a class or subclass, subclasses have already emerged even within the standard library (see lib/urlparse for a prime example of extending the namedtuple class). Regards, Jason -----Original Message----- From: Calvin Spealman [mailto:ironfroggy at socialserve.com] Sent: Friday, 13 June, 2008 12:17 To: Jason R. Coombs Cc: python-list at python.org Subject: Re: namedtuple suggestions On Jun 13, 2008, at 11:17 AM, Jason R. Coombs wrote: > I see a new function in (python 2.6) lib/collections called > namedtuple. This is a great function. I can see many places in my > code where this will be immensely useful. > > I have a couple of suggestions. > > My first suggestion is to use self.__class__.__name__ instead of the > hard-coded typename in __repr__, so that subclasses don't have to > override these methods just to use the correct name. > > def __repr__(self): > return self.__class__.__name__ + '(%(reprtxt)s)' %% self > \n I feel like a large point of NamedTuple is for those cases where you need a small object with some attributes _without_ creating a subclass. Useful for mocks, for example, or when you need to trick a function into dealing with a quick proxy or stub. If a large point is not needing to create a class but instead creating a cheap object, should it be a good idea to then subclass the very thing that was intended to help you avoid creating a class in the first place? What do you gain subclassing it? However, I always think a repr reflecting a type name should reflect the correct type, so I'm not disagreeing on that point. But, just don't use concating :-) -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 6580 bytes Desc: not available URL: From nick at craig-wood.com Sat Jun 28 07:32:35 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 28 Jun 2008 06:32:35 -0500 Subject: C++ or Python References: Message-ID: Kurda Yon wrote: > I would like to know what are advantages of Python in comparison with C > ++? In which cases and why Python can be a better tool than C++? Python is a lot more fun than C++ ;-) Anyway no need to use one or the other... I've done projects where we've embedded python into into a large C++ program to give easy scriptability to our application in a real language. I've also done the reverse - embedded C/C++ into python. And for the really easy option there is ctypes. Given a blank canvas I'd start with python and then add a bit of C/C++ if some part of it was running too slowly. If there were existing C/C++ libraries then I'd use ctypes to interface with them. I don't think I ever want to start another large C++ app - been there, done that, got the (mental) scars to prove it ;-) All my humble opinion of course! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From gagsl-py2 at yahoo.com.ar Fri Jun 13 13:31:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Jun 2008 14:31:18 -0300 Subject: GIL cpu multi core usage problem References: <207312b70806091126t6d9c3479hfe39368cd06b029e@mail.gmail.com> <207312b70806130455h4db9c6dn91485837b7a4bf1c@mail.gmail.com> Message-ID: En Fri, 13 Jun 2008 08:55:30 -0300, Pau Freixes escribi?: > When you say this "C extensions (usually) release the GIL when they don't > call into any Python code" do you talk about this macros ? > > Py_BEGIN_ALLOW_THREADS > > Py_END_ALLOW_THREADS Exactly. -- Gabriel Genellina From kurdayon at yahoo.com Mon Jun 30 19:44:07 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Mon, 30 Jun 2008 16:44:07 -0700 (PDT) Subject: Functions associated with a class. Message-ID: Hi, I start to learn the object oriented programing in Python. As far as I understood, every class has a set of corresponding methods and variables. For me it is easy to understand a method as a one-argument function associated with a class. For example, if I call "x.calc" and "y.calc" and if "x" and "y" belongs to different classes I, actually, call to different function (the first one is associated with the first class and the second one with the second class). If "x" and "y" belongs to the same class, the "x.calc" and "y.calc" refer to the same function (but called with different arguments ("x" and "y", respectively)). In the above described case we have one-argument function. But what should we do if we one two have a two-argument function. For example, we want to have a method "calc" which take two objects and returns one value. How do we call this method? Like "x&y.calc"? Or just calc(x,y)? In the case of the one-argument functions Pythons automatically decide which function to call (associated with the first class or with the second class). Will it be the same in the case of the two-argument function. I am not sure that I am clear. If I am not clear, just ask me. I will try to reformulate my questions. Thank you. From mccredie at gmail.com Wed Jun 18 13:54:29 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 18 Jun 2008 10:54:29 -0700 (PDT) Subject: How to split a string containing nested commas-separated substrings References: <0b568cf3-ecce-4da0-9d23-1cbfe47a5fe7@m36g2000hse.googlegroups.com> Message-ID: <31c424a3-15cf-4ecb-bcf6-5edd24aa19ca@s50g2000hsb.googlegroups.com> On Jun 18, 10:19 am, Robert Dodier wrote: > Hello, > > I'd like to split a string by commas, but only at the "top level" so > to speak. An element can be a comma-less substring, or a > quoted string, or a substring which looks like a function call. > If some element contains commas, I don't want to split it. > > Examples: > > 'foo, bar, baz' => 'foo' 'bar' 'baz' > 'foo, "bar, baz", blurf' => 'foo' 'bar, baz' 'blurf' > 'foo, bar(baz, blurf), mumble' => 'foo' 'bar(baz, blurf)' 'mumble' > > Can someone suggest a suitable regular expression or other > method to split such strings? > > Thank you very much for your help. > > Robert You might look at the shlex module. It doesn't get you 100%, but its close: >>> shlex.split('foo, bar, baz') ['foo,', 'bar,', 'baz'] >>> shlex.split( 'foo, "bar, baz", blurf') ['foo,', 'bar, baz,', 'blurf'] >>> shlex.split('foo, bar(baz, blurf), mumble') ['foo,', 'bar(baz,', 'blurf),', 'mumble'] Using a RE will be tricky, especially if it is possible to have recursive nesting (which by definition REs can't handle). For a real general purpose solution you will need to create a custom parser. There are a couple modules out there that can help you with that. pyparsing is one: http://pyparsing.wikispaces.com/ Matt From martin at v.loewis.de Sun Jun 1 14:43:54 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 01 Jun 2008 20:43:54 +0200 Subject: ValueError: unknown locale: UTF-8 In-Reply-To: References: Message-ID: <4842edea$0$25496$9b622d9e@news.freenet.de> > ValueError: unknown locale: UTF-8 >>>> > > This is on open bug or is there more to it? Do you have an environment variable set who is named either LANG or starts with LC_? Regards, Martin From ironfroggy at socialserve.com Mon Jun 16 09:20:35 2008 From: ironfroggy at socialserve.com (Calvin Spealman) Date: Mon, 16 Jun 2008 09:20:35 -0400 Subject: PEP 372 -- Adding an ordered directory to collections In-Reply-To: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> Message-ID: <745B0ED0-F59E-4588-9209-A90282AEDD5E@socialserve.com> This gets my +1, for what its worth. I don't really see a good reason not to include the insert() method, however. I don't see that it would complicate things much, if at all. >>> d = odict([('a', 42), ('b', 23)]) >>> d.insert(1, ('c', 19)) >>> d collections.odict([('a', 42), ('c', 19), ('b', 23)]) On Jun 16, 2008, at 4:37 AM, Armin Ronacher wrote: > Abstract > ======== > > This PEP proposes an ordered dictionary as a new data structure for > the ``collections`` module, called "odict" in this PEP for short. The > proposed API incorporates the experiences gained from working with > similar implementations that exist in various real-world applications > and other programming languages. > > > Rationale > ========= > > In current Python versions, the widely used built-in dict type does > not specify an order for the key/value pairs stored. This makes it > hard to use dictionaries as data storage for some specific use cases. > > Some dynamic programming languages like PHP and Ruby 1.9 guarantee a > certain order on iteration. In those languages, and existing Python > ordered-dict implementations, the ordering of items is defined by the > time of insertion of the key. New keys are appended at the end, keys > that are overwritten and not moved. > > The following example shows the behavior for simple assignments: > >>>> d = odict() >>>> d['parrot'] = 'dead' >>>> d['penguin'] = 'exploded' >>>> d.items() > [('parrot', 'dead'), ('penguin', 'exploded')] > > That the ordering is preserved makes an odict useful for a couple of > situations: > > - XML/HTML processing libraries currently drop the ordering of > attributes, use a list instead of a dict which makes filtering > cumbersome, or implement their own ordered dictionary. This affects > ElementTree, html5lib, Genshi and many more libraries. > > - There are many ordererd dict implementations in various libraries > and applications, most of them subtly incompatible with each other. > Furthermore, subclassing dict is a non-trivial task and many > implementations don't override all the methods properly which can > lead to unexpected results. > > Additionally, many ordered dicts are implemented in an inefficient > way, making many operations more complex then they have to be. > > - PEP 3115 allows metaclasses to change the mapping object used for > the class body. An ordered dict could be used to create ordered > member declarations similar to C structs. This could be useful, for > example, for future ``ctypes`` releases as well as ORMs that define > database tables as classes, like the one the Django framework ships. > Django currently uses an ugly hack to restore the ordering of > members in database models. > > - Code ported from other programming languages such as PHP often > depends on a ordered dict. Having an implementation of an > ordering-preserving dictionary in the standard library could ease > the transition and improve the compatibility of different libraries. > > > Ordered Dict API > ================ > > The ordered dict API would be mostly compatible with dict and existing > ordered dicts. (Note: this PEP refers to the Python 2.x dictionary > API; the transfer to the 3.x API is trivial.) > > The constructor and ``update()`` both accept iterables of tuples as > well as mappings like a dict does. The ordering however is preserved > for the first case: > >>>> d = odict([('a', 'b'), ('c', 'd')]) >>>> d.update({'foo': 'bar'}) >>>> d > collections.odict([('a', 'b'), ('c', 'd'), ('foo', 'bar')]) > > If ordered dicts are updated from regular dicts, the ordering of new > keys is of course undefined again unless ``sort()`` is called. > > All iteration methods as well as ``keys()``, ``values()`` and > ``items()`` return the values ordered by the the time the key-value > pair was inserted: > >>>> d['spam'] = 'eggs' >>>> d.keys() > ['a', 'c', 'foo', 'spam'] >>>> d.values() > ['b', 'd', 'bar', 'eggs'] >>>> d.items() > [('a', 'b'), ('c', 'd'), ('foo', 'bar'), ('spam', 'eggs')] > > New methods not available on dict: > > ``odict.byindex(index)`` > > Index-based lookup is supported by ``byindex()`` which returns > the key/value pair for an index, that is, the "position" of a > key in the ordered dict. 0 is the first key/value pair, -1 > the last. > >>>> d.byindex(2) > ('foo', 'bar') > > ``odict.sort(cmp=None, key=None, reverse=False)`` > > Sorts the odict in place by cmp or key. This works exactly > like ``list.sort()``, but the comparison functions are passed > a key/value tuple, not only the value. > >>>> d = odict([(42, 1), (1, 4), (23, 7)]) >>>> d.sort() >>>> d > collections.odict([(1, 4), (23, 7), (42, 1)]) > > ``odict.reverse()`` > > Reverses the odict in place. > > ``odict.__reverse__()`` > > Supports reverse iteration by key. > > > Questions and Answers > ===================== > > What happens if an existing key is reassigned? > > The key is not moved but assigned a new value in place. This is > consistent with existing implementations and allows subclasses to > change the behavior easily:: > > class movingcollections.odict): > def __setitem__(self, key, value): > self.pop(key, None) > odict.__setitem__(self, key, value) > > What happens if keys appear multiple times in the list passed to the > constructor? > > The same as for regular dicts: The latter item overrides the > former. This has the side-effect that the position of the first > key is used because the key is actually overwritten: > >>>> odict([('a', 1), ('b', 2), ('a', 3)]) > collections.odict([('a', 3), ('b', 2)]) > > This behavior is consistent with existing implementations in > Python, the PHP array and the hashmap in Ruby 1.9. > > Why is there no ``odict.insert()``? > > There are few situations where you really want to insert a key at > an specified index. To avoid API complication, the proposed > solution for this situation is creating a list of items, > manipulating that and converting it back into an odict: > >>>> d = odict([('a', 42), ('b', 23), ('c', 19)]) >>>> l = d.items() >>>> l.insert(1, ('x', 0)) >>>> odict(l) > collections.odict([('a', 42), ('x', 0), ('b', 23), ('c', 19)]) > > > Example Implementation > ====================== > > A poorly performing example implementation of the odict written in > Python is available: > > `odict.py odict.py>`_ > > The version for ``collections`` should be implemented in C and use a > linked list internally. > > Other implementations of ordered dicts in various Python projects or > standalone libraries, that inspired the API proposed here, are: > > - `odict in Babel`_ > - `OrderedDict in Django`_ > - `The odict module`_ > - `ordereddict`_ (a C implementation of the odict module) > - `StableDict`_ > - `Armin Rigo's OrderedDict`_ > > > .. _odict in Babel: http://babel.edgewall.org/browser/trunk/babel/ > util.py?rev=374#L178 > .. _OrderedDict in Django: > http://code.djangoproject.com/browser/django/trunk/django/utils/ > datastructures.py?rev=7140#L53 > .. _The odict module: http://www.voidspace.org.uk/python/odict.html > .. _ordereddict: http://www.xs4all.nl/~anthon/Python/ordereddict/ > .. _StableDict: http://pypi.python.org/pypi/StableDict/0.2 > .. _Armin Rigo's OrderedDict: http://codespeak.net/svn/user/arigo/ > hack/pyfuse/OrderedDict.py > > > Future Directions > ================= > > With the availability of an ordered dict in the standard library, > other libraries may take advantage of that. For example, ElementTree > could return odicts in the future that retain the attribute ordering > of the source file. > > > Copyright > ========= > > This document has been placed in the public domain. > -- > http://mail.python.org/mailman/listinfo/python-list From rdabane at gmail.com Wed Jun 4 02:48:38 2008 From: rdabane at gmail.com (rdabane at gmail.com) Date: Tue, 3 Jun 2008 23:48:38 -0700 (PDT) Subject: Help need with subprocess communicate References: <0312b7e9-bffe-4360-bf3a-f5b3b26d243d@l64g2000hse.googlegroups.com> <530ccda9-818e-4abe-9f82-0720e27c48fd@z72g2000hsb.googlegroups.com> Message-ID: <8aef95d4-065d-4afe-bed6-bb3b4aabe04e@u12g2000prd.googlegroups.com> On Jun 3, 11:23 pm, Dennis Lee Bieber wrote: > On Tue, 3 Jun 2008 18:04:40 -0700 (PDT), rdab... at gmail.com declaimed the > following in comp.lang.python: > > > > > Hi Daniel, > > Thanks for your reply.. > > I've done exactly as you suggested...but I'm still having problem with > > the read...it just gets stuck in > > the read ( I think because its a blocking read...) > > And it is likely blocking because the subprocess is doing buffered > output -- ie, nothing is available to be read because the output has not > been flushed. > > This is a problem with most programs when run as a subprocess -- it > is common for stdout, when routed to a pipe or file, to behave as a > buffered stream that only flushes when some x-bytes have been written; > unlike stdout to a console which gets flushed on each new-line. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ Is there way to configure the stdout buffer size so that it flushes earlier.. Is there a way to make above mentioned piece code working? From timr at probo.com Wed Jun 18 03:11:20 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 18 Jun 2008 07:11:20 GMT Subject: Python GC does not work as it should be References: Message-ID: "Jaimy Azle" wrote: > >Jean-Paul Calderone wrote: > >> A system exception? What's that? C doesn't have exceptions. > >How could I determine it? I dont know GCC implementation, and others, but C >on MSVC does have it. My application were not written in C, an exception >raised was something like "access violation at address xxxx on module >python25.dll", and MSVC debugger shows collecting state were not reset (1), >that is why GC would never happen. Correct. That error is not recoverable. If the garbage collector crashes, the collector is in an indeterminate state, so it is quite reasonable to prevent it from being called again. Here is an excellent rule: Never check for an exception that you are not prepared to handle. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ivan.illarionov at gmail.com Thu Jun 5 10:56:42 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 5 Jun 2008 07:56:42 -0700 (PDT) Subject: Tuples part 2 References: <6d3e6d40-63a6-40d1-8ea4-5ddf40238d8d@m44g2000hsc.googlegroups.com> Message-ID: <99bc30fb-532a-4c4f-9f5e-e7a18c28d2a5@z72g2000hsb.googlegroups.com> On 5 ???, 18:19, "victor.hera... at gmail.com" wrote: > On Jun 5, 3:49 pm, Ivan Illarionov wrote: > > > > > On 5 ???, 01:57, "victor.hera... at gmail.com" > > wrote: > > > > Hi Everyone, > > > > i have another question. What if i wanted to make n tuples, each with > > > a list of coordinates. For example : > > > > coords = list() > > > for h in xrange(1,11,1): > > > for i in xrange(1, 5, 1) : > > > for j in xrange(1, 5, 1) : > > > for k in xrange(1,2,1) : > > > coords.append((i,j,k)) > > > lista+str(h)= tuple coords > > > print tuple(coords) > > > > so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do > > > it the way i show you above but it is not working properly. I wish you > > > could help me with that. Thanks again, > > >>> from itertools import repeat, izip > > >>> coords = tuple((i,j,k) for i in xrange(1,5) for j in xrange(1,5) for k in xrange(1,2)) > > >>> locals().update(("tuple%s" % i, coord) for i, coord in izip(xrange(1,11), repeat(coords))) > > >>> tuple1 > > > ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (2, 1, 1), (2, 2, 1), (2, > > 3, 1), (2 > > , 4, 1), (3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1), (4, 1, 1), (4, 2, > > 1), (4, 3 > > , 1), (4, 4, 1)) > > > Does this help? > > > But I don't understand why you need this? > > > Ivan > > Hi, > > What i need is, for example: > > tuple 1=((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)) > > tuple 2=((2, 1, 1), (2, 2, 1), (2, 3, 1), (2, 4, 1)) > > tuple 3=((3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1)) > > and so on. Please help me and sorry for not taking the time to post my > questions properly. > > Victor Or even so: locals().update(("tuple_%s" % i, tuple((i,j,k) for j in range(1,5) for k in range(1,2))) for i in range(1,5)) Ivan From spoier at gmail.com Mon Jun 9 17:32:08 2008 From: spoier at gmail.com (Skye) Date: Mon, 9 Jun 2008 14:32:08 -0700 (PDT) Subject: Question by someone coming from C... References: <9d40211d-e03f-4f0c-a512-3ac78b0ede21@i18g2000prn.googlegroups.com> Message-ID: <4789a069-1038-4ee2-a2d6-933a9eaf6e2e@s21g2000prm.googlegroups.com> OK, sounds good. So if not bitfields, what would be a good Python-y way to do it? Flip booleans in a "debug config" dictionary or something? Skye From usenet at janc.be Sat Jun 7 18:27:38 2008 From: usenet at janc.be (Jan Claeys) Date: Sat, 07 Jun 2008 22:27:38 GMT Subject: definition of a highlevel language? References: <2759eed3-956d-45c7-8dfb-9557f74133b3@56g2000hsm.googlegroups.com> <26d0b3d2-01cc-49bd-b284-1a849b0b835f@y38g2000hsy.googlegroups.com> <34dcbdc1-5285-41ec-be06-c88c56bb0372@i76g2000hsf.googlegroups.com> <45f03028-a86c-4357-9aa2-0148f7cc84dc@d45g2000hsc.googlegroups.com> Message-ID: Op Mon, 26 May 2008 15:49:33 -0400, schreef Dan Upton: > The point about them looking very little like x86/ARM/etc chips is the > important part though--IIRC, part of the failure of Java machines was > lousy support for preexisting code, due to the optimizations for Java > bytecode, and I expect the same would be true of a Python > bytecode-optimized processor. AFAIK "Java processors" are mostly used as coprocessors next to an ARM core (or similar), allowing you to run Java applications at a reasonable speed on otherwise relatively slow mobile phone CPUs and the like. In theory, it's possible to design a processor that can run some form of Python-oriented bytecode quite effici?ntly, but I fear that nobody really wants to invest the money to do so at the moment? -- JanC From __peter__ at web.de Tue Jun 3 04:22:55 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Jun 2008 10:22:55 +0200 Subject: Merging ordered lists References: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> <8140b81b-bfa1-463b-a92a-19c0f6453444@k30g2000hse.googlegroups.com> Message-ID: etal wrote: > > def unique(items): > > ? ? u = set(items) > > ? ? if len(u) == len(items): > > ? ? ? ? return items > > ? ? result = [] > > ? ? for item in items: > > ? ? ? ? if item in u: > > ? ? ? ? ? ? result.append(item) > > ? ? ? ? ? ? u.remove(item) > > ? ? return result > > You did right by preserving the original (non-alphabetical) ordering, > but I'm less enthusiastic about the shape of this function. My > original function used 7 lines of code, and only 1 for the unique() > step. This uses up to three container objects. Is it really an > improvement? Yes :) Seriously, you are using O(n) containers and O(n) lookup where mine uses O(1). For short lists it doesn't matter, but as the list length grows the difference gets huge: $ cat unique.py def unique(items): u = set(items) if len(u) == len(items): return items result = [] for item in items: if item in u: result.append(item) u.remove(item) return result def unique_lc(ref): return [r for i, r in enumerate(ref) if r and r not in ref[i+1:]] sample_a = range(1000) sample_b = range(1000) import random for i in random.sample(sample_b, 10): sample_b[i] = 0 $ python -m timeit -s"from unique import unique as u, sample_a as s" "u(s)" 10000 loops, best of 3: 52.8 usec per loop $ python -m timeit -s"from unique import unique_lc as u, sample_a as s" "u(s)" 10 loops, best of 3: 44.2 msec per loop 3 orders of magnitude for the shortcut. $ python -m timeit -s"from unique import unique as u, sample_b as s" "u(s)" 1000 loops, best of 3: 646 usec per loop $ python -m timeit -s"from unique import unique_lc as u, sample_b as s" "u(s)" 10 loops, best of 3: 39 msec per loop Still 2 orders of magnitude if my unique() does some actual work. Peter From sturlamolden at yahoo.no Tue Jun 3 22:53:25 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 3 Jun 2008 19:53:25 -0700 (PDT) Subject: How to perform a nonblocking read from a process References: <15c889d4-3e06-4ffd-a86e-10cfa87d3bc5@k37g2000hsf.googlegroups.com> Message-ID: On Jun 4, 3:20 am, rdab... at gmail.com wrote: > It seems that stdout.readline() is a blocking read and it just gets > stuck their.. > How to fix this .. Threads are the simplest remedy for blocking i/o. From michele.simionato at gmail.com Tue Jun 24 05:37:48 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 24 Jun 2008 02:37:48 -0700 (PDT) Subject: Python 3000 vs Perl 6 References: <89fbe834-68b7-49e6-8136-62dee53c2f40@t54g2000hsg.googlegroups.com> Message-ID: <7bad9ebd-81ab-48c4-854b-05f085e9d936@27g2000hsf.googlegroups.com> On Jun 24, 11:16?am, cokofree... at gmail.com wrote: > Towards it being more advanced than Python 3k, time will tell. It is worth reminding that, in more than one sense, the most advanced language is the one with less features ... Michele Simionato From pfreixes at gmail.com Sun Jun 15 10:22:22 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Sun, 15 Jun 2008 16:22:22 +0200 Subject: please critique my thread code In-Reply-To: <222a1935-20dd-44a0-bc42-71a25be96d30@79g2000hsk.googlegroups.com> References: <222a1935-20dd-44a0-bc42-71a25be96d30@79g2000hsk.googlegroups.com> Message-ID: <207312b70806150722o4f678v6ab404d79dba2f34@mail.gmail.com> Hi, The main while in main thread spend all cpu time, it's more convenient put one little sleep between each iteration or use a some synchronization method between threads. And about your questions IMO: > --- Are my setup and use of threads, the queue, and "while True" loop > correct or conventional? May be, exist another possibility but this it's good, another question is if iterate arround the 240000 numbers it's the more efficient form for retrieve all projects. --- Should the program sleep sometimes, to be nice to the SourceForge > servers, and so they don't think this is a denial-of-service attack? You are limiting your number of connections whit you concurrent threads, i don't believe that SourceForge have a less capacity for request you concurrent threads. > > --- Someone told me that popen is not thread-safe, and to use > mechanize. I installed it and followed an example on the web site. > There wasn't a good description of it on the web site, or I didn't > find it. Could someone explain what mechanize does? I don't know , but if you don't sure you can use urllib2. > > --- How do I choose the number of threads? I am using a MacBook Pro > 2.4GHz Intel Core 2 Duo with 4 GB 667 MHz DDR2 SDRAM, running OS > 10.5.3. For default phtreads in linux flavor spend 8MB for thread stack, i dont know in you MacBook. i think between 64 to 128 threads it's correct. > > > Thank you. > > Winston > > > > #!/usr/bin/env python > > # Winston C. Yang > # Created 2008-06-14 > > from __future__ import with_statement > > import mechanize > import os > import Queue > import re > import sys > import threading > import time > > lock = threading.RLock() > > # Make the dot match even a newline. > error_pattern = re.compile(".*\n\n.*", re.DOTALL) > > def now(): > return time.strftime("%Y-%m-%d %H:%M:%S") > > def worker(): > > while True: > > try: > id = queue.get() > except Queue.Empty: > continue > > request = mechanize.Request("http://sourceforge.net/project/"\ > "memberlist.php?group_id=%d" % > id) > response = mechanize.urlopen(request) > text = response.read() > > valid_id = not error_pattern.match(text) > > if valid_id: > f = open("%d.csv" % id, "w+") > f.write(text) > f.close() > > with lock: > print "\t".join((str(id), now(), "+" if valid_id else > "-")) > > def fatal_error(): > print "usage: python application start_id end_id" > print > print "Get the usernames associated with each SourceForge project > with" > print "ID between start_id and end_id, inclusive." > print > print "start_id and end_id must be positive integers and satisfy" > print "start_id <= end_id." > sys.exit(1) > > if __name__ == "__main__": > > if len(sys.argv) == 3: > > try: > start_id = int(sys.argv[1]) > > if start_id <= 0: > raise Exception > > end_id = int(sys.argv[2]) > > if end_id < start_id: > raise Exception > except: > fatal_error() > else: > fatal_error() > > # Print the start time. > start_time = now() > print start_time > > # Create a directory whose name contains the start time. > dir = start_time.replace(" ", "_").replace(":", "_") > os.mkdir(dir) > os.chdir(dir) > > queue = Queue.Queue(0) > > for i in xrange(32): > t = threading.Thread(target=worker, name="worker %d" % (i + > 1)) > t.setDaemon(True) > t.start() > > for id in xrange(start_id, end_id + 1): > queue.put(id) > > # When the queue has size zero, exit in three seconds. > while True: > if queue.qsize() == 0: > time.sleep(3) > break > > print now() > -- > http://mail.python.org/mailman/listinfo/python-list > -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Mon Jun 23 11:14:08 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 23 Jun 2008 08:14:08 -0700 (PDT) Subject: Regular expression problem References: <181fe17d-61f0-40f4-89b4-99fe4c483bf7@k30g2000hse.googlegroups.com> Message-ID: On Jun 22, 10:13?pm, abranches wrote: > Hello everyone. > > I'm having a problem when extracting data from HTML with regular > expressions. > This is the source code: > > You are ready in the next
    style="display: inline;">12 span>M 48S > > And I need to get the remaining time. Until here, isn't a problem > getting it, but if the remaining time is less than 60 seconds then the > source becomes something like this: > > You are ready in the next
    style="display: inline;">36 span>S > > I'm using this regular expression, but the minutes are always None... > You are ready in the next.*?(?:>(\d+)M
    )?.*?(?:>(\d+) span>S) > > If I remove the ? from the first group, then it will work, but if > there are only seconds it won't work. > I could resolve this problem in a couple of python lines, but I really > would like to solve it with regular expressions. > Your regex is working like this: 1. Match 'You are ready in the next'. 2. Match an increasing number of characters, starting with none ('.*?'). 3. Try to match a pattern ('(?:>...)?') from where the previous step left off. This doesn't match, but it's optional anyway, so continue to the next step. (No characters consumed.) 4. Match an increasing number of characters, starting from none ('.*?'). It's this step that consumes the minutes. It then goes on to match the seconds, and the minutes are always None as you've found. I've come up with this regex: You are ready in the next(?:.*?>(\d+)M)?(?:.*?>(\d+)S) Hope that helps. From roy at panix.com Sun Jun 15 21:29:12 2008 From: roy at panix.com (Roy Smith) Date: Sun, 15 Jun 2008 21:29:12 -0400 Subject: newbie question: for loop within for loop confusion References: Message-ID: In article , takayuki wrote: > Hi, > > I'm studying python via the exellent book "How to think like a python > programmer" by Allen Downey. > > Noob question follows... > > animals.txt is a list of animals, each on a separate line: "aardvard, > bat, cat, dog, elephant, fish, giraffe, horse, insect, jackelope" > > I want to loop through the list of words and print words that don't > have any "avoid" letter in them. > > def hasnolet(avoid): > fin = open('animals.txt') > for line in fin: > word = line.strip() > for letter in avoid: > if letter in word: > break > else: > print word > > hasnolet('abcd') > I could give you a fish, or I could teach you to fish. I'd rather do the latter. So... Take your inner loop: > for letter in avoid: > if letter in word: > break > else: > print word and instrument it so you can see exactly what's happening. Try something like: > for letter in avoid: > print "letter = %s" % letter > if letter in word: > print "it's in word" > break > else: > print "no it's not" > print word and see if that helps. From ptmcg at austin.rr.com Mon Jun 16 09:46:59 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 16 Jun 2008 06:46:59 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> Message-ID: <8ec4632c-2cae-40d1-ba5d-8d88854dae52@m73g2000hsh.googlegroups.com> 1. With the current dict, the following code a = { "A" : 1, "B" : 2 } b = { "B" : 2, "A" : 1 } a==b evaluates to True. I assume that if these were odicts, this would evaluate to False. 2. Will odict.byindex support slicing? 3. Will odict inherit from dict? 4. The current dict API (as of Python 2.5) is given by dir as: ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] If I read your PEP correctly, you propose adding: byindex sort reverse __reverse__ (should be '__reversed__', to match list's reverse iterator) (This isn't really a question, your PEP was not completely explicit about what odict's API would be, so I thought enumerating what dict does currently might illuminate some other unresolved aspects of odict. For instance, since odict is somewhat list-like in its notion of keys and values, will pop support list-like popping as well as what dict currently provides? Will you need a 'popbyindex' for the same reason you need 'byindex', so that you have unambiguous lookup of items by index vs. by key. Perhaps doing dir(list) will help you to see other items to resolve/clarify.) 5. The more I think and write about this, the more struck I am at the similarity of odict and the ParseResults class in pyparsing. For instance, in ParseResults, there is also support for dict-style and list-style item referencing, and I chose to restrict some cases so that using [] notation would not be ambiguous. You might want to add pyparsing.ParseResults as another reference of current "odicts in the wild" (although ParseResults implements quite a bit of additional behavior that would not be required or necessarily appropriate for odict). I vote +0 on this PEP - I've never personally needed an odict, but I can see how some of the XML and ORM coding would be simplified by one. -- Paul (I could go either way on the name 'odict' or 'ordereddict'. Given the desire for this to evenutally become a built-in, keep the name short. On the other hand, collections already has 'defaultdict', so is 'ordereddict' so bad?) From sturlamolden at yahoo.no Wed Jun 4 18:16:19 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 4 Jun 2008 15:16:19 -0700 (PDT) Subject: multiprocessing module (PEP 371) References: <877a5774-d3cc-49d3-bb64-5cab8505a419@m3g2000hsc.googlegroups.com> <2953a72d-cdc7-4360-ac25-36618fe9229f@s50g2000hsb.googlegroups.com> Message-ID: On Jun 4, 11:29 pm, Paul Boddie wrote: > tested the executable on Windows. COW (copy-on-write, for those still > thinking that we're talking about dairy products) would be pretty > desirable if it's feasible, though. There is a well known C++ implementation of cow-fork on Windows, which I have slightly modified and ported to C. But as the new WDK (Windows driver kit) headers are full of syntax errors, the compiler choke on it. :( I am seriously considering re-implementing the whole cow fork in pure Python using ctypes. If you pass NULL as section handle to ZwCreateProcess (or NtCreateProcess) you do get a rudimentary cow fork. But the new process image has no context and no active threads. The NT kernel is designed to support several subsystems. Both the OS/2 and SUA subsystems provide a functional COW fork, but the Win32 subsystem do not expose the functionality. I honestly don't understand why, but maybe it is backwards compatibility that prevents it (it's backlog goes back to DOS, in which forking was impossible due to single- tasking.) But anyway ... what I am trying to say is that pyprocessing is somewhat inefficient (and limited) on Windows due to lack of a fork (cow or not). From eckhardt at satorlaser.com Thu Jun 19 08:21:46 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 19 Jun 2008 14:21:46 +0200 Subject: Simple Python class questions References: Message-ID: John Dann wrote: > Let's say I define the class in a module called comms.py. The class > isn't really going to inherit from any other class (except presumably > in the most primitive base-class sense, which is presumably automatic > and implicit in using the class keyword). Let's call the class > serial_link. So in comms.py I have: > > class serial_link: > def __init__(self): > Try > Import serial # the pyserial library Stop, this can't work. Other than VB, Python actually is case sensitive, so you must write 'try' and not 'Try' and also 'import' and not 'Import'. Further, many (all?) statements that cause an indention are usually terminated with a colon, so like with 'class ..:' and 'def ..:' you also must use 'try:' and not just 'try'. Fix all these and try again, I guess this will already help a lot. One more thing: you are abusing exceptions. Typically, in such a short program you only have one try-except pair in the main entry function and all other code only throws the exceptions. In particular the __init__ function of a class should always signal errors using exceptions. However, this is not a strict yes/no question but rather a stylistic one. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From allendowney at gmail.com Mon Jun 9 13:03:18 2008 From: allendowney at gmail.com (allendowney at gmail.com) Date: Mon, 9 Jun 2008 10:03:18 -0700 (PDT) Subject: Can I find out (dynamically) where a method is defined? References: Message-ID: Thanks Maric! That's very close to what I want, although using dir() can be misleading because if you invoke it on class B you get all of class A's methods as well. I took your idea and wrote it up like this: def find_defining_class(obj, meth_name): """find and return the class object that will provide the definition of meth_name (as a string) if it is invoked on obj. """ for ty in type(obj).mro(): if meth_name in ty.__dict__: return ty return None Cheers, Allen On Jun 9, 12:01?pm, Maric Michaud wrote: > Le Monday 09 June 2008 17:28:45 allendow... at gmail.com, vous avez ?crit?: > > > So, is there any way to inspect a method to see where (in what class) > > it > > is defined? > > In [56]: class a(object) : > ? ? def a() : return > ? ? def b() : ?return > ? ?....: > ? ?....: > > In [59]: class b(a) : > ? ? def b() : return > ? ? def c() : return > ? ?....: > ? ?....: > > In [62]: i=b() > > In [63]: for m in 'a', 'b', 'c' : > ? ?....: ? ? print [ t for t in type(i).mro() if m in dir(t) ] > ? ?....: > ? ?....: > [] > [, ] > [] > > mro stands for "method resolution order", check the reference on this > and "super", it worths the effort. > From stef.mientki at gmail.com Sun Jun 1 13:32:05 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 01 Jun 2008 19:32:05 +0200 Subject: [Business apps for Windows] Good grid + calendar, etc.? In-Reply-To: <0fc701c8c3e2$dc883b80$0203a8c0@MOUSE> References: <0fc701c8c3e2$dc883b80$0203a8c0@MOUSE> Message-ID: <4842DD15.3020604@gmail.com> Ryan Ginstrom wrote: >> On Behalf Of Gilles Ganault >> Is it hopeless, or did I overlook things? Are there other >> solutions I should look at (FLTK, etc.)? For those of you >> writing business apps in Python for Windows, how do things go >> as far as GUI widgets are concerned? >> > > To do a bit of shameless plugging, I wrote an overview of Python GUI > platforms for Windows a month or two ago: > http://ginstrom.com/scribbles/2008/02/26/python-gui-programming-platforms-fo > r-windows/ > > For your stated needs, I'd advise checking out IronPython or Python.NET > (which allow use of .NET GUI libraries). > AFAIK, Venster is (at least for windows-mobile-like platforms) replaced by the very good and stable PocketPyGUI. cheers, Stef > Regards, > Ryan Ginstrom > > -- > http://mail.python.org/mailman/listinfo/python-list > From taygunkekec at gmail.com Fri Jun 27 08:40:57 2008 From: taygunkekec at gmail.com (Taygun Kekec) Date: Fri, 27 Jun 2008 05:40:57 -0700 (PDT) Subject: Windows OS , Bizarre File Pointer Fact References: <864ab9f2-7d99-49f0-9d41-93ec41e26203@y38g2000hsy.googlegroups.com> Message-ID: Allright i figured it out . Very stupid but very forgottable fact. I should close the file before deleting it with shell command... From rentlong at gmail.com Sat Jun 14 03:18:52 2008 From: rentlong at gmail.com (rent) Date: Sat, 14 Jun 2008 00:18:52 -0700 (PDT) Subject: How to sort very large arrays? References: Message-ID: On Jun 14, 1:54 am, kj wrote: > I'm downloading some very large tables from a remote site. I want > to sort these tables in a particular way before saving them to > disk. In the past I found that the most efficient way to do this > was to piggy-back on Unix's highly optimized sort command. So, > from within a Perl script, I'd create a pipe handle through sort > and then just print the data through that handle: This is a python clone of your code from a python rookie :) from os import popen p = popen("sort -t '\t' -k1,1 -k2,2 -u > %s" % out_file) for line in data: print >> p, line there is no "die $!" here, I think it is good to let python throw the exception to your console > > open my $out, "|$sort -t '\t' -k1,1 -k2,2 -u > $out_file" or die $!; > print $out $_ for @data; > > But that's distinctly Perlish, and I'm wondering what's the "Python > Way" to do this. > > TIA! > > kynn > > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. From eckhardt at satorlaser.com Wed Jun 4 06:12:44 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 04 Jun 2008 12:12:44 +0200 Subject: Best way to modify code without breaking stuff. References: <2531546.63WkQjL8G4@news.perlig.de> Message-ID: Andr? Malo wrote: > As mentioned in another posting revision control is a good thing as well. > Not just for that task. >From my point of view revision control is not a question but a fact. Seriously, if you are not using any RCS already, it is about time you start doing so. I even use it for my private toy projects. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From jeffrey at fro.man Mon Jun 23 16:23:12 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Mon, 23 Jun 2008 13:23:12 -0700 Subject: Using Python to run SSH commands on a remote server References: <03a078c8$0$3229$c3e8da3@news.astraweb.com> <86adnQ8H4MFYdcLVnZ2dnUVZ_sHinZ2d@cablespeedwa.com> <03a08853$0$3220$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > I guess a blanket process might be a tad risky, but don't you want all CGI > files to be executable by all? Typically, I prefer CGI scripts to be executable only the owner. If the web server runs those scripts as a different user, then that user must also be permitted to execute the scripts of course. Also note that "all .py files on my web server" is not necessarily restricted to CGI scripts -- and therein lies the real gist of my cautionary note. Jeffrey From jeff at jmcneil.net Fri Jun 13 12:11:11 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Fri, 13 Jun 2008 12:11:11 -0400 Subject: urllib (54, 'Connection reset by peer') error In-Reply-To: <92ecee86-ba92-4f14-b4f8-05064ef5406c@f63g2000hsf.googlegroups.com> References: <92ecee86-ba92-4f14-b4f8-05064ef5406c@f63g2000hsf.googlegroups.com> Message-ID: <82d28c40806130911p91f959v1a5107cb5061aaaf@mail.gmail.com> It means your client received a TCP segment with the reset bit sent. The 'peer' will toss one your way if it determines that a connection is no longer valid or if it receives a bad sequence number. If I had to hazard a guess, I'd say it's probably a network device on the server side trying to stop you from running a mass download (especially if it's easily repeatable and happens at about the same byte range). -Jeff On Fri, Jun 13, 2008 at 10:21 AM, wrote: > Hi, > > I have a small Python script to fetch some pages from the internet. > There are a lot of pages and I am looping through them and then > downloading the page using urlretrieve() in the urllib module. > > The problem is that after 110 pages or so the script sort of hangs and > then I get the following traceback: > >>>>> > Traceback (most recent call last): > File "volume_archiver.py", line 21, in > urllib.urlretrieve(remotefile,localfile) > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/urllib.py", line 89, in urlretrieve > return _urlopener.retrieve(url, filename, reporthook, data) > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/urllib.py", line 222, in retrieve > fp = self.open(url, data) > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/urllib.py", line 190, in open > return getattr(self, name)(url) > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/urllib.py", line 328, in open_http > errcode, errmsg, headers = h.getreply() > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/httplib.py", line 1195, in getreply > response = self._conn.getresponse() > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/httplib.py", line 924, in getresponse > response.begin() > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/httplib.py", line 385, in begin > version, status, reason = self._read_status() > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/httplib.py", line 343, in _read_status > line = self.fp.readline() > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/socket.py", line 331, in readline > data = recv(1) > IOError: [Errno socket error] (54, 'Connection reset by peer') >>>>>>> > > My script code is as follows: > ----------------------------------------- > import os > import urllib > > volume_number = 149 # The volumes number 150 to 544 > > while volume_number < 544: > volume_number = volume_number + 1 > localfile = '/Users/Chris/Desktop/Decisions/' + str(volume_number) + > '.html' > remotefile = 'http://caselaw.lp.findlaw.com/scripts/getcase.pl? > court=us&navby=vol&vol=' + str(volume_number) > print 'Getting volume number:', volume_number > urllib.urlretrieve(remotefile,localfile) > > print 'Download complete.' > ----------------------------------------- > > Once I get the error once running the script again doesn't do much > good. It usually gets two or three pages and then hangs again. > > What is causing this? > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From aahz at pythoncraft.com Wed Jun 11 16:39:25 2008 From: aahz at pythoncraft.com (Aahz) Date: 11 Jun 2008 13:39:25 -0700 Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: In article , Frank Millman wrote: > >My approach is based on expressing a decimal number as a combination >of an integer and a scale, where scale means the number of digits to >the right of the decimal point. You should probably use one written by an expert: http://www.pythoncraft.com/FixedPoint.py -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From gh at ghaering.de Tue Jun 17 07:49:55 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 17 Jun 2008 13:49:55 +0200 Subject: Numeric type conversions In-Reply-To: References: Message-ID: John Dann wrote: > I'm new to Python and can't readily find the appropriate function for > the following situation: > > I'm reading in a byte stream from a serial port (which I've got > working OK with pyserial) and which contains numeric data in a packed > binary format. Much of the data content occurs as integers encoded as > 2 consecutive bytes, ie a 2-byte integer. [...] Use the unpack() function from the struct module. -- Gerhard From mccredie at gmail.com Fri Jun 20 14:10:44 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 20 Jun 2008 11:10:44 -0700 (PDT) Subject: Tkinter canvas drag/drop obstacle References: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> Message-ID: <09ec833f-7751-4991-8d09-45c200fb4c18@z72g2000hsb.googlegroups.com> On Jun 20, 9:11?am, Peter Pearson wrote: > Tkinter makes it very easy to drag jpeg images around on a > canvas, but I would like to have a "target" change color when > the cursor dragging an image passes over it. ?I seem to be > blocked by the fact that the callbacks that might tell the > target that the mouse has entered it (, , > even ) aren't called if the mouse's button is down. > What am I missing? ?Have I failed to find the right Tkinter > document? ?Is Tkinter the wrong tool for this job? ?Thanks. > > -- > To email me, substitute nowhere->spamcop, invalid->net. I have used a combination of and . You might also throw in a event to keep track of whether or not the mouse button was down when it entered the widget or not. Depending on what you really want to do though, you might take advantage of the 'active' state: import Tkinter as tk can = tk.Canvas() can.pack(fill=tk.BOTH, expand=True) can.create_rectangle( 10,10,100,100, fill="black", activewidth=5, activeoutline="blue" ) can.mainloop() The 'active*' options take effect when the mouse is on top of that item. If all you are _really_ interested in is a visual indicator, this should work for you. Note that there is also a disabled state. I only discovered this by looking at the options available and guessing. >>> from pprint import pprint >>> import Tkinter as tk >>> can = tk.Canvas() >>> can.pack(fill=tk.BOTH, expand=True) >>> r = can.create_rectangle(10,10,100,100) >>> pprint(can.itemconfig(r)) {'activedash': ('activedash', '', '', '', ''), 'activefill': ('activefill', '', '', '', ''), 'activeoutline': ('activeoutline', '', '', '', ''), 'activeoutlinestipple': ('activeoutlinestipple', '', '', '', ''), 'activestipple': ('activestipple', '', '', '', ''), 'activewidth': ('activewidth', '', '', '0.0', '0.0'), 'dash': ('dash', '', '', '', ''), 'dashoffset': ('dashoffset', '', '', '0', '0'), 'disableddash': ('disableddash', '', '', '', ''), 'disabledfill': ('disabledfill', '', '', '', ''), 'disabledoutline': ('disabledoutline', '', '', '', ''), 'disabledoutlinestipple': ('disabledoutlinestipple', '', '', '', ''), 'disabledstipple': ('disabledstipple', '', '', '', ''), 'disabledwidth': ('disabledwidth', '', '', '0.0', '0'), 'fill': ('fill', '', '', '', ''), 'offset': ('offset', '', '', '0,0', '0,0'), 'outline': ('outline', '', '', 'black', 'black'), 'outlineoffset': ('outlineoffset', '', '', '0,0', '0,0'), 'outlinestipple': ('outlinestipple', '', '', '', ''), 'state': ('state', '', '', '', ''), 'stipple': ('stipple', '', '', '', ''), 'tags': ('tags', '', '', '', ''), 'width': ('width', '', '', '1.0', '1.0')} The 'state' option can be set to 'normal', 'hidden' or 'disabled'. So if you want to make your canvas items look different when they are disabled, set the disabled* options and set 'state' to 'disabled'. Matt From n.emami at gmail.com Mon Jun 9 09:27:44 2008 From: n.emami at gmail.com (Nader) Date: Mon, 9 Jun 2008 06:27:44 -0700 (PDT) Subject: lists to save in a tuple Message-ID: <130e261e-1e1a-4657-b8db-8a7704fb083d@z66g2000hsc.googlegroups.com> Hello, I have two lists and would save them in a tuple. a = [1,2,3] b = ['a','b','c'] with the next statement I can do that: t = [(x,y), for x in a for y in b] This gives the next list: [(1,'a'),(1,'b'),(1,'c'), (2,'a'),(2,'b'),(2,'c'), (3,'a'),(3,'b'), (3,'c')] But I want the next list: [(1,'a'),(2,'b'),(3,'c')] Would somebody tell me how I can solve this problem? Regards, Nader From jason.scheirer at gmail.com Fri Jun 27 15:51:05 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Fri, 27 Jun 2008 12:51:05 -0700 (PDT) Subject: Django or TurboGears for a new project References: <8763ru6cra.fsf@internal.daycos.com> Message-ID: On Jun 27, 9:52?am, Kirk Strauser wrote: > We're looking to migrate a Zope site to Django, but before getting beyond > the dreaming stage, I thought I'd see what others are doing these days. > > If you were going to start a fairly complex site today with lots of DB > integration, would you begin with Django or TurboGears, or something else > entirely? > > I'm more interested in social, rather than technical reasons (unless there's > something you absolutely love or despise about one or the other). > Popularity is actually a pretty big consideration because I'd like to work > with an eager community who's doing cool new things. > > I know asking for comparisons like this is potentially flamebait-ish, but I > really don't mean it that way. ?It's just that I don't have a lot of friends > in the industry in this particular development niche who I can ask for > recommendations, and this seems like as good a place as any to find subject > matter experts. > > Thanks, > -- > Kirk Strauser > The Day Companies I've noticed I write a lot less code with TurboGears (as in my apps are done faster and smaller), but you're going to find more Django programmers and therefore a larger developer force and more recipes online. From disappearedng at gmail.com Tue Jun 10 12:09:24 2008 From: disappearedng at gmail.com (disappearedng at gmail.com) Date: Tue, 10 Jun 2008 09:09:24 -0700 (PDT) Subject: Web Crawler - Python or Perl? References: <484D7329.6060107@behnel.de> <1a91e16d-ccfc-487a-80fc-4d9992455eb9@p25g2000hsf.googlegroups.com> <484d9bdc$0$6606$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <91cbb629-b085-45bd-aeec-5b3dba8f34c7@r66g2000hsg.googlegroups.com> As to why as opposed to what, I am attempting to build a search engine right now that plans to crawl not just html but other things too. I am open to learning, and I don't want to learn anything that doesn't really contribute to building my search engine for the moment. Hence I want to see whether learning PERL will be helpful to the later parts of my search engine. Victor From google at mrabarnett.plus.com Tue Jun 17 11:58:11 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 17 Jun 2008 08:58:11 -0700 (PDT) Subject: Numeric type conversions References: Message-ID: On Jun 17, 12:28 pm, John Dann wrote: > I'm new to Python and can't readily find the appropriate function for > the following situation: > > I'm reading in a byte stream from a serial port (which I've got > working OK with pyserial) and which contains numeric data in a packed > binary format. Much of the data content occurs as integers encoded as > 2 consecutive bytes, ie a 2-byte integer. > > I'm guess that there should be a function available whereby I can say > something like: > > My2ByteInt = ConvertToInt(ByteStream[12:13]) > > to take a random example of the 2 bytes occurring at positions 12 and > 13 in the byte stream. > [snip] Please note that in slicing the start position is included and the end position is excluded, so that should be ByteStream[12:14]. From maric at aristote.info Mon Jun 23 08:40:57 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 23 Jun 2008 14:40:57 +0200 Subject: listcomprehension, add elements? In-Reply-To: References: <13452c64-ef91-49a2-bb73-7f33c088660e@d45g2000hsc.googlegroups.com> Message-ID: <200806231440.57737.maric@aristote.info> Le Monday 23 June 2008 13:51:34 John Machin, vous avez ?crit?: > On Jun 23, 9:16 pm, Maric Michaud wrote: > > Le Monday 23 June 2008 11:39:44 Boris Borcic, vous avez ?crit : > > > John Machin wrote: > > > > Instead of sum(a + b for a, b in zip(foo, bar)) > > > > why not use sum(foo) + sum(bar) > > > > ? > > > > > > or even sum(foo+bar) as may apply. > > > > Because some are better than others : > > > > sum(foo+bar) is the worst, it create a superfluous list of len(foo) + > > len(bar) elements. > > > > sum(a + b for a, b in zip(foo, bar)), creates a list of max(len(foo), > > len(bar)) elements, in most cases it is the same as the former. > > > > This could have been corrected using itertools.izip. > > > > So the winner is sum(foo) + sum(bar), which does not create anything not > > needed. > > > > But if the question is "how to build the list and sum up all elements in > > a efficient way for sequences of arbitrary length ", it's important to > > make it in the same iteration, so the most effective/clear, and so > > "pythonic", way to do this is (untested) : > > > > res, sum = [], 0 > > Please use tot or total, not sum! > > > for s in (a + b for a, b > > in zip(itertools.izip(xrange(1, 51), > > Perhaps you should not have left zip() in there ... > > > xrange(50, 0, > > -1)))): sum += s > > res.append(sum) > > Do you mean res.append(s) ? > Yes, my mistakes, all remarks are indeed true. Sorry for this out of thoughts sketch. > I would have thought that it would have been better to create the list > and then sum it: > res = [a + b for a, b in itertools.izip(foo_iter, bar_iter)] > total = sum(res) > This is good enough if you accept the overhead of iterating twice over the whole list. But this may be a bit more complicated, for efficiency, there is a better way of allocating memory than successively appending new item. I guess this should be a far better solution, but you'll need to know the required number of iteration (the size of your iterators, the xrange in this sample) : res, total = [None] * n, 0 for i, s in enumerate(a + b for a, b in izip(xrange(1, n+1), xrange(n, 0, -1)): total += s res[i] =s -- _____________ Maric Michaud From tgrav at mac.com Wed Jun 4 18:58:34 2008 From: tgrav at mac.com (Tommy Grav) Date: Wed, 4 Jun 2008 18:58:34 -0400 Subject: gcc error in Mac OS X In-Reply-To: <12956470806041550k7e2815b4ga6823ee7967a8718@mail.gmail.com> References: <12956470806041550k7e2815b4ga6823ee7967a8718@mail.gmail.com> Message-ID: What happens when you run which gcc Cheers Tommy On Jun 4, 2008, at 6:50 PM, Zhaojie Boulder wrote: > Hello, > > I am new to Mac and used python in linux before. What I am trying to > do is to install "Ipython" and "PyCogent" in Mac OS X. > > For PyCogent, after entering the package path, I typed "python > setup.py install". The results are as follows: > > Didn't find Pyrex - will compile from .c files > running install > running build > running build_py > running build_ext > building 'cogent.align._compare' extension > gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused- > madd -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes - > DMACOSX -I/usr/include/ffi -DENABLE_DTRACE -arch i386 -arch ppc - > pipe -I/Users/zhaojie/Downloads/PyCogent-1.0.1/include -I/System/ > Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 - > c cogent/align/_compare.c -o build/temp.macosx-10.5-i386-2.5/cogent/ > align/_compare.o -w > unable to execute gcc: No such file or directory > error: command 'gcc' failed with exit status 1 > > After google, I installed Xcode,but it did not help. Also, the Xcode > folder is not within "applications" folder, but a separate one > parallel with "applications". Dragging Xcode folder into the > applications folder did not make a difference, either. > > Hope someone familiar with Mac can help me out. > > Thank you, > > Jie > -- > http://mail.python.org/mailman/listinfo/python-list From gh at ghaering.de Tue Jun 3 11:07:02 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 03 Jun 2008 17:07:02 +0200 Subject: Please solve me the problem In-Reply-To: <905b76210806022159l1bcb0165r1096c491f665e914@mail.gmail.com> References: <905b76210806022159l1bcb0165r1096c491f665e914@mail.gmail.com> Message-ID: sagar panda wrote: > Hi > > I am sagar. I want to write a python script that will run the python > scripts automatically from a directory. Please help me out to sovle this > problem? You can use the execfile() builtin function to execute Python scripts. And you can use glob.glob("/some/path/*.py") to find the Python scripts. You'll need to import the glob module first, of course. That should help you implement the solution. -- Gerhard From joemacbusiness at yahoo.com Thu Jun 26 18:31:57 2008 From: joemacbusiness at yahoo.com (joemacbusiness at yahoo.com) Date: Thu, 26 Jun 2008 15:31:57 -0700 (PDT) Subject: Need help capturing output of re.search Message-ID: <771ef68a-d976-4f61-a3cc-7ed56fddc756@k37g2000hsf.googlegroups.com> Hi - I need help capturing the output of a RegEx search. I dont understand why this conditional fails. Here is the code: #================================= start snip ====================================== #!/usr/local/bin/python import os import re dirName = '/home/user/bin/logs' os.chdir(dirName) files = os.listdir(dirName) for myFile in files: # print 'checking ...', myFile reCheck = '' reCheck = re.search(r'\bCC_', myFile) # print 'reCheck = ', '=', reCheck, '=' if reCheck == "None": print myFile, ' ..... does not qualify' else: print ' ', myFile, 'qualifies...', reCheck #================================= end snip ====================================== The problem is that reCheck never == None. So all of the files "qualify". My understanding of the re.search (re.search(r'\bCC_', myFile)) is ... 1) give me only files that start with a word boundary (\b) 2) followed by a (CC_) 3) in myFile Why doesn't the output of the re.search load reCheck with valid data? (like "None") Thanks From python at rcn.com Wed Jun 4 07:36:51 2008 From: python at rcn.com (Raymond Hettinger) Date: Wed, 4 Jun 2008 04:36:51 -0700 (PDT) Subject: defaultdict.fromkeys returns a surprising defaultdict References: Message-ID: <81be85b4-978e-423d-8a1a-11f54e11cf18@x1g2000prh.googlegroups.com> On Jun 3, 1:11?pm, Matthew Wilson wrote: > I used defaultdict.fromkeys to make a new defaultdict instance, but I > was surprised by behavior: > ? ? >>> b = defaultdict.fromkeys(['x', 'y'], list) > ? ? >>> b > ? ? defaultdict(None, {'y': , 'x': }) One other thought: Even after correcting the code as shown in other posts, I don't think you're on the right track. If you know the full population of keys at the outset and just want them to all have an initial value, the defaultdict isn't the right tool. Instead, just populate a regular dict in usual way: >>> dict((k, []) for k in 'xyz') {'y': [], 'x': [], 'z': []} The time to use defaultdict is when you *don't* want to pre-populate a dict. The factory gets run during the lookup phase and creates your default just-in-time for use: >>> d = defaultdict(list) >>> for k in 'zyzygy': d[k].append(1) # empty list created on lookup if needed >>> d defaultdict(, {'y': [1, 1, 1], 'z': [1, 1], 'g': [1]}) Raymond From xdicry at gmail.com Mon Jun 23 04:50:30 2008 From: xdicry at gmail.com (Evan) Date: Mon, 23 Jun 2008 01:50:30 -0700 (PDT) Subject: how to send a "Multiline" mail with smtplib? References: <72daf82c-1921-4aba-b41a-3bf13d3f0e51@s21g2000prm.googlegroups.com> Message-ID: <243cbf35-d9a3-4d98-a4fa-2b991b38e71b@s21g2000prm.googlegroups.com> On Jun 19, 6:12 pm, Lie wrote: > On Jun 19, 4:02 pm, Justin Ezequiel > wrote: > > > perhaps change html > > > body=MIMEText('hello,\r\n > > ok',_subtype='html',_charset='windows-1255') > > > to plain > > > body=MIMEText('hello,\r\n > > ok',_subtype='plain',_charset='windows-1255') > > If that was the case, and you needed a line break in html-mode, use >
    or

    tags. Thanks all, and yes, if I use "plain" or use HTML tag "
    ", it worked: (1) HTML: I use tag "
    " and " ", and when I reply that mail, I will see "
    " tag in mail content, it is not a good option. thanks, Evan From brad.navarro at wni.com Wed Jun 11 14:33:10 2008 From: brad.navarro at wni.com (Brad Navarro) Date: Wed, 11 Jun 2008 13:33:10 -0500 Subject: Programming question Message-ID: <31C3FE622274D44A8FE8E8D649AE178805E738D4@exch1.wni.com> Greetings, Being extremely new to Python, I haven't got the experience to figure this one out on my own and frankly I am not sure I would know where to look. Basically, what I am trying to do is get a list of each file's attributes within a directory. Basically, the information that the 'ls -l' command would give you in a linux shell, except the results for each file in the directory are stored as a list. I am presently using version 1.5 on a linux machine. I have kindly requested my system administrator to upgrade to 2.5.2, but until then I am afraid I am stuck with 1.5. Thanks, Brad -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Jun 13 12:52:41 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Jun 2008 18:52:41 +0200 Subject: Finding a sense of word in a text References: <2b696ed5-bb4c-4c02-8d35-ac6235d8584b@y21g2000hsf.googlegroups.com> <2a6c26f6-5aea-4bf1-9cf8-866bf1d1f86d@w1g2000prd.googlegroups.com> Message-ID: Sengly wrote: > Thank you. I have tried but no luck :( NLTK, maybe? Searching for "synonym" within nltk.org gives http://nltk.org/doc/en/words.html Peter From mnordhoff at mattnordhoff.com Wed Jun 18 05:18:46 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 18 Jun 2008 09:18:46 +0000 Subject: reading from an a gzip file In-Reply-To: <4e9ff9ad-6fe5-413c-b81f-c76e33c043d0@f36g2000hsa.googlegroups.com> References: <4e9ff9ad-6fe5-413c-b81f-c76e33c043d0@f36g2000hsa.googlegroups.com> Message-ID: <4858D2F6.4060004@mattnordhoff.com> Nader wrote: > Hello, > > I have a gzip file and I try to read from this file withe the next > statements: > > gunziped_file = gzip.GzipFile('gzip-file') > input_file = open(gunziped_file,'r') > > But I get the nezt error message: > > Traceback (most recent call last): > File "read_sfloc_files.py", line 131, in ? > input_file = open(gunziped_file,'r') > TypeError: coercing to Unicode: need string or buffer, instance found > > I think that I do some mistake. Would some body tell me what is my > mistake? > > Nader gzip.GzipFile() creates a file-like object. You don't call open() on it; you use it directly. $ echo foo >test $ gzip test $ python >>> import gzip >>> gfh = gzip.GzipFile('test.gz', 'rb') >>> gfh.read() 'foo\n' >>> gfh.close() -- From sajmikins at gmail.com Wed Jun 11 17:05:59 2008 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 11 Jun 2008 14:05:59 -0700 (PDT) Subject: Simple and safe evaluator References: Message-ID: <8ffd23bc-d7e9-49a0-a166-79baa174b265@u12g2000prd.googlegroups.com> On Jun 11, 1:25 pm, bvdp wrote: > Is there a simple/safe expression evaluator I can use in a python > program. I just want to pass along a string in the form "1 + 44 / 3" or > perhaps "1 + (-4.3*5)" and get a numeric result. > > I can do this with eval() but I really don't want to subject my users to > the problems with that method. > > In this use I don't need python to worry about complex numbers, > variables or anything else. Just do the math on a set of values. Would > eval() with some restricted list of permitted operators do the trick? > > I'm feeling too lazy to write/debug my own parser for this :) > > Thanks, Bob. Funny, I need exactly the same kind of parser myself right now. Fredrik Lundh has posted some code-and-explanation on an excellent simple parser that's easy to extend. http://effbot.org/zone/simple-iterator-parser.htm Just make it recognize the operator tokens you're interested in and if a string parsers w/o errors then you know it's safe to eval(). I probably won't get to writing this myself for a few days or a week, but if you do will you post it here (or send me a copy)? I'll do the same if I get to it sooner. Regards, ~Simon From ncoghlan at gmail.com Wed Jun 4 07:29:38 2008 From: ncoghlan at gmail.com (NickC) Date: Wed, 4 Jun 2008 04:29:38 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> Message-ID: <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> On Jun 4, 4:09 am, "Russ P." wrote: > What is it about leading underscores that bothers me? To me, they are > like a small pebble in your shoe while you are on a hike. Yes, you can > live with it, and it does no harm, but you still want to get rid of it. With leading underscores, you can see *at the point of dereference* that the code is accessing private data. With a "this is private" keyword you have no idea whether you're accessing private or public data, because the two namespaces get conflated together. I'll keep my pebble, thanks. Cheers, Nick. From guillermo.listas at googlemail.com Tue Jun 3 19:33:53 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Tue, 3 Jun 2008 16:33:53 -0700 (PDT) Subject: Keep a script running in the background References: <210b7fc6-ed52-461d-8b53-455e247d7a29@e39g2000hsf.googlegroups.com> Message-ID: These are the basic requirements: Script A must keep a dictionary in memory constantly and script B must be able to access and update this dictionary at any time. Script B will start and end several times, but script A would ideally keep running until it's explicitly shut down. I have the feeling the way to do this is Python is by pickling the dict, but I need the method that gives the best performance. That's why I'd rather want to keep it in memory, since I understand pickling involves reading from and writing to disk. I'm using SQLite as a database. But this dict is an especial index that must be accessed at the highest speed possible. From mail at timgolden.me.uk Fri Jun 27 09:59:38 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 27 Jun 2008 14:59:38 +0100 Subject: shorten path to files In-Reply-To: References: Message-ID: <4864F24A.6030602@timgolden.me.uk> > On 2008-06-27, cesco wrote: >> Hi, >> >> I need to retrieve the content of some files which are placed on a >> network drive so in order to open them I need the full path to the >> file. >> Unfortunately some times the path is longer than 256 characters and in >> Windows such a path is too long with the result that the file is not >> found (though it is there). >> >> Is there any way around this? It's not clear from your description whether this applies, but there is an API to obtain the short version of a Windows path: http://timgolden.me.uk/pywin32-docs/win32api__GetShortPathName_meth.html (NB this is obviously the pywin32 project; I'm simply hosting a copy of the docs). Also, on more recent versions of the NT family, you can map drive letters to deep paths, you can do something like this: NET USE * \\server\share\path1\path2\path3\path4 and then do things with x:\path5\path6\ etc. And you may find that passing a version of the filename as in the example below will bypass the limit anyway. Note that this uses the \\?\ prefix. contents = open (ur"\\?\c:\some\really\long\path").read () TJG From __peter__ at web.de Sun Jun 15 07:41:23 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Jun 2008 13:41:23 +0200 Subject: marshal.dumps quadratic growth and marshal.dump not allowing file-like objects References: Message-ID: John Machin wrote: >> Here's how marshal resizes the string: >> >> newsize = size + size + 1024; >> if (newsize > 32*1024*1024) { >> newsize = size + 1024*1024; >> } >> >> Maybe you can split your large objects and marshal multiple objects to >> keep the size below the 32MB limit. >> > > But that change went into the svn trunk on 11-May-2008; perhaps the OP > is using a production release which would have the previous version, > which is merely "newsize = size + 1024;". That is indeed much worse. Depending on what the OP means by "large objects" the problem may be fixed in subversion then. > Do people really generate 32MB pyc files, or is stopping doubling at > 32MB just a safety valve in case someone/something runs amok? A 32MB pyc would correspond to a module of roughly the same size. So someone/something runs amok in either case. Peter From lists at cheimes.de Tue Jun 10 18:43:57 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 11 Jun 2008 00:43:57 +0200 Subject: Question by someone coming from C... In-Reply-To: <1213049846.3030.28.camel@jmk> References: <70c02bf1-b26f-4fba-9a33-38e79e3e34eb@p25g2000pri.googlegroups.com> <1213049846.3030.28.camel@jmk> Message-ID: John Krukoff wrote: > Since you probably want access to these from many different places in > your code, I find the simplest way is to create a logging module of your > own (not called logging, obviously) and instantiate all of your loggers > in that namespace, then import that one module as needed. No, don't do that. Simple do import logging log = logging.getLogger("some_name") The logging module takes care of the rest. The logging.getLogger() function creates a new logger *only* when the name hasn't been used yet. Christian From metalkeys404 at gmail.com Sun Jun 29 02:09:04 2008 From: metalkeys404 at gmail.com (Ampedesign) Date: Sat, 28 Jun 2008 23:09:04 -0700 (PDT) Subject: lxml and links References: <4865C579.9010401@behnel.de> Message-ID: On Jun 27, 10:00?pm, Stefan Behnel wrote: > Ampedesign wrote: > > I'm trying to extract all the links on a page with lxml. Ideally, I > > would like it to return me a list of hrefs of each link on the page, > > in a list. > > > How would I go about doing this? > > Read the manual? > > http://codespeak.net/lxml/dev/lxmlhtml.html#working-with-linkshttp://codespeak.net/lxml/dev/tutorial.html#tree-iterationhttp://codespeak.net/lxml/dev/xpathxslt.html#xpath > > Stefan Yeah, I was just having some trouble understanding it. But nevermind, I think I figured it out. From larry.bates at websafe.com` Sat Jun 14 13:43:52 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 14 Jun 2008 12:43:52 -0500 Subject: Python + RDBM framework? In-Reply-To: References: Message-ID: <9PGdnQYEHsf_nsnVnZ2dnUVZ_t3inZ2d@comcast.com> bukzor wrote: > It seems that whenever I have an application that uses a database > (MySQL) I end up writing a database framework from scratch. Is there > some accepted pre-existing project that has done this? > > I see Django, but that seems to have a lot of web-framework that I > don't (necessarily) need. I just want to have my objects go in and out > of the database in a consistent manner without writing a ton of code. > Can you just use the database part without making a full-blow web app? > > I see Zope, but that doesn't use MySQL (as far as I can tell), which > I've invested a lot of time learning to use and optimize. Also, my > manager wants to be able to log into a MySQL prompt and be able to > look at the data. > > --Buck Zope definitely has MySQL interface, but if you think Django is a lot then Zope is even more. If I'm understanding your correctly what you want is ORM/ These links should help: http://pythonnotes.blogspot.com/2004/09/python-orm-tools.html http://www.sqlalchemy.org/ http://www.sqlobject.org/ -Larry From francis.girard07 at gmail.com Wed Jun 18 07:55:46 2008 From: francis.girard07 at gmail.com (Francis Girard) Date: Wed, 18 Jun 2008 07:55:46 -0400 Subject: Interpreting string containing \u000a Message-ID: Hi, I have an ISO-8859-1 file containing things like "Hello\u000d\u000aWorld", i.e. the character '\', followed by the character 'u' and then '0', etc. What is the easiest way to automatically translate these codes into unicode characters ? Thank you Francis Girard From carsten.haese at gmail.com Tue Jun 10 15:09:33 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Tue, 10 Jun 2008 15:09:33 -0400 Subject: problems with opening files due to file's path In-Reply-To: References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> Message-ID: Alexnb wrote: > No this time it perhaps gave me the worst of all heres what I entered, and > the output > >>>> startfile(r"%s"%full) ***full is the path*** > > startfile(r"%s"%full) > > WindowsError: [Error 2] The system cannot find the file specified: > '"C:\\Documents and Settings\\Alex\\My Documents\\My > Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I\'m Yours (Single)\x01 - I\'m > Yours.wma"' Contrary to what other posters have asserted, doing the above can't make a difference. Putting 'r' in front of a string literal tells Python not to give backslashes in the string literal any special treatment. Since there are no backslashes in "%s", the 'r' does nothing. Therefore, (r"%s"%full) is the same as ("%s"%full), which is the same as (full), assuming that `full` is the name of a string. The real answer lies in fixing the code where you're assigning the pathname to 'full', which you haven't posted. Please post the code where you're assigning the pathname, or better yet, post the complete code you're running. -- Carsten Haese http://informixdb.sourceforge.net From samslists at gmail.com Fri Jun 20 18:44:56 2008 From: samslists at gmail.com (samslists at gmail.com) Date: Fri, 20 Jun 2008 15:44:56 -0700 (PDT) Subject: Time-out for regular expressions... Message-ID: I'm doing a lot of regular expressions these days. Sometimes when I'm crafting them I mess up, and make them too complicated. So that when my program runs, they take forever. (Maybe not literally forever---I abort the program after a few seconds.) What I'd like to have happen is every time I search using a regular expression is after a few seconds (the exact number being user definable), it will stop searching, perhaps by raising an exception. How can I implement this? Thanks From tracyde at gmail.com Fri Jun 6 09:24:23 2008 From: tracyde at gmail.com (Derek Tracy) Date: Fri, 6 Jun 2008 09:24:23 -0400 Subject: Python CGI Upload from Server Status In-Reply-To: <608040960806060616ja7fbc89ya9c5f92c881b14d@mail.gmail.com> References: <9999810b0806060550w5a7297dbm8ba5cc902cad6f8b@mail.gmail.com> <608040960806060616ja7fbc89ya9c5f92c881b14d@mail.gmail.com> Message-ID: <9999810b0806060624j23639fc5r3c90e010489801eb@mail.gmail.com> On Fri, Jun 6, 2008 at 9:16 AM, John Dohn wrote: > On Sat, Jun 7, 2008 at 12:50 AM, Derek Tracy wrote: > >> I am trying to create a simple python cgi app that allows the user to kick >> off an ftp from the server the cgi is on to another server; I have that >> piece working using ftplib but since the files in question are usually very >> large (500mb to 2gb) in size I want to be able to display some sort of >> status to the user, preferrably a progress bar of some sort. > > > You'll need some AJAX progress bar (hint: google for this term ;-) that > will be getting updates from the server or request an update every second or > so. > > The question is if your upload code can provide progress tracking? If it's > just a call to some xyz.upload("/here/is/my-500M-file.bin") that only > returns after several minutes of uploading without giving you any updates on > how fast things go you're probably out of luck. > OTOH if it can do e.g.callbacks for progress reporting or if it can run in > a separate thread that you could query somehow you can hook that to that > AJAX thing of your choice. > > JDJ > > -- > http://mail.python.org/mailman/listinfo/python-list > I will look for the AJAX Progress Bar, but I will admit I have never touched AJAX and haven't written javascript in years. I patched Pythons ftplib.py storbinary() to send callbacks to the specified method, so I have the callbacks locked down. The thing to note is that this app isn't allowing the user to upload to the server the cgi is on but rather allowing the user to kick off an ftp process on the server to another server. Would there be a way to do this with python cgi and automatically append or update information on the page it is displaying? -- --------------------------------- Derek Tracy tracyde at gmail.com --------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From circularfunc at yahoo.se Sun Jun 22 18:27:56 2008 From: circularfunc at yahoo.se (cirfu) Date: Sun, 22 Jun 2008 15:27:56 -0700 (PDT) Subject: rightclick-copy in IDLE? Message-ID: <6b40b216-65b8-40da-9072-7b3249086c7c@m44g2000hsc.googlegroups.com> when i rightclick in python idle i get set breakpoint or something. n options i dont find a way to change to the normal copy/paste options. From goldnery at gmail.com Sun Jun 1 08:32:45 2008 From: goldnery at gmail.com (Gandalf) Date: Sun, 1 Jun 2008 05:32:45 -0700 (PDT) Subject: Need Tutorial For the following lib References: <9950cf3f-e58a-413a-bdff-a40cc1c6cf6d@8g2000hse.googlegroups.com> <0bdd04b8-23b6-4a68-bda2-6984428ce7bd@b1g2000hsg.googlegroups.com> <4KCdnQj2nvh7F9_VnZ2dnUVZ_uidnZ2d@comcast.com> Message-ID: On Jun 1, 1:41 pm, Larry Bates wrote: > Gandalf wrote: > > Hi scott, you couldn't be more wrong about my laziness. I straggle > > with my poor English for hours to fined what I'm looking for. > > I found a very simple and not comprehensive tutorial for the pyWinAuto > > lib in this addresshttp://pywinauto.openqa.org/ > > but it only show how to do the basic, and my knowledge at this point > > is not enough to figure the rest I need to know by myself > > I found another simple lib for the watsup that based on winGuiAuto > > lib in this address > >http://www.tizmoi.net/watsup/intro.html > > But for some risen I couldn't manage to ran it in my computer > > > I'm trying to generate auto mouse double click or auto selecting text > > (the selecting text part is the one I interest in. mouse double click > > just do the same effect if the mouse cursor is on text) > > > I'm sorry you feel I'm lazy. The truth is that event writing this > > message takes me an enormous power. > > weather you choose to help me or not I still going to keep trying , > > But you have the opportunity to save me lots of trouble, So maybe one > > day I could help others. > > > so if you familiar with any good tutorial for this library please let > > me know and if not then thank you anyway for wonting to help > > > Y.G > > What you want is an easy solution to what isn't an easy problem, but (as with > your other post) you refuse to provide enough information to allow us to help > you. If I were you, I would download wxPython and go through the demos that it > includes. comp.python.wxpython list is excellent (at least as good as this one) > for any follow-up questions. Windows events and mouse clicks are going to take > a concerted effort (on your part) to learn (especially if you haven't > accomplished such a task in another language). > > -Larry Hi, Larry. thank you for your interaction. I did manage to do half of the things I was asking you about them. I manage to create an application which react to a mouse and keyboard events that occur anywhere in the O.P (that done easily by the phHook library here http://mindtrove.info/articles/monitoring-global-input-with-pyhook/#toc-references ) And I manage to find lib which auto generate event they event show you with video how simple it's to get done http://pywinauto.openqa.org/ and this is the video. it's interesting http://showmedo.com/videos/video?name=UsingpyWinAutoToControlAWindowsApplication&fromSeriesID=7 The only problem is that they show only how to automatically open notepad. they have this DoubleClick method as I saw in the documentation (i think this is what I'm looking for) but they don't show how to use it. I'm telling you that because I believe it's not as complex as you think it is. I think I'm close. if i could just fine a manual which show more examples or a bit more information i can do this. Thank you From exarkun at divmod.com Mon Jun 16 14:46:54 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 16 Jun 2008 14:46:54 -0400 Subject: String Concatenation O(n^2) (was: Re: Explaining Implementing a Binary Search Tree.) In-Reply-To: <3fc761710806161030r35e9b21gfe0f76326adb66b9@mail.gmail.com> Message-ID: <20080616184654.4714.1818914611.divmod.quotient.9798@ohm> On Mon, 16 Jun 2008 11:30:19 -0600, Ian Kelly wrote: >On Mon, Jun 16, 2008 at 11:09 AM, Jean-Paul Calderone > wrote: >> It will depend what version of Python you're using and the *exact* details >> of the code in question. An optimization was introduced where, if the >> string being concatenated to is not referred to anywhere else, it will be >> re-sized in place. This means you'll probably see sub-quadratic behavior, >> but only with a version of Python where this optimization exists and only >> if the code can manage to trigger it. > >AFAICT, PyString_Concat never calls _PyString_Resize. Am I looking in >the wrong place? Yep. The optimization is done directly from the eval loop. Take a look at ceval.c, if you search for _PyString_Resize you should see it. Jean-Paul From kyosohma at gmail.com Tue Jun 10 13:11:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 10 Jun 2008 10:11:13 -0700 (PDT) Subject: Instructions on how to build py2exe 0.6.8 (or an installer would be nice, too!) References: <5426baaf-2ba6-41b0-a0ec-1070429b5195@x35g2000hsb.googlegroups.com> <7f3360e4-8a12-45cf-99fa-6172cb5a1aaa@a1g2000hsb.googlegroups.com> Message-ID: <5cde3ec8-2e8d-4c1e-bee9-1ee51f649cd8@d45g2000hsc.googlegroups.com> On Jun 10, 10:47?am, chard... at gmail.com wrote: > On Jun 10, 11:34?am, Mike Driscoll wrote: > > > > > Maybe I'm missing something, but I can rename the executables I create > > using py2exe 0.6.6 to anything I want after they're created. > > > Or are you talking about a Windows installer for the py2exe module > > itself? Where are you finding this 0.6.8 version anyway? I can't find > > it onwww.py2exe.org > > > Anyway, what Thomas is talking about is that the only way to create a > > usable installer of py2exe on Windows is to use the same compiler that > > the Python you are using. As I understand it, Python 2.4 and 2.5 used > > Visual Studio 2003. I think 2.3 used VS6. I have both, so I can try to > > compile an installer for any of those versions if you can link me to > > the source. > > > Mike > > > Python Extension Building Network: ? ? http:\\www.pythonlibrary.org > > The issue with renaming executables only applies to single-file > executables, i.e. ones created with zipfile = None as an argument to > setup() and --bundle 1 as a command line argument. This is a known > issue as of 0.6.6:http://py2exe.org/index.cgi/ProblemsToBeFixed I'm using GUI2Exe to wrap my 0.6.6 version of py2exe. I use the bundle into a single file option in it and have zipfile=None too. But maybe one of my other switches is different. > > I found sources for 0.6.8 on CVS at:http://sourceforge.net/cvs/?group_id=15583 > > A Windows installer for the 0.6.8 py2exe module would be ideal, but > somehow I doubt that's going to happen anytime soon since there hasn't > been a new installer since 2006. If you are willing to build that for > me (since I don't have VS) I'd really appreciate it : ) I'm using 32- > bit WinXP on this computer. I finally figured out how to check out the code. I'm at work now, where I only have VS2008 installed so I'll have to wait until I get home this evening to try compiling it. I'll let you know if I have any luck. --------------------- Mike Python Extension Building Network: http:\\www.pythonlibrary.org From jgodoy at gmail.com Wed Jun 25 06:38:38 2008 From: jgodoy at gmail.com (Jorge Godoy) Date: Wed, 25 Jun 2008 07:38:38 -0300 Subject: IDE on the level of Eclipse or DEVc++? References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> <486214ae$0$9742$426a34cc@news.free.fr> <87ej6lq02c.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Bruno Desthuilliers writes: > >> If you're into clickodroms, you may want to have a look at Eric too. >> As far as i'm concerned, I still wait for something that would be >> worth dropping emacs + python-mode + ecb. > > I'm having the most success with this combination, yes. Though ecb is > rather non-Emacs-like in its configuration, and seems to strongly > expect to be run in graphical mode, it is still very powerful. Heh... I'm another one that keeps trying new things but comes back to Emacs all the time. Eclipse is too heavy, NetBeans has a poor support, Eric is too "mousy"... -- Jorge Godoy From xkenneth at gmail.com Thu Jun 26 21:59:01 2008 From: xkenneth at gmail.com (xkenneth) Date: Thu, 26 Jun 2008 18:59:01 -0700 (PDT) Subject: Design principles and architecture of an information transfer standard based on XML and SOAP Message-ID: <070a2cec-5c4b-44ab-93ff-a0811f7c226b@u6g2000prc.googlegroups.com> All, So i'm just about to undertake my first real open source project, and I'm looking for a bit of advice. There's an oilfield standard called WITSML (Wellsite Information Transfer Standard Markup Language - witsml.org), it's basically a collection of XML schemas and a spec for an client-server based communication standard based on SOAP and WSDL. I'm looking for advice and past experience on how to architect this project and implement it properly. I'm fairly new with concepts such as threading, ORM, etc in a server/client context. If anyone has any past experience they'd like to contribute, architecture theory, documentation, anything at all, I'd be very grateful. You can find our project here: (also feel more than welcome to join and help!) http://www.openplans.org/projects/openwitsml/summary Regards, Kenneth Miller xkenneth at gmail.com From cjw at ncf.ca Mon Jun 23 18:46:14 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 23 Jun 2008 18:46:14 -0400 Subject: IDE on the level of Eclipse or DEVc++? In-Reply-To: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> Message-ID: cirfu wrote: > is there an IDE for python of the same quality as Eclipse or DEVC++? > > I am currently using the editor that coems iwth python and it is all > fine but for bigger projects it would be nice to have some way to > easier browse the projectfiles for example. I don't know these but you might look at PyScripter. Colin W. From kusumi.tomohiro at jp.fujitsu.com Wed Jun 4 22:00:30 2008 From: kusumi.tomohiro at jp.fujitsu.com (Tomohiro Kusumi) Date: Thu, 05 Jun 2008 11:00:30 +0900 Subject: Question regarding re module Message-ID: <484748BE.4000704@jp.fujitsu.com> Hi, I have a question regarding re module. # By the way I'm not in this list, so I'm sorry but please CC me. I tried following code in Python shell using a regular expression. Why doesn't the result of dir(reg) have 'pattern', 'flags', and 'groupindex' although they exist as members of _sre.SRE_Pattern instance ? It sort of irritates me, because whenever I write Python code using a module which I'm not used to using, I often try Python shell with TAB complete to find out the member of module/instance. Tomohiro Kusumi ------------------------------------------------- Python 2.5 (r25:51908, May 16 2008, 13:41:55) [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> reg = re.compile(r"[0-9]+") >>> reg.pattern '[0-9]+' >>> reg.flags 0 >>> reg.groupindex {} >>> dir(reg) ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] >>> reg. reg.__copy__ reg.finditer reg.search reg.subn reg.__deepcopy__ reg.match reg.split reg.findall reg.scanner reg.sub From cwitts at gmail.com Fri Jun 27 05:59:51 2008 From: cwitts at gmail.com (Chris) Date: Fri, 27 Jun 2008 02:59:51 -0700 (PDT) Subject: Question on List References: <7f03fa3f-c8fd-45a8-b4a5-d7c66982aa4a@q27g2000prf.googlegroups.com> Message-ID: <8131e1be-a767-42c0-9409-b7353c7466ab@y38g2000hsy.googlegroups.com> On Jun 27, 9:51?am, subhabrata.i... at hotmail.com wrote: > Dear All, > I am trying to write the following code: > > def try1(n): > ? ? ? ? a1="God Godess Borother Sister Family" > ? ? ? ? a2=a1.split() > ? ? ? ? a3=raw_input("PRINT A WORD") > ? ? ? ? a4=a1.find(a3) > ? ? ? ? print a4 > ? ? ? ? a5=[] > ? ? ? ? if a4>0: > ? ? ? ? ? ? ? ? a5=a2.index(a3) > ? ? ? ? ? ? ? ? a6=a5+1 > ? ? ? ? ? ? ? ? a7=a2[a6] > ? ? ? ? ? ? ? ? print "The new word is" > ? ? ? ? ? ? ? ? print a7 > ? ? ? ? ? ? ? ? a8=a5.append(a7) > ? ? ? ? ? ? ? ? print a5 > ? ? ? ? elif a4<0: > ? ? ? ? ? ? ? ? a11=a3 > ? ? ? ? ? ? ? ? print "The word is not availiable in String" > ? ? ? ? ? ? ? ? print a11 > ? ? ? ? ? ? ? ? a6=a5.append(a11) > ? ? ? ? ? ? ? ? print a5 > ? ? ? ? else: > ? ? ? ? ? ? ? ? print "Error" > > Now, my question is I like to see a5 or the empty list as appended > with elements. Results I am getting is a5 giving single value like > ['God'],['Godess']... but I like to see it as ['God','Godess'...] etc. > Am I going wrong? > Do I have to rethink it in some other way? > If any one can kindly let me know. > Best Regards, > Subhabrata. First notes, the string .find() method return -1 for not found and zero or above if the search string is present. Remember you count from zero. Secondly, list .append() methods do not return a new list but modify the list in place. Thirdly, the .index() method of a list requires an integer and not a string. And lastly, indentation should be 4 spaces not 8. Just doing a sloppy job on the code (and my interpretation of what you wanted) def try1(n): new_list = [] input_string="God Godess Borother Sister Family" while n: user_selection=raw_input("PRINT A WORD") if input_string.find(user_selection) > -1: s = input_string.split() i = [i for i,j in enumerate(s) if j == user_selection] new_word = s[i+1] print 'The new word is %s' % new_word new_list.append(new_word) print new_list else: print 'User selection of "%s" not in the string.' % user_selection new_list.append(user_selection) print new_list n -= 1 Obviously I'm going to assume that the code you posted excluded your loop control for the "try n amount of times". What was most likely the cause is that you loop through your structure for every attempt of the n times but each time you reset your list when you re-create it. Hope that helps some. Chris From boggom at comcast.net Thu Jun 26 07:54:34 2008 From: boggom at comcast.net (boggom at comcast.net) Date: Thu, 26 Jun 2008 04:54:34 -0700 (PDT) Subject: very large graph References: <135bba90-a9dd-4fcd-9220-6271e5a7c876@59g2000hsb.googlegroups.com> Message-ID: Drawing a large graph like this is not very insightful by itself, and doing this well is still an art form. Many cool visualizations, and all very domain and question dependent, can be found at http://www.visualcomplexity.com/vc/ You can also search on flickr for network and graph drawing. Much of it is eyecandy though. What do you really want to know? Your graph is not overly huge for python, provided you do not want to compute nonlocal statistics such as betweenness metrics. (If you have a laptop running windows and with less than 1GB RAM, then you have a really large graph.) Given that you do not know much about graph theory, I would suggest that networkx applied to a subset of your large website --- one of the representative branches --- will allow for the fastest way to figure out what you want to do. Python provides access to many other libraries for html mangling or even webpage analysis. Imagine writing C code to ask questions like: how many pdfs and images? how big are they? when were these pages last updated? etc. You can come up with 10 questions faster than you can write C code, and this where python has its great advantage. You can learn graph theory while using these libraries, on one of the smaller branches of your website tree. Even interactively by using ipython. This provides at least a feeling of great power while stumbling in the dark. Many of your edges are probably repetitions associated with navigation menus to provide a standard look-and-feel. See how much of that you can strip out and find the cross-links that took effort to insert an manage. (I suggest doing the analyis on a digraph rather than a graph, even if you want to draw it as graph.) For visualization, the new ubigraph is quite fast compared to graphviz. See the cool networkx + ubigraph video at http://ubietylab.net/blog/ Ask on the networkx mailinglist when stuck. From lane at ubixum.com Fri Jun 27 23:37:33 2008 From: lane at ubixum.com (Lane Brooks) Date: Fri, 27 Jun 2008 21:37:33 -0600 Subject: CAPI and thread safety In-Reply-To: <4eb6ab80-7280-47fb-b8bc-366154f6274d@d1g2000hsg.googlegroups.com> References: <4eb6ab80-7280-47fb-b8bc-366154f6274d@d1g2000hsg.googlegroups.com> Message-ID: <4865B1FD.9060300@ubixum.com> Thanks for the pointer. I'll check it out. That is what I was looking for. Lane Benjamin wrote: > On Jun 27, 4:33 pm, Lane Brooks wrote: > >> I am writing an extension module that needs to release the global >> interpreter lock during some blocking I/O calls, but I need a mutex in >> the C code to make some of the shared data in the extension module are >> kept thread safe. Can anyone recommend a portable way to do this? I >> could use a pthread mutex, but I do not think that is portable. >> >> Are any of the python mutexes or locks exposed through the C API? I >> could not find anything. >> > > Look at Include/pythread.h. You can use PyThread_allocate_lock to get > the threading abstractions that Python uses. > > >> Thanks, >> Lane >> > > -- > http://mail.python.org/mailman/listinfo/python-list > From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jun 5 09:48:46 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 05 Jun 2008 15:48:46 +0200 Subject: Python and Harry Potter? References: <6aprloF38p4l7U1@mid.dfncis.de> Message-ID: <6aq95uF35vu95U1@mid.individual.net> Casey wrote: > Python fan??? Harry speaks Python fluently. We should all be so > lucky! > > I'm told Harry is looking forward to Py3K and getting rid of all > the old (hog)warts .... Well, how about another Python renaming flame thread then? Let's call Python 3.0 "Parselmouth" instead ... Regards, Bj?rn -- BOFH excuse #83: Support staff hung over, send aspirin and come back LATER. From google at mrabarnett.plus.com Fri Jun 20 10:56:32 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 20 Jun 2008 07:56:32 -0700 (PDT) Subject: Named tuples and projection References: Message-ID: <3ec6ca53-9ec9-42b4-8ee2-cb56a6aed375@z66g2000hsc.googlegroups.com> On Jun 20, 9:38?am, Giuseppe Ottaviano wrote: > I found the namedtuple very convenient for rapid prototyping code, for ? > functions that have to return a number of results that could grow as ? > the code evolves. They are more elegant than dicts, and I don't have ? > to create a new explicit class. Unfortunately in this situation they ? > lose the convenience of tuple unpacking: changing tuple's parameters ? > would break other functions unpacking the result. > One solution, with 3.0 syntax, would be unpacking only the used ? > parameters, using always a *rest > a, b, *rest = f() > so that if the tuple grows, the code keeps working. > However I find this confusing (and not avaliable in python 2.5). > I don't know if similar solutions have been proposed, I came up with ? > this one: > [snip] Provided you don't change the order of the items in the tuple, you can just use slicing: a, b = f()[ : 2] From wuwei23 at gmail.com Wed Jun 4 20:18:47 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 4 Jun 2008 17:18:47 -0700 (PDT) Subject: how should i use this function? References: <99ed3c04-bd62-4456-ae12-eca4179005dc@r66g2000hsg.googlegroups.com> Message-ID: <38e6c38a-d84c-486d-b9bc-f256c0a3e21c@a32g2000prf.googlegroups.com> On Jun 5, 4:14 am, Gandalf wrote: > I tried to import win32ui.PyCRichEditCtrl, But the shell told me > their's no such module. > > If anyone can show me an example it would be great For starters, you're looking at the documentation for ActivePython 2.2 rather than 2.5. Do you know about pythons introspective abilities? That you can find a list of available methods & objects by doing 'dir(win32ui)' in the interpreter? Having said that, here's how to get a PyCRichEditCtrl object: ActivePython 2.5.1.1 (ActiveState Software Inc.) based on Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import win32ui >>> rec = win32ui.CreateRichEditCtrl() >>> type(rec) It's worth noting that win32ui is basically just a wrapper around the Microsoft Foundation Classes, so you'll need to look through the MFC documentation rather than that of the wrapper. This might help get you started: http://www.onlamp.com/pub/a/python/excerpts/chpt20/pythonwin.html From jamitwidme at gmail.com Thu Jun 26 16:01:39 2008 From: jamitwidme at gmail.com (jamitwidme at gmail.com) Date: Thu, 26 Jun 2008 13:01:39 -0700 (PDT) Subject: ConfigParser: Can I read(ConfigParser.get()) a configuration file and use it to call a funciton? References: <34b51593-d787-4f12-9cc2-473d3832ff0d@k37g2000hsf.googlegroups.com> <7fd37b8c-b96d-480c-94c4-e53f8598830e@d45g2000hsc.googlegroups.com> Message-ID: <63176df7-2d7d-4679-ae2a-cdb5404741df@z72g2000hsb.googlegroups.com> Thank you for the answers. Now I understood how to call a function, let me ask you another question. configuration.cfg --------------------------------------- [1234] title: abcd function: efgh --------------------------------------- reading.py -------------------------------------------------------- import ConfigParser class Functions: def efgh(self): print 'blah' fcn = Functions() config = ConfigParser.ConfigParser() config.read('configuration.cfg') title = config.get('1234','title') # number 1 function_name = config.get('1234','function') title = getattr(fcn, function_name) title() -------------------------------------------------------- instead of assigning string value('abcd') to title at number 1 I want to assign this function(fcn.efgh()) to abcd and make abcd a FunctionType. so later on, I want to call it by abcd(), not title(). The reason is I will have a loop reading from configuration file, so I need to have different names for each function. abcd is a string I read got it from config.get('1234','title') Thanks again. From software at ginstrom.com Sun Jun 1 08:27:30 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Sun, 1 Jun 2008 21:27:30 +0900 Subject: [Business apps for Windows] Good grid + calendar, etc.? In-Reply-To: References: Message-ID: <0fc701c8c3e2$dc883b80$0203a8c0@MOUSE> > On Behalf Of Gilles Ganault > Is it hopeless, or did I overlook things? Are there other > solutions I should look at (FLTK, etc.)? For those of you > writing business apps in Python for Windows, how do things go > as far as GUI widgets are concerned? To do a bit of shameless plugging, I wrote an overview of Python GUI platforms for Windows a month or two ago: http://ginstrom.com/scribbles/2008/02/26/python-gui-programming-platforms-fo r-windows/ For your stated needs, I'd advise checking out IronPython or Python.NET (which allow use of .NET GUI libraries). Regards, Ryan Ginstrom From carbonimax at gmail.com Mon Jun 23 08:51:48 2008 From: carbonimax at gmail.com (Carbonimax) Date: Mon, 23 Jun 2008 05:51:48 -0700 (PDT) Subject: py2exe, PyQT, QtWebKit and jpeg problem References: Message-ID: <37ce3f9c-034e-4a3d-8524-310810894715@s50g2000hsb.googlegroups.com> On Jun 21, 12:21?am, David Boddie wrote: > On Friday 20 June 2008 17:24, Phil Thompson wrote: > > > On Fri, 20 Jun 2008 08:04:57 -0700 (PDT),Carbonimax > > wrote: > >> I have a problem with py2exe and QtWebKit : > >> I make a program with a QtWebKit view. > >> If I launch the .py directly, all images (jpg, png) are displayed but > >> if I compile it with py2exe I have only png images. No jpg ! > >> No error message, nothing. > > >> Have you a solution ? Thank you. > > > At a guess, the JPEG support is implemented as a Qt plugin which you are > > not including. > > Yes, that would appear to the be most obvious cause. See here for another > report about this: > > http://lists.trolltech.com/qt4-preview-feedback/2008-03/msg00064.html > > David How can I do that ? If I copy the dll in the dist directory, and I use QLibrary() and load(), it does work in the .py but it doesn't in .exe made with py2exe my code : dll = QLibrary(path_to_dll) res = dll.load() res == true in the .py res == false in the .exe :-/ From ivan.illarionov at gmail.com Fri Jun 20 04:27:06 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Fri, 20 Jun 2008 01:27:06 -0700 (PDT) Subject: advanced listcomprehenions? References: Message-ID: <3b92811d-a029-440f-9e56-1d4ca2fa064e@d1g2000hsg.googlegroups.com> On 20 ???, 11:31, Duncan Booth wrote: > Terry Reedy wrote: > >> [['Fizz', 'Buzz', 'FizzBuzz', str(i)][62/(pow(i, 4, 15) + 1)%4] for i > >> in xrange(1, 101)] > > > These make the lookup table variable, so it has to be recalculated for > > each i. > > So what? Mark Wooding was posting about mathematical elegance and came up > with that really neat pow() call. If runtime came into it then one of the > previous solutions or (as Mark already said) a straightforward sometable[i% > 15] is going beat something like this hands-down. > > This is coding for fun not profit. > > -- > Duncan Boothhttp://kupuguy.blogspot.com I can't resist... [[i,"Fizz","Buzz","FizzBuzz"][(not i%3)+(not i%5)*2] for i in range(1, 101)] Ivan From gabriela.soares.fcup at gmail.com Wed Jun 11 11:42:06 2008 From: gabriela.soares.fcup at gmail.com (Gabriela Soares) Date: Wed, 11 Jun 2008 16:42:06 +0100 Subject: [Tutor] python gui In-Reply-To: <333efb450806110825i376b9e45we2e6d98d6bdb0396@mail.gmail.com> References: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> <333efb450806110818g134b930cj6e36f7bd79a9083@mail.gmail.com> <9d68e4e90806110818q18c57bd2v8b3219de9b2a1ca1@mail.gmail.com> <333efb450806110825i376b9e45we2e6d98d6bdb0396@mail.gmail.com> Message-ID: <9d68e4e90806110842i51e3cf4fsbf8540a301db5a7f@mail.gmail.com> Hello, With all respect, I posed the question as a noob who has NO ideia how to solve the problem at hand. All I asked for were some references, such as known applications that use such technology to guide me to where I should focus. It never crossed my mind to ask for code. If I wanted to do so, I wouldn't use a mailing list and would go to search engines such as google code or krugle. I am sorry you got the wrong impression. If I didn't explain myself the most correct way, then I present my apologies. The link I gave was in flex, so redirecting me to a page about flex is useless. I was asking about how can I get a similar effect but using just python. There fits the python mailing list and the **possible** broad question. If you can't help me I surelly understand. But please do not take me for a fool kind sir/madam. Thank you, Gabriela Soares. On Wed, Jun 11, 2008 at 4:25 PM, W W wrote: > On Wed, Jun 11, 2008 at 10:18 AM, Gabriela Soares > wrote: > > How ? > > That's an extremely broad question, and shows little initiative, and > offers little information. Most of us are happy to help you solve > problems for free, but few, if any, are willing to write your programs > for free. > > > Any references ? > > www.google.com > > Norman linked to a fairly interesting project. > > Hope this helps, > Wayne > > > On Wed, Jun 11, 2008 at 4:18 PM, W W wrote: > >> > >> On Wed, Jun 11, 2008 at 8:03 AM, Gabriela Soares > >> wrote: > >> > Greetings, > >> > > >> > I want to make a dynamic dashboard, something like: > >> > > >> > http://examples.adobe.com/flex3/labs/dashboard/main.html# > >> > > >> > but using python. Is it possible ? > >> > >> Yes. > >> > >> -Wayne > > > > > > > > -- > > Gabriela Soares > > > > "I learned that courage was not the absence of fear, but the triumph over > > it. The brave man is not he who does not feel afraid, but he who conquers > > that fear." > > Nelson Mandela > > > > -- > To be considered stupid and to be told so is more painful than being > called gluttonous, mendacious, violent, lascivious, lazy, cowardly: > every weakness, every vice, has found its defenders, its rhetoric, its > ennoblement and exaltation, but stupidity hasn't. - Primo Levi > -- Gabriela Soares "I learned that courage was not the absence of fear, but the triumph over it. The brave man is not he who does not feel afraid, but he who conquers that fear." Nelson Mandela -------------- next part -------------- An HTML attachment was scrubbed... URL: From dp at admailinc.com Wed Jun 18 13:26:31 2008 From: dp at admailinc.com (Ethan Furman) Date: Wed, 18 Jun 2008 09:26:31 -0800 Subject: Does '!=' equivelent to 'is not' [drifting a little more] In-Reply-To: References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> Message-ID: <48594547.8090305@admailinc.com> Gabriel Genellina wrote: > (This thread is getting way above 10000cp...) What is 10000cp? -- Ethan From jeff_d_harper at hotmail.com Sat Jun 21 01:15:37 2008 From: jeff_d_harper at hotmail.com (jeff_d_harper at hotmail.com) Date: Fri, 20 Jun 2008 22:15:37 -0700 (PDT) Subject: Sqlite3 textfactory and user-defined function Message-ID: I've run into a problem with text encoding in the Sqlite3 module. I think it may be a bug. By default sqlite3 converts strings in the database from UTF-8 to unicode. This conversion can be controlled by changing the connection's text_factory. I have a database that stores strings in 8-bit ISO-8859. So, I set the text_factory to do no conversion. In my database I use user defined functions. I noticed that even when I set text_factory = lambda x:x, it appears to do UTF-8 to unicode conversion on strings that are passed to my user defined function. I've included a small program that illustrates the problem. It creates a database and table in memory and then populates 2 rows. One row contains an ASCII string. The other row contains a string with the non-ascii string, "T?st". Then, the program does an SQL select which calls the user-defined function, my_func(). The resulting row tuples contain 8-bit strings. But, my_func() is passed unicode strings. Notice, my_func is called with None instead of "T?st". I suspect this is because the binary representation of "T?st" is not valid UTF-8. Is there a way to turn off the UTF-8 to unicode when my_func() is called? Is this a bug or intended behavior? import sqlite3 def create_table(dbase): #dbase.execute(r"""PRAGMA encoding = "UTF-16le";""") dbase.execute(r"""CREATE TABLE `my_table` ( 'id' INTEGER, 'column' BLOB); """) def add_rows(dbase): c = dbase.cursor() string1 = "Test" string2 = "T\xe9st" try: print string1 c.execute(r"""INSERT INTO `my_table` ('id', 'column') VALUES (?,?)""", (1,string1)) print string2 c.execute(r"""INSERT INTO `my_table` ('id', 'column') VALUES (?,?)""", (2,string2,)) finally: c.close() def select_rows(dbase): c = dbase.cursor() try: c.execute(r"""SELECT *, my_func(`column`) FROM `my_table`""") for row in c: print row finally: c.close() def factory(x): print 'x =', x return x def my_func(p): print 'my_func(%r) type = %s' % (p,type(p)) def my_test(): db_path = ":memory:" try: os.remove(db_path) except: pass dbase = sqlite3.connect(db_path) dbase.text_factory = lambda x:x dbase.create_function('my_func', 1, my_func) try: create_table(dbase) add_rows(dbase) select_rows(dbase) finally: dbase.commit() dbase.close() my_test() From socyl at 987jk.com.invalid Thu Jun 19 17:17:35 2008 From: socyl at 987jk.com.invalid (kj) Date: Thu, 19 Jun 2008 21:17:35 +0000 (UTC) Subject: Why no output from xml.dom.ext.PrettyPrint? Message-ID: OK, the following should work but doesn't, and I can't figure out why: >>> from xml.marshal.generic import dumps >>> dumps( ( 1, 2.0, 'foo', [3,4,5] ) ) '12.0foo345' >>> from xml.dom.ext import PrettyPrint >>> PrettyPrint( dumps( ( 1, 2.0, 'foo', [3,4,5] ) ) ) >>> import sys >>> PrettyPrint( dumps( ( 1, 2.0, 'foo', [3,4,5] ) ), sys.stdout ) >>> Why am I seeing no output from PrettyPrint? TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From python at hope.cz Mon Jun 9 11:02:51 2008 From: python at hope.cz (Johny) Date: Mon, 9 Jun 2008 08:02:51 -0700 (PDT) Subject: How to find the first space? Message-ID: <7a91cc8f-2e93-46e9-8360-a01da9170187@m44g2000hsc.googlegroups.com> How can I find the first space using regex? For example I have text Text=' This is a sample ' The last space I can remove by Text=re.sub(r"\s(?!\w)",'',Text) but I do not know how to remove the first space. Can anyone help? Thanks L. From circularfunc at yahoo.se Tue Jun 24 14:30:55 2008 From: circularfunc at yahoo.se (cirfu) Date: Tue, 24 Jun 2008 11:30:55 -0700 (PDT) Subject: NameError: name 'maketrans' is not defined, pythonchallenge References: <50a56351-b875-4a08-b19c-3ac6092fd509@e39g2000hsf.googlegroups.com> Message-ID: import string text = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." table = string.maketrans(string.ascii_lowercase, string.ascii_lowercase[2:]+string.ascii_lowercase[:2]) print string.translate(text,table) From Russ.Paielli at gmail.com Tue Jun 3 00:11:58 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 2 Jun 2008 21:11:58 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> Message-ID: <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> On Jun 2, 6:21 pm, alex23 wrote: > On Jun 3, 9:41 am, "Russ P." wrote: > > > Here's what I think Python should have. I think it should have a > > keyword, something like "priv," to identify data or functions as > > "private." > > As I stated earlier in this thread, if you want a public interface and > a private implementation, rather than adding another language feature > why not just separate them into two classes? This is exactly what the > Bridge pattern provides and would clearly denote your intention in the > code. Yes, that looks interesting, but I think it has a couple of drawbacks. First, it requires another completely separate class for the "implementation" (although perhaps that could be a nested class). Secondly, I think it essentially just adds a sort of inner namespace through which the "private" data is accessed. That might be a good idea, but I don't think it's quite the same as encapsulation. From bignose+hates-spam at benfinney.id.au Tue Jun 17 22:26:57 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 18 Jun 2008 12:26:57 +1000 Subject: Annoying message when interrupting python scripts References: <578d1ef8-231b-46fa-a181-e320fe1cc368@s33g2000pri.googlegroups.com> Message-ID: <87y753wk9a.fsf@benfinney.id.au> John Machin writes: > On Jun 18, 12:51 am, geoffbache wrote: > [snip] > > Is this a bug? I couldn't find any code, but I imagine something like > > try: > > import site > > except: > > sys.stderr.write("import site failed; use -v for traceback\n") > > > > which should surely allow a KeyboardInterrupt exception through? > > Surely?? A bare "except" catches *all* remaining uncaught exceptions. I parsed that "should" as "this should be changed". > Allowing a KeyboardInterrupt exception through would require: > except KeyboardInterrupt: > pass Actually, to allow it through would require re-raising it: except KeyboardInterrupt: raise Yes, I think that's what Geoff is saying "should" be done :-) -- \ "When I was born I was so surprised I couldn't talk for a year | `\ and a half." -- Gracie Allen | _o__) | Ben Finney From chardish at gmail.com Tue Jun 10 14:01:02 2008 From: chardish at gmail.com (chardish at gmail.com) Date: Tue, 10 Jun 2008 11:01:02 -0700 (PDT) Subject: Instructions on how to build py2exe 0.6.8 (or an installer would be nice, too!) References: <5426baaf-2ba6-41b0-a0ec-1070429b5195@x35g2000hsb.googlegroups.com> <7f3360e4-8a12-45cf-99fa-6172cb5a1aaa@a1g2000hsb.googlegroups.com> <5cde3ec8-2e8d-4c1e-bee9-1ee51f649cd8@d45g2000hsc.googlegroups.com> Message-ID: <9af1adfb-5bce-48e8-b17f-4d838f788b90@d77g2000hsb.googlegroups.com> On Jun 10, 1:11?pm, Mike Driscoll wrote: > On Jun 10, 10:47?am, chard... at gmail.com wrote: > > > > > On Jun 10, 11:34?am, Mike Driscoll wrote: > > > > Maybe I'm missing something, but I can rename the executables I create > > > using py2exe 0.6.6 to anything I want after they're created. > > > > Or are you talking about a Windows installer for the py2exe module > > > itself? Where are you finding this 0.6.8 version anyway? I can't find > > > it onwww.py2exe.org > > > > Anyway, what Thomas is talking about is that the only way to create a > > > usable installer of py2exe on Windows is to use the same compiler that > > > the Python you are using. As I understand it, Python 2.4 and 2.5 used > > > Visual Studio 2003. I think 2.3 used VS6. I have both, so I can try to > > > compile an installer for any of those versions if you can link me to > > > the source. > > > > Mike > > > > Python Extension Building Network: ? ? http:\\www.pythonlibrary.org > > > The issue with renaming executables only applies to single-file > > executables, i.e. ones created with zipfile = None as an argument to > > setup() and --bundle 1 as a command line argument. This is a known > > issue as of 0.6.6:http://py2exe.org/index.cgi/ProblemsToBeFixed > > I'm using GUI2Exe to wrap my 0.6.6 version of py2exe. I use the bundle > into a single file option in it and have zipfile=None too. But maybe > one of my other switches is different. > > > > > I found sources for 0.6.8 on CVS at:http://sourceforge.net/cvs/?group_id=15583 > > > A Windows installer for the 0.6.8 py2exe module would be ideal, but > > somehow I doubt that's going to happen anytime soon since there hasn't > > been a new installer since 2006. If you are willing to build that for > > me (since I don't have VS) I'd really appreciate it : ) I'm using 32- > > bit WinXP on this computer. > > I finally figured out how to check out the code. I'm at work now, > where I only have VS2008 installed so I'll have to wait until I get > home this evening to try compiling it. I'll let you know if I have any > luck. > > --------------------- > Mike > > Python Extension Building Network: ? ? http:\\www.pythonlibrary.org Thanks, Mike. Hopefully you'll have more luck than I've had : ) Evan From kumarvs06561 at gmail.com Tue Jun 10 13:25:37 2008 From: kumarvs06561 at gmail.com (kumarvs06561 at gmail.com) Date: Tue, 10 Jun 2008 10:25:37 -0700 (PDT) Subject: make more money Message-ID: make more money internet jobs easy way to make money http://kumarpracticals.blogspot.com/ From kyosohma at gmail.com Tue Jun 17 13:49:57 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 17 Jun 2008 10:49:57 -0700 (PDT) Subject: text alignment References: <39d1c620-9923-46e7-999d-ed86c8b465ff@34g2000hsh.googlegroups.com> Message-ID: <114f3f4c-4004-488b-86c5-4bf6416e15bd@l42g2000hsc.googlegroups.com> On Jun 17, 11:45?am, Gandalf wrote: > On Jun 17, 6:43?pm, Gandalf wrote: > > > Hi every one. What is the similar python WX style property for CSS > > text-align? > > > I need this item text to start from the right direction: > > > aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60)) > > ? ? ? ? aaa.LoadPage('../../aa.html') > > > Thanks! > > *right to the left direction... > > And I'm using pythin 2.5 on XP (I forget to mention...) The HtmlWindow widget can only display simple html. So, while you cannot use CSS, you should be able to use the simple html alignment directives. Check out the following site for pointers: http://www.htmlite.com/lite008.php If you want to be able to use CSS and javascript, you'll want to use the ActiveX_IEHtmlWindow (wx.lib.iewin) widget instead as it embeds Internet Explorer. Mike From Lie.1296 at gmail.com Sat Jun 21 08:55:12 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 21 Jun 2008 05:55:12 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <79a1c500-1844-4405-8f52-21e845a85f9b@z66g2000hsc.googlegroups.com> Message-ID: <5678904d-93ee-40f1-97b2-78d49ce29fb7@f24g2000prh.googlegroups.com> On Jun 21, 2:02?pm, eliben wrote: > On Jun 21, 8:52 am, Peter Otten <__pete... at web.de> wrote: > > > > > eliben wrote: > > > On Jun 20, 2:44 pm, Peter Otten <__pete... at web.de> wrote: > > >> eliben wrote: > > >> > Additionally, I've found indentation to be a problem in such > > >> > constructs. Is there a workable way to indent the code at the level of > > >> > build_func, and not on column 0 ? > > > >> exec"if 1:" + code.rstrip() > > > >> Peter > > > > Why is the 'if' needed here ? I had .strip work for me: > > > A simple .strip() doesn't work if the code comprises multiple lines: > > > >>> def f(): > > > ... ? ? return """ > > ... ? ? x = 42 > > ... ? ? if x > 0: > > ... ? ? ? ? ? ? print x > > ... ? ? """ > > ...>>> exec "if 1:\n" + f().rstrip() > > 42 > > >>> exec f().strip() > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? File "", line 2 > > ? ? if x > 0: > > ? ? ^ > > IndentationError: unexpected indent > > I see. In my case I only evaluate function definitions with 'exec', so > I only need to de-indent the first line, and the others can be > indented because they're in a new scope anyway. What you suggest works > for arbitrary code and not only function definitions. It's a nice > trick with the "if 1:" :-) Have you actually profiled your code? Or are you just basing this assumptions on guesses? From goldnery at gmail.com Wed Jun 4 14:59:33 2008 From: goldnery at gmail.com (Gandalf) Date: Wed, 4 Jun 2008 11:59:33 -0700 (PDT) Subject: how should i use this function? References: <99ed3c04-bd62-4456-ae12-eca4179005dc@r66g2000hsg.googlegroups.com> <5a09fa94-b3ce-4a13-af42-b9a1e6980900@25g2000hsx.googlegroups.com> Message-ID: On Jun 4, 8:21 pm, sturlamolden wrote: > On Jun 4, 8:14 pm, Gandalf wrote: > > > I tried to import win32ui.PyCRichEditCtrl, But the shell told me > > their's no such module. > > There isn't, as it is a class. win32ui is a module. If you cannot > import that, you don't have pywin32 installed. Go get it from > Sourceforge. But I pywin32 use it all the time i have pywinauto From none at this.time Thu Jun 26 00:07:16 2008 From: none at this.time (The Pythonista) Date: Thu, 26 Jun 2008 00:07:16 -0400 Subject: Any GUI lib wiget is capable of a WYSIWYG editor? References: Message-ID: On Tue, 24 Jun 2008 14:23:12 +0800, oyster wrote: > that is an html editor with text and picture, while the picture is > linked to the local image file. > > for wxPython, the richtextcontrol save the image as en embedded object, > so it is not my choice > > is there any other GUI lib and/or sample code to do so? > > thanks Consider TkHtml. You can find a Tix wrapper for it here: http://tix.sourceforge.net/Tixapps/src/Python/TkHtml.py -- code.py: A blog about life, the universe, and Python http://pythonista.wordpress.com ** Posted from http://www.teranews.com ** From mccredie at gmail.com Tue Jun 24 18:45:42 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 24 Jun 2008 15:45:42 -0700 (PDT) Subject: Sequence iterators with __index__ References: Message-ID: <433c6aca-745e-4c9f-b182-d76291449829@m73g2000hsh.googlegroups.com> On Jun 24, 3:29?pm, schickb wrote: > I think it would be useful if iterators on sequences had the __index__ > method so that they could be used to slice sequences. I was writing a > class and wanted to return a list iterator to callers. ?I then wanted > to let callers slice from an iterator's position, but that isn't > supported without creating a custom iterator class. > > Are there reasons for not supporting this generally? I realize not all > iterators would have the __index__ method, but that seems ok. > > In Python 3, maybe this could be called a SequenceIterator > > -Brad Could you post an example of what you are talking about? I'm not getting it. In any case, the first step is writing a PEP. http://www.python.org/dev/peps/ Matt From mensanator at aol.com Sat Jun 7 13:24:23 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 7 Jun 2008 10:24:23 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> Message-ID: <0f156f41-3c84-48c4-bfa0-391cf11ce119@c58g2000hsc.googlegroups.com> On Jun 7, 5:21?am, Paul Miller wrote: > On Fri, 06 Jun 2008 18:01:45 -0700, Mensanator wrote: > > What happens if your iterables aren't the same length? > > I chose not to consider that case, That's a bad habit to teach a newbie, isn't it? > since they were the same length in the > original post. ? The issue I'm stressing is HOW they got to be the same size. If I was teaching programming and the OP turned in that example, I would mark him down. Not because he got the answer wrong. Not because he used zip. Not because he failed to use enumerate or itertools. But because he hardcoded the array bounds and THAT'S the lesson the OP should take away from this. > Based on the variable names, it seemed reasonable that > there would always be a 1-to-1 correspondence between > elements of each list. ? Yes, reasonable at the time. But this is Python, not C. Lists can change size under program control, a feature that's extremely useful. But there's a price for that usefulness. Practices that made sense in C (define a constant to set array bounds) aren't transportable over to systems that simply don't have the restrictions that require those practices. > However, if you do > > score_costs = [(base_scores[i], score_costs[i]) for i in range (min (len > (base_scores), len (score_costs))] > > then you get exactly what you would get using zip. ? And if the iterables change size dynamically, you could get either a crash due to index out of range or else silently a wrong answer. > That's one heck of a > long line, though, hence my earlier comment: I have no problem telling the OP this method. But I think you should warn him about potential problems. Surely you didn't intend to leave him to twist in the wind so that he learns a thing or two when his programs crash? > > >> But, I'd rather just use zip. :-) > > > And with zip() you won't get an error, but it won't be correct, either. > > If it doing what zip() does makes sense, then just use zip(). ?Otherwise, > check for the case where the iterables are of different length, and do > the appropriate thing (raise an error, pad the shorter one, whatever). That's all I'm suggesting. Along with pointing out that enumerate or itertools can do this for him. > > -- > code.py: a blog about Python. ?http://pythonista.wordpress.com > ** Posted fromhttp://www.teranews.com** From deets at nospam.web.de Mon Jun 9 18:15:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 10 Jun 2008 00:15:29 +0200 Subject: Question by someone coming from C... In-Reply-To: References: Message-ID: <6b5oc2F38ti2mU1@mid.uni-berlin.de> Skye schrieb: > Writing this app in Python, not sure what the "best practice" would > be. > > I want a bitfield global logging level that allows me to turn specific > debugging modules on and off. If I was doing this in C, I'd just use > some globals like: > > unsigned int debug_level = 0; > #define DEBUG_GENERAL 0x0001 > #define DEBUG_CONFIG 0x0002 > #define DEBUG_OPTIONS 0x0004 > etc etc For debugging - use the module logging. And configure properly. Diez From rcdailey at gmail.com Fri Jun 6 13:31:37 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 6 Jun 2008 12:31:37 -0500 Subject: Where to find Visual Studio Syntax Highlighting (for python)? Message-ID: <496954360806061031y52a1312chce74619442097620@mail.gmail.com> Hi, Does anyone know of a way to get syntax coloring working in Visual Studio 2008 for Python? I did some googling but I couldn't find anything. Help is appreciated, thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From circularfunc at yahoo.se Sun Jun 22 18:32:24 2008 From: circularfunc at yahoo.se (cirfu) Date: Sun, 22 Jun 2008 15:32:24 -0700 (PDT) Subject: listcomprehension, add elements? Message-ID: <13452c64-ef91-49a2-bb73-7f33c088660e@d45g2000hsc.googlegroups.com> [a+b for a,b in zip(xrange(1,51), xrange(50,0,-1))] [51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51] i want to add all the elemtns a s well. can i do this all in a listcomprehension? i can do this ofc: reduce(lambda x,y:x+y,[a+b for a,b in zip(xrange(1,51), xrange(50,0,-1))]) but reduce is a functional way of doing it, what is the more pythonic way of doing this? From kris at FreeBSD.org Tue Jun 24 07:44:49 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Tue, 24 Jun 2008 13:44:49 +0200 Subject: Bit substring search Message-ID: <4860DE31.1040407@FreeBSD.org> I am trying to parse a bit-stream file format (bzip2) that does not have byte-aligned record boundaries, so I need to do efficient matching of bit substrings at arbitrary bit offsets. Is there a package that can do this? This one comes close: http://ilan.schnell-web.net/prog/bitarray/ but it only supports single bit substring match. Kris From nwinters3000 at gmail.com Tue Jun 10 09:47:13 2008 From: nwinters3000 at gmail.com (nwinters3000 at gmail.com) Date: Tue, 10 Jun 2008 06:47:13 -0700 (PDT) Subject: PEP on breaking outer loops with StopIteration References: Message-ID: <98d87e96-3e6e-4b13-acf3-1f7db4409a42@x1g2000prh.googlegroups.com> On Jun 9, 10:50?pm, Dan Bishop wrote: > On Jun 9, 8:07?pm, "Kris Kowal" wrote: > > > I had a thought that might be pepworthy. ?Might we be able to break > > outer loops using an iter-instance specific StopIteration type? > > > You can break out of outer loops now with the proper (ab)use of > exceptions: > > class BreakInner(Exception): > pass > class BreakOuter(Exception): > pass > try: > for letter in string.lowercase: > try: > for number in xrange(10): > print letter, number > if letter == 'a' and number == 5: > raise BreakInner() > if letter == 'b' and number == 5: > raise BreakOuter() > except BreakInner: > pass > except BreakOuter: > pass I prefer having a new function wrapping the inner loop and using both break and return, but this doesn't allow you to "break 1 loop up and 2 loops up", and doesn't help to continue a particular loop further up def innerLoop(letter): for number in xrange(10): print letter, number if letter == 'a' and number == 5: break if letter == 'b' and number == 5: return for letter in string.lowercase: innerLoop(letter) In response to the suggested syntax, I have found occasions where I iterate through the same variable [say searching for duplicates within some tolerance to merge into one item] in an inner loop. I also don't see how it would extend to something like: for evenNumber in [x*2+1 for x in xrange(5)]: print evenNumber From afriere at yahoo.co.uk Tue Jun 24 21:35:58 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 24 Jun 2008 18:35:58 -0700 (PDT) Subject: how to convert '8868' to u'\u8868' References: <5268385d-04c7-4726-ab55-0f729ce8d883@a9g2000prl.googlegroups.com> Message-ID: <5580a767-367b-44c0-8ef4-5c8585ed86cd@a32g2000prf.googlegroups.com> On Jun 25, 11:30 am, CodeHunter wrote: > a = '8868' > b = u'\u8868' > > I want to convert a to b > > who can help me ? > > thank you very much! unicode(a) From hv at tbz-pariv.de Wed Jun 4 05:22:49 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Wed, 04 Jun 2008 11:22:49 +0200 Subject: Image Processing (batch) In-Reply-To: <48454198$0$12642$3b214f66@aconews.univie.ac.at> References: <6akqd5F37rofnU1@mid.individual.net> <48454198$0$12642$3b214f66@aconews.univie.ac.at> Message-ID: <6an58hF37ifogU1@mid.individual.net> Weinhandl Herbert schrieb: > Thomas Guettler schrieb: >> Hi, >> >> I tried PIL for image batch processing. But somehow I don't like it >> - Font-Selection: You need to give the name of the font file. >> - Drawing on an image needs a different object that pasting and saving. >> - The handbook is from Dec. 2006. >> >> What image libraries do you suggest? > > try : > http://photobatch.stani.be/ This is a GUI, my processing needs to be done on the server. I need a library with Python API. photobatch uses PIL, so I think I would not gain much. Does photobatch improve font loading? BTW, the homepage of this project uses frames. The URL does not change, ... you can't send links or bookmark pages. Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From rurpy at yahoo.com Mon Jun 2 19:26:35 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Mon, 2 Jun 2008 16:26:35 -0700 (PDT) Subject: Checking each item in m.group()? References: <2d1b2ac1-3fa1-41c7-a2c2-560c8322b6fb@z72g2000hsb.googlegroups.com> Message-ID: miller.paul.w at gmail.com wrote: > On Jun 2, 5:06 pm, Peter Otten <__pete... at web.de> wrote: > >> You are taking the wrong approach here. >> >> Don't build SQL statements as strings; you are enabling the next SQL >> injection attack. Pass parameters using the DB API instead. >> >> Don't use regular expressions to parse a CSV file. Python's csv module is >> more likely to deal correctly with the quirks of that standard. >> > > I'd like to second both these statements. Regardless of whether these > CSV files are from a trusted source or not, it's a virtual truism of > programming that eventually, any application will be used in ways it > was not intended. Since using a parameterized query is a simple way > to avoid a common security hole, even if such a thing could never be > exploited by the app in its current configuration, you should do > things the Right Way. That way, even if your code is twisted to some > other use in the future, it's less likely to cause problems. I don't have a problem with a response saying "it's a good idea to use parameterized queries and explaining why", but I have seen way too many responses like this which are basically FUD. I'm not sure what a "virtual" truism is, but if it is like a truism, it's not true. There are many cases where one can accurately predict that the code will not be used in the future in some different app. I don't know what the OP was doing, but I have done many data conversion jobs where I have done things similar to the OP. The jobs were one-time, move data from system A to system B (with some munging in between) and I could and did predict the conversion code would not get reused. My accuracy rate is 100%. And if you do reuse code where you feed it untrusted input in a security sensitive context, and you don't bother to verify the security of said, code, you already have so many problems, one more probably won't make much difference. To the OP: The advice to use parameterized queries is good but overstated. There are cases when it is quite safe to use non-parameterized statements: * When you control the data going into the query )e.g., you've generated it yourself). * When the data come from trusted sources (including something like sys.input if the only people with access to the program are trusted). * When you can reliably check the data yourself, for example in: sql = "SELECT * FROM foo WHERE id=%d" % int(some_string) cursor.execute (sql) it doesn't really matter what "some_string" contains (if you are prepared for a Python exception). But note that checking and escaping strings in more general or complicated cases can be quite tricky.) In most cases a good reason to use a parameterized query is that it is no harder than to not use one, so why not and get the additional safety for free? A parameterized query can often run faster than a non-parameterized one since the database can reuse the cached compiled query. (But sometimes the opposite is true, see below). A parameterized form of the above is: sql = "SELECT * FROM foo WHERE id=?" % int(some_string) cursor.execute (sql, int(some_string)) so it is just as easy. There are times though when it is slightly harder. If idnums is an arbitrary list of ints: sql = "SELECT * FROM foo WHERE id IN(%s) % ','.join(idnums) cursor.execute (sql) Using a parameterized query might look like: sql = "SELECT * FROM foo WHERE id IN(%s) % ','.join(['?']*len(idnums)) cursor.execute (sql, idnums) When you have written such code a few times it becomes a natural idiom, but if you only do so occasionally, you are in a hurry, and the conditions above apply, then there is no reason not to go with the first form. And if you you already have a text string of comma-separated digits, the ease of using the direct sql form becomes even greater: sql = "SELECT * FROM foo WHERE id IN(%s) % idnums_string cursor.execute (sql) But of course, if "idnums_strings" came from an untrusted source, then you need to validate it first, e.g.: if idnums_string.strip("0123456789 ,"): then raise Error There are also times when using a parameterized query can dramatically (and I mean two or three *orders of magnitude*) slow down your query when using prepared queries. For example: sql = "SELECT * FROM foo WHERE txt LIKE "%s%%" % some_string cursor.execute (sql) can be expected to run quite quickly in most database systems, since the database knows that the searched for text starts with a constant string and can thus use an index. The parameterized form: sql = "SELECT * FROM foo WHERE txt LIKE ?" cursor.execute (sql, [some_string + "%"]) will often run very very slowly, because when the query is prepared the database has no idea if the argument will start with a constant string of not, and thus can only assume the worst, and prepare the query so that it doesn't use an index. The bottom line is, as in all things, understanding the issues will lead to much better decisions than blindly following some dumbed down advice like, "always use parameterized queries". (And to the OP. if you already know all this, my apologies if I sound like I'm talking down to you, but perhaps other people may benefit. I get tired of reading simplistic "do X, period." responses sometimes.) From wmcbrine at users.sf.net Wed Jun 25 21:13:10 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Thu, 26 Jun 2008 01:13:10 GMT Subject: Newbie question about tuples and list comprehensions References: Message-ID: On Wed, 25 Jun 2008 16:02:52 -0700, John Machin wrote: > Here's one approach (requires Python 2.5 or later): > [(50 if x < 50 else x, 50 if y < 50 else y, 50 if z < 50 else z) for > (x, y, z) in source] [(max(x, 50), max(y, 50), max(z, 50)) for (x, y, z) in source] -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From Lie.1296 at gmail.com Tue Jun 10 19:09:29 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 10 Jun 2008 16:09:29 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net> <484ad07b$0$25721$607ed4bc@cv.net> <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> <484b3464$0$25724$607ed4bc@cv.net> <09d98480-c834-42bd-b97f-481133be9cb4@s50g2000hsb.googlegroups.com> <77d2d56a-7ab6-4d33-81d4-b15cc8fc63d6@u36g2000prf.googlegroups.com> Message-ID: On Jun 8, 11:11?pm, Mensanator wrote: > On Jun 8, 4:04?am, Lie wrote: > > > > > On Jun 8, 8:56?am, Mensanator wrote: > > > > On Jun 7, 8:22?pm, John Salerno wrote: > > > > > Mensanator wrote: > > > > > What I DID say was that how the builtins actually > > > > > work should be understood and it APPEARED that the > > > > > OP didn't understand that. Maybe he understood that > > > > > all along but his example betrayed no evidence of > > > > > that understanding. > > > > > Well, the truth is that I know zip truncates to the shorter of the two > > > > arguments, > > > > Ok, sorry I thought otherwise. > > > > > and also in my case the two arguments would always be the > > > > same length. > > > > Yes, because you're controlling the source code. > > > But since lists are mutable, source code literals > > > don't always control the length of the list. > > > Since when source code literals ever control the length of a list? > > Isn't score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] > considered a literal? Yep, but it's not the sole controller of the length of a list. There are other things that might control the length of the list like del, append, etc. > > What controls the length of the list is the semantic meaning of the > > list, > > Wha do you mean by that? The list contains 11 objects. > How could the length be any different? What I meant is in some cases (not all) the list might semantically be nonsense if it is of different length (i.e. it have fixed length). > > in some cases it just makes no sense that the list would ever > > have different length. > > And in such case there won't be any problem, will there? > > Is that a good habit to teach a newbie? To write > code that only works for special cases? I think it is up to the programmer to decide whether special case is enough or a general case is necessary. From roopesh.raj at gmail.com Fri Jun 20 03:37:32 2008 From: roopesh.raj at gmail.com (Roopesh) Date: Fri, 20 Jun 2008 00:37:32 -0700 (PDT) Subject: poplib - retr() getting stuck Message-ID: <3504f6cc-5cb7-4115-8d79-a7a5cd810689@d19g2000prm.googlegroups.com> Hi, I am using poplib's retr() to fetch mails from my gmail account. It works fine, in some cases it gets stuck inside the retr() method and does not come out. >From the logs I could find that when retr() is called, it stops executing further statements, nor does it throw an exceptions but simply stops. My code is roughly like the foll: try: print "1" mymsg = M.retr(msg_no) print "2" except poplib.error_proto, e: print "exception1" except Exception, e: print "exception2" What can be the reason for this? Can anyone help me. Thanks Roopesh From rasmussen.bryan at gmail.com Fri Jun 20 04:15:12 2008 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Fri, 20 Jun 2008 10:15:12 +0200 Subject: don't make it worse! - was Re: SPAM In-Reply-To: <485B5F5F.8070207@gmail.com> References: <88f0c3ba-46e1-4b30-a61d-482e5ecf339a@t12g2000prg.googlegroups.com> <485A0E77.2050009@gmail.com> <485AE162.8050407@gmail.com> <485B5F5F.8070207@gmail.com> Message-ID: <3bb44c6e0806200115g5101faa3jd6e4c253978a7d52@mail.gmail.com> I guess it didn't because I was reading through Google Mail, and it wasn't filtered. Best Regards, Bryan Rasmussen On Fri, Jun 20, 2008 at 9:42 AM, Aspersieman wrote: > Michael Torrie wrote: > > Aspersieman wrote: > > > SPAM > > > Obviously. Please refrain from replying to the SPAM on this list. It > just makes the problem worse. > > Thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list > > > > Errr....Ok. > > I read somewhere that replying to potential spam with 'SPAM' in subject will > add it (the message sender you are replying to) to google's spam filters. > Can't find the link now though. > > Sorry though, if doing this didn't help - or made it worse. :) > > Nicol > > -- > > The three things to remember about Llamas: > 1) They are harmless > 2) They are deadly > 3) They are made of lava, and thus nice to cuddle. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From jeff at jmcneil.net Sat Jun 14 21:55:16 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Sat, 14 Jun 2008 18:55:16 -0700 (PDT) Subject: Socket Programming References: Message-ID: <1dfab813-2491-4d6e-a46f-f3616e9d88f4@f63g2000hsf.googlegroups.com> On Jun 14, 5:38?pm, srinivasan srinivas wrote: > Hi, > Is there any way(method) to find whether the socket got closed or not?? > Thanks, > Srini > > ? ? ? Best Jokes, Best Friends, Best Food and more. Go tohttp://in.promos.yahoo.com/groups/bestofyahoo/ That's slightly difficult to answer without knowing any context. Do you want to know if the other end has closed the connection? Assuming that's the case and you're just using the standard socket library, it's largely the same as it would be should you do it in C. A TCP socket with a closed peer will select as 'ready' for read. When you attempt to read that socket, you'll have a 0 length return. If you attempt to write to a socket that's been closed by the other end, you ought to receive a "Broken pipe' socket error. If you attempt to write to a socket that *you've* already closed, then you should just get a standard 'Bad file descriptor' socket.error. Google's your friend with topics like this. There's a lot out there pertaining to the standard POSIX socket calls. From vlastimil.brom at gmail.com Sun Jun 8 15:37:04 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sun, 8 Jun 2008 21:37:04 +0200 Subject: Need help porting Perl function In-Reply-To: References: Message-ID: <9fdb569a0806081237r1c564c82va52bbfc8202cf862@mail.gmail.com> 2008/6/7, kj : > > > > ... The original Perl function takes a reference to an array, removes > from this array all the elements that satisfy a particular criterion, > > and returns the list consisting of the removed elements. ... > > > > Just out of curiosity, as I didn't find any mention of filter() in the suggestions in this thread, I'd like to ask, whether there are some reasons, why not to use it (or the itertools equivalent); actually it seems to me to be the simplest way to acomplish the mentioned task (as the solutions not modifying the original list were proposed too). e.g.: >>> lst=range(14) >>> odd = filter(lambda x: x % 2, lst) >>> even = filter(lambda x: not x % 2, lst) >>> lst, odd, even (or a version using itertools.ifilter, ifilterfalse) Are there maybe some significant performance disadvantages in the two subsequent implied loops over the input list? Regards, Vlastimil Brom -------------- next part -------------- An HTML attachment was scrubbed... URL: From jphalip at gmail.com Sun Jun 29 09:39:17 2008 From: jphalip at gmail.com (Julien) Date: Sun, 29 Jun 2008 06:39:17 -0700 (PDT) Subject: Unnormalizing normalized path in Windows Message-ID: <2fd61534-2370-452c-8ca2-269ee01ed8e7@r37g2000prm.googlegroups.com> Hi, In Windows, when a path has been normalized with os.path.normpath, you get something like this: C:/temp/my_dir/bla.txt # With forward slashes instead or backward slashes. Is it possible to revert that? >>> magic_function('C:/temp/my_dir/bla.txt') 'C:\temp\my_dir\bla.txt' I wonder if there's a standard function to do that... Thanks a lot! Julien From n.emami at gmail.com Thu Jun 12 08:15:28 2008 From: n.emami at gmail.com (Nader) Date: Thu, 12 Jun 2008 05:15:28 -0700 (PDT) Subject: get keys with the same values References: <7334507d-24e7-43f9-baa3-4e9e87eb20fa@w7g2000hsa.googlegroups.com> Message-ID: On Jun 12, 2:05 pm, Chris wrote: > On Jun 12, 1:48 pm, Nader wrote: > > > > > On Jun 12, 1:35 pm, bearophileH... at lycos.com wrote: > > > > Nader: > > > > > d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} > > > > I will something as : > > > > d.keys(where their values are the same) > > > > That's magic. > > > > > With this statement I can get two lists for this example: > > > > l1= ['a','e'] > > > > l2=['b','d'] > > > > Would somebody tell me how I can do it? > > > > You can create a new dict where the keys are the values of the input > > > dict and the values are a list of the keys of the original dict. So > > > scanning the keys, values of the input dict, you can fill the second > > > dict. Then you can scan the second dict, and create a list that > > > contains only value lists longer than one. > > > > Bye, > > > bearophile > > > Is it niet possible with one or two statement, maybe with list > > comprehension. For exmple: > > > l = [(k,v) for k in d.keys() for v in d.values() | en here we need > > some extra logic (v = 1)] > > > I don;t konw how we can define a logic statement in a list > > comprehension. > > It will be very compact, if it would possible. > > > Nader > > If you are going to use this reverse look-up alot you'd be better off > building another dictionary with the original values being keys and > the original keys being values, if it is used infrequently enough you > can search for it with result_list = [k for k,v in dictionary.items() > if v == search_value] Thank you! It is the anwser which I was looking for. [(k,v) for k,v in d.items() if v is pattern]. But I don't understand what tou mean of "reverse look-up a lot"! I have to read some informations inclusive (latitudes and longitudes) form a file and after some processing to save part of this information to other file. Why do I make a new dictionary? Nader From tamim.shahriar at gmail.com Mon Jun 9 14:07:38 2008 From: tamim.shahriar at gmail.com (subeen) Date: Mon, 9 Jun 2008 11:07:38 -0700 (PDT) Subject: Web Crawler - Python or Perl? References: Message-ID: On Jun 9, 11:48 pm, disappeare... at gmail.com wrote: > Hi all, > I am currently planning to write my own web crawler. I know Python but > not Perl, and I am interested in knowing which of these two are a > better choice given the following scenario: > > 1) I/O issues: my biggest constraint in terms of resource will be > bandwidth throttle neck. > 2) Efficiency issues: The crawlers have to be fast, robust and as > "memory efficient" as possible. I am running all of my crawlers on > cheap pcs with about 500 mb RAM and P3 to P4 processors > 3) Compatibility issues: Most of these crawlers will run on Unix > (FreeBSD), so there should exist a pretty good compiler that can > optimize my code these under the environments. > > What are your opinions? It really doesn't matter whether you use Perl or Python for writing web crawlers. I have used both for writing crawlers. The scenarios you mentioned (I/O issues, Efficiency, Compatibility) don't differ two much for these two languages. Both the languages have fast I/O. You can use urllib2 module and/or beautiful soup for developing crawler in Python. For Perl you can use Mechanize or LWP modules. Both languages have good support for regular expressions. Perl is slightly faster I have heard, though I don't find the difference myself. Both are compatible with *nix. For writing a good crawler, language is not important, it's the technology which is important. regards, Subeen. http://love-python.blogspot.com/ From daveparker at flamingthunder.com Sat Jun 28 13:47:19 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Sat, 28 Jun 2008 10:47:19 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <4847ecf6$0$25178$c3e8da3@news.astraweb.com> Message-ID: <950ba374-e753-40d3-840a-d353ade785d4@a9g2000prl.googlegroups.com> On Jun 7, 10:24 am, Sam Denton wrote: > I've long believed that '=' should be banned from programming languages. > Use '==' for equality tests, and ':=' for assignments. That's an interesting suggestion that I don't recall hearing anyone else ever mention. On Jun 7, 10:24?am, Sam Denton wrote: > John Salerno wrote: > > "Dave Parker" wrote in message > >news:a95c09d9-94c3-4dac-9439-9176038d93d9 at w8g2000prd.googlegroups.com... > > On May 20, 7:05 pm, Collin wrote: > > > --- > > For example, consider the two statements: > > > ? ? ?x = 8 > > ? ? ?x = 10 > > > The reaction from most math teachers (and kids) was "one of those is > > wrong because x can't equal 2 different things at the same time". > > --- > > > Aw, come on. I'm a novice programmer but even after reading the most basic > > of introductions to a programming language I can tell that x is being > > assigned one value, then another. > > I've long believed that '=' should be banned from programming languages. > ? Use '==' for equality tests, and ':=' for assignments.- Hide quoted text - > > - Show quoted text - From exarkun at divmod.com Wed Jun 11 10:13:50 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 11 Jun 2008 10:13:50 -0400 Subject: Producer-consumer threading problem In-Reply-To: Message-ID: <20080611141350.4714.1433994826.divmod.quotient.8137@ohm> On Tue, 10 Jun 2008 22:46:37 -0700 (PDT), George Sakkis wrote: >On Jun 10, 11:47 pm, Larry Bates wrote: >> >> I had a little trouble understanding what exact problem it is that you are >> trying to solve but I'm pretty sure that you can do it with one of two methods: > >Ok, let me try again with a different example: I want to do what can >be easily done with 2.5 Queues using Queue.task_done()/Queue.join() >(see example at http://docs.python.org/lib/QueueObjects.html), but >instead of having to first put all items and then wait until all are >done, get each item as soon as it is done. > >> 1) Write the producer as a generator using yield method that yields a result >> every time it is called (something like os.walk does). I guess you could yield >> None if there wasn't anything to consume to prevent blocking. > >Actually the way items are generated is not part of the problem; it >can be abstracted away as an arbitrary iterable input. As with all >iterables, "there are no more items" is communicated simply by a >StopIteration. > >> 2) Usw somethink like Twisted insted that uses callbacks instead to handle >> multiple asynchronous calls to produce. You could have callbacks that don't do >> anything if there is nothing to consume (sort of null objects I guess). > >Twisted is interesting and very powerful but requires a different way >of thinking about the problem and designing a solution. More to the >point, callbacks often provide a less flexible and simple API than an >iterator that yields results (consumed items). For example, say that >you want to store the results to a dictionary. Using callbacks, you >would have to explicitly synchronize each access to the dictionary >since they may fire independently. This isn't true. Access is synchronized automatically by virtue of the fact that there is no pre-emptive multithreading in operation. This is one of the many advantages of avoiding threads. :) There may be valid arguments against callbacks, but this isn't one of them. Jean-Paul From cslush at gmail.com Fri Jun 27 18:47:16 2008 From: cslush at gmail.com (sleek) Date: Fri, 27 Jun 2008 15:47:16 -0700 (PDT) Subject: Embedded Python Import problem Message-ID: I am having trouble with the following code: PyObject *module = PyImport_ImportModule(modulename); if (module == NULL) { PyObject* et, *ev, *etr; PyErr_Fetch(&et, &ev, &etr); PyObject* traceback = PyImport_ImportModule("traceback"); PyObject* tb = PyObject_CallMethodObjArgs(traceback, PyString_FromString("format_exception"), et, ev, etr, NULL); char *message = PyString_AsString(PyObject_Str(tb)); ... ... } When this code executes, it gets into the "module == NULL" condition. However, when I try to get the exception that occurred, I get the value "" copied into the "char* message" variable. Can anyone shed some light on what might cause this to happen? I thought that if I actually get into that NULL condition that an exception has occurred. From ironfroggy at socialserve.com Mon Jun 16 12:36:08 2008 From: ironfroggy at socialserve.com (Calvin Spealman) Date: Mon, 16 Jun 2008 12:36:08 -0400 Subject: 'string'.strip(chars)-like function that removes from the middle? In-Reply-To: <48569B9E.6030206@admailinc.com> References: <48569B9E.6030206@admailinc.com> Message-ID: <7E4F274D-2139-441D-B641-497B885C6227@socialserve.com> On Jun 16, 2008, at 12:58 PM, Ethan Furman wrote: > Greetings. > > The strip() method of strings works from both ends towards the middle. > Is there a simple, built-in way to remove several characters from a > string no matter their location? (besides .replace() ;) > > For example: > .strip --> 'www.example.com'.strip('cmowz.') > 'example' > .??? --> --- 'www.example.com'.strip('cmowz.') > 'exaple' >>> re.sub('|'.join('cmowz.'), "www.example.com") '.exaple.' > -- > Ethan > > -- > http://mail.python.org/mailman/listinfo/python-list From e.yunak at gmail.com Sat Jun 21 10:29:50 2008 From: e.yunak at gmail.com (Val-Amart) Date: Sat, 21 Jun 2008 07:29:50 -0700 (PDT) Subject: Fast and easy GUI prototyping with Python References: <9c349bf0-ef63-4463-bd4e-cdbe331b58c3@z66g2000hsc.googlegroups.com> Message-ID: On 21 ???, 15:36, ero... at gmail.com wrote: > Which tools would you use? I want the interface design to be as easy > and fast as possible, all ideology aside. I'm considering either > IronPython+Visual Studio or Python+Qt -- but I'm open for other > suggestions. > > Visual Studio seems to offer the easiest solution, but is IronPython > stable enough? How easy is the IronPython/Visual Studi integration? > What about IronPython Studio? Use PyQt. You will gain great portability +all the functionality built in qt. You can try PyGTK also, though i wont recommend it. From aahz at pythoncraft.com Wed Jun 11 15:35:00 2008 From: aahz at pythoncraft.com (Aahz) Date: 11 Jun 2008 12:35:00 -0700 Subject: Producer-consumer threading problem References: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> Message-ID: In article <1f8adb7a-1257-4a56-b69a-557115c60050 at k37g2000hsf.googlegroups.com>, George Sakkis wrote: > >I'd like some feedback on a solution to a variant of the producer- >consumer problem. My first few attempts turned out to deadlock >occasionally; this one seems to be deadlock-free so far but I can't >tell if it's provably correct, and if so, whether it can be >simplified. Take a look at the threading tutorial on my web page, specifically the threadpool spider. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From eckhardt at satorlaser.com Wed Jun 4 03:48:01 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 04 Jun 2008 09:48:01 +0200 Subject: Best way to modify code without breaking stuff. References: Message-ID: Jesse Aldridge wrote: > I've got a module that I use regularly. I want to make some extensive > changes to this module but I want all of the programs that depend on > the module to keep working while I'm making my changes. What's the > best way to accomplish this? You simply run the module's unit tests that tell you if the new module's behaviour differs from the expectations. If you don't have unit tests, I'd say it's about time writing them. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From bruno.42.desthuilliers at websiteburo.invalid Fri Jun 6 11:25:04 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 06 Jun 2008 17:25:04 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <4847d39d$0$7614$426a74cc@news.free.fr> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> Message-ID: <48495693$0$26543$426a74cc@news.free.fr> Russ P. a ?crit : > On Jun 5, 4:53 am, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> Russ P. a ?crit : > >> Given your very recent discovery of what 'dynamic' *really* means in >> Python (like, for exemple, dynamically adding / replacing attributes - >> including methods - on a per-class or per-instance basis), possibly, yes. > > My "very recent" discovery? Funny, I thought I knew that several years > ago. Looks like I mistook your """ I also realize, by the way, that Python allows a client of a class to define a new class member from completely outside the class definition """ as "I just realized (...)" Sorry for having read too fast. >>> I also realize, by the way, that Python allows a client of a class to >>> define a new class member from completely outside the class >>> definition. Obviously, that cannot be declared private. >> Why so ? > > Why should the client of a class not be able to declare a *private* > member of the class? You're kidding, right? I'm dead serious. I often add implementation attributes to either a class or an instance. These *are* implementation parts, not API. > Do you mind if I tell you > how to arrange the furniture in your bedroom? I must be a bit dumb, but I don't see how human interaction problems relate to enforced access restriction in an OO programming language. >>> But if the >>> same identifier is already declared private within the class, than the >>> new definition should not be allowed (because it would defeat the >>> whole idea of "private" class members). >> Why so ? >> >> Metaprogramming (including monkeypatching) is part of the pythoneer's >> toolbox, and while it's not something to use without pretty good >> reasons, it has many times proven to be a real life saver. In languages >> not allowing it, the solutions to the class of problems easily solved by >> monkeypatching happens to be at best a kludge, at worst plain >> unsolvable, at least without too much effort to be even worth it. Your >> above proposition would arbitrarily make possible and useful things >> either uselessly complicated or near impossible. > > For the record, I have made it abundantly clear that I don't think > Python should not have as rigorous an encapsulation regime as C++ or > Java. The worst that could happen with my proposition is that you > would need to use a "mangled" name to access private data or methods. That's already the case - when you use __name_mangling. And if there's no effective access restriction, then what the point of having this 'priv' keyword ? > But you will be using the name many times, you can reassign your own > name, of course, so the mangled name need not appear more than once > where it is needed. Once again, I just don't see the point. Either you want effective access restriction in Python, or you don't. And if you don't, what would this 'priv' keyword be useful to ? From space.captain.face at gmail.com Sat Jun 7 10:14:53 2008 From: space.captain.face at gmail.com (Kalibr) Date: Sat, 7 Jun 2008 07:14:53 -0700 (PDT) Subject: Dynamically naming objects. References: <8a99c3fa-1eeb-49b3-a714-b6063ec1daab@d19g2000prm.googlegroups.com> <3d2a85b2-255d-4e93-8cfb-e2772f57b69a@u6g2000prc.googlegroups.com> Message-ID: Thanks for all this info. I'll try all your scripts out. from what you guys have said, I did the following: I set up a 'computer class' (I'lm leaving out the mutators) class computer: def __init__(self, IP, owner, ph_connections, connections): assert isIP(IP) == True self.IP = IP self.owner = owner for i in ph_connections: assert isIP(i) == True self.ph_connections = ph_connections for i in connections: assert isIP(i) == True self.connections = connections isIP(IP) is a function that checks if it looks like an IP based on some rules. Anyway.... I set up a list of users, each with their computer object named after them, so: users = ['Kal', 'Noob', 'Fred'] I ran through them with some code based vaguely on what you guys have said: for i in users: i = computer('', i, [], []) I set up the ph_connections and connections lists as empty for ease of use. Does this code seem right? I can't get it to work. From Gilles at Mon Jun 2 14:42:16 2008 From: Gilles at (nospam@nospam.com) Date: Mon, 02 Jun 2008 20:42:16 +0200 Subject: [Re] Checking each item in m.group()? Message-ID: Hello I need to go through each line of a CSV file, and extract some fields using a regex. Then, I need to check each retrieved field, and if it looks like "", turn this into NULL so that it's correct SQL. I tried a few things, but still can't it working: ======== #Second field might be empty -> "" #"Col1","" #"Col1","Col2" p = re.compile('^"(.+?)","(.*?)"$') for line in textlines: m = p.search(line) if m: #Check each column : if '', then turn into NULL """ for col in line: if col == "": col = "NULL" """ """ for col in m.group(): if col == "": col="NULL" """ """ for col in m.group(0): if col == "": col="NULL" """ """ for i in range (0,len(line)): if line[i] == "": line[i]="NULL" """ """ for i in range(1,len(m.group(0))): if m.group(i) == "": m.group(i)="NULL" """ sql = "INSERT INTO mytable (col1, col2) VALUES ('%s','%s')" % (m.group(1),m.group(2)) print sql f.close() ======== Does someone know the correct syntax? Thank you. From soltys at noabuse.com Fri Jun 20 04:20:13 2008 From: soltys at noabuse.com (Soltys) Date: Fri, 20 Jun 2008 10:20:13 +0200 Subject: Regular expression In-Reply-To: References: <42396af0-29aa-45ea-8588-186b0ccbab58@z16g2000prn.googlegroups.com> Message-ID: Duncan Booth pisze: > Sallu wrote: >> string = 'rich?' > ... >> unicode(string)).encode('ASCII', 'ignore') > ... >> Output : >> >> sys:1: DeprecationWarning: Non-ASCII character '\xc3' in file regu.py >> on line 4, but no encoding declared; see >> http://www.python.org/peps/pep-0263.html for details >> rich? >> Traceback (most recent call last): >> File "regu.py", line 13, in ? >> msg=strip_accents(string) >> File "regu.py", line 10, in strip_accents >> return unicodedata.normalize('NFKD', >> unicode(string)).encode('ASCII', 'ignore') >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position >> 4: ordinal not in range(128) >> >> > The problem is the expression: unicode(string) which is equivalent to > saying string.decode('ascii') > > The string contains a non-ascii character so the decode fails. You should > specify whatever encoding you used for the source file. From the error > message it looks like you used utf-8, so "string.decode('utf-8')" should > give you a unicode string to work with. > > Or just specify source encoding like that: #!/usr/bin/python # -*- coding: utf-8 -*- or #!/usr/bin/python # coding=utf-8 -- Soltys "Free software is a matter of liberty not price" From seandavi at gmail.com Wed Jun 11 17:20:52 2008 From: seandavi at gmail.com (Sean Davis) Date: Wed, 11 Jun 2008 14:20:52 -0700 (PDT) Subject: Numpy array to gzip file References: <404de0ba-edd5-47ff-8b25-132aa0b5b570@c58g2000hsc.googlegroups.com> Message-ID: On Jun 11, 12:42 pm, "drobi... at gmail.com" wrote: > On Jun 11, 9:17 am, Sean Davis wrote: > > > > > I have a set of numpy arrays which I would like to save to a gzip > > file. Here is an example without gzip: > > > b=numpy.ones(1000000,dtype=numpy.uint8) > > a=numpy.zeros(1000000,dtype=numpy.uint8) > > fd = file('test.dat','wb') > > a.tofile(fd) > > b.tofile(fd) > > fd.close() > > > This works fine. However, this does not: > > > fd = gzip.open('test.dat','wb') > > a.tofile(fd) > > > Traceback (most recent call last): > > File "", line 1, in > > IOError: first argument must be a string or open file > > > In the bigger picture, I want to be able to write multiple numpy > > arrays with some metadata to a binary file for very fast reading, and > > these arrays are pretty compressible (strings of small integers), so I > > can probably benefit in speed and file size by gzipping. > > > Thanks, > > Sean > > Use > fd.write(a) That seems to work fine. Just to add to the answer a bit, one can then use: b=numpy.frombuffer(fd.read(),dtype=numpy.uint8) to get the array back as a numpy uint8 array. Thanks for the help. Sean From duncan.booth at invalid.invalid Fri Jun 20 08:07:18 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Jun 2008 12:07:18 GMT Subject: Simple Python class questions References: Message-ID: John Dann wrote: > Yes I was wondering about that, but I wasn't clear about when 'body' > code (ie not contained within a def block) in the module might run > under Python. So it seemed to be safer to place the import statement > inside the 'constructor' to get the earliest warning of non-visibility > of pyserial. But you seem to be implying that the body code will run > when the class is instantiated - have I understood that right? It > surely doesn't run when the module containing the class is imported > into the main module - does it?? It would certainly make life easier > to place the import in the body of the module. Python starts executing at the top of your main script and then proceeds line by line down until it falls off the bottom. Various things can divert it from this straightforward progression towards the end of the script, some of them such as if/for/while/raise or function calls are obvious, but the less obvious ones include: import somemodule (or 'from somemodule import something') if 'somemodule' has not previously been imported this will find the module and execute the lines of code in the module from top to bottom just as for the main script. When it falls off the bottom of the module it returns to the import statement, assigns the module or the imported attributes to a name or names in the calling namespace (yes, an import is just a highly specialised assignment statement), and then continues with the next statement. If somemodule has already started being imported anywhere in the program then the import simply returns immediately and does the assignment. (This can be a cause of confusion if you try to import modules recursively as it is perfectly possible that the imported module has not yet finished executing, so it may not yet have all the classes and functions you expect). class somename(bases): somecode A 'class' statement in Python is just executable code. The body of the class is executed from top to bottom but in a new namespace. When execution falls off the bottom of the class body a new class object is created from that namespace and the base classes. The new class object is then assigned to 'somename' (i.e. a class statement is a specialised assignment statement). Then execution then procedes with the next statement. def functionname(arg1, arg2=default): somecode A 'def' statement in Python is also a specialised assignment statement: unlike 'class' it doesn't immediately execute the code in the body, but it does evaluate any default argument values when it encounters the 'def'. Then it creates a new function object from the code in the body and the default arguments (and a few other things such as the argument specification and the function name). Then it continues with the next statement. global name The 'global' statement is not executed at runtime. It is the only Python statement which is purely compile time. Once you understand this it should be much clearer: everything except global is executed when it is encountered following the normal rules for program flow, and all the ways of creating module, classes, and functions simply execute some code and then do an assignment (and so if you wish you can later overwrite the values they assigned). If you wish to do something special when an import fails then you simply put try:..except: around the import at the top level in a module and handle it there: you don't need to put either the import or the handler inside a function. -- Duncan Booth http://kupuguy.blogspot.com From nick at craig-wood.com Mon Jun 2 12:30:22 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 02 Jun 2008 11:30:22 -0500 Subject: ctypes, function pointers and a lot of trouble References: Message-ID: Matt wrote: > class MemStreamData(Structure): > _fields_ = [("mode", c_byte), > ("lPos", c_uint), > ("dwVisibleSize", c_uint), > ("dwBufferSize", c_uint), > ("cpBuffer", POINTER(c_char))] > > class FilStreamData (Structure): > _fields_ = [("szFileName", c_char * 30), > ("hFile", c_uint)] > > > > and the code to fill all that with the right data is the following: > > > datainfo = cdReleaseImageInfo() > > databuf = c_char * 100000 > cbuffer=MemStreamData() > cbuffer.mode = c_byte(0) > cbuffer.lPos = c_uint(0) > cbuffer.dwVisibleSize = c_uint(100000) > cbuffer.dwBufferSize = c_uint(100000) > > #this line does not work, wrong datatype!? > cbuffer.cpBuffer = POINTER(databuf) [snip] > Does anyone see where the errors are? databuf = c_char * 100000 Is a type not an instance... You need to instantiate it, eg >>> from ctypes import * >>> class MemStreamData(Structure): ... _fields_ = [("cpBuffer", POINTER(c_char))] ... >>> cbuffer=MemStreamData() >>> databuf = c_char * 100000 >>> cbuffer.cpBuffer = POINTER(databuf) Traceback (most recent call last): File "", line 1, in TypeError: expected LP_c_char instance, got _ctypes.PointerType >>> databuftype = c_char * 100000 >>> databuf = databuftype() >>> cbuffer.cpBuffer = databuf >>> databuf <__main__.c_char_Array_100000 object at 0xb7d04dac> There is a shorthand for exactly this though as it is a common operation >>> databuf = create_string_buffer(1000) >>> cbuffer.cpBuffer = databuf >>> databuf -- Nick Craig-Wood -- http://www.craig-wood.com/nick From tjreedy at udel.edu Wed Jun 18 01:32:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 18 Jun 2008 01:32:28 -0400 Subject: Does '!=' equivelent to 'is not' In-Reply-To: References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> <20080617120941.GE7349@dragontoe.org> Message-ID: >> Saying a flat "no" alone, without qualifying your statement is >> generally interpreted as rude in English... It's kind of like how you >> talk to children when they're too young to understand the explanation. >> Yucky. > > I didn't meant to be rude at all - and I apologize to Mr. Lie. The > explanation for such strong "No" was in the paragraph below it (the idea > was to say: "No to this, yes to that") As a very much native English speaker I disagree that 'No' is necessarily rude. I wish I could more often get such a clean answer to my questions from my child. From floydophone at gmail.com Tue Jun 10 11:06:29 2008 From: floydophone at gmail.com (Peter Hunt) Date: Tue, 10 Jun 2008 08:06:29 -0700 (PDT) Subject: Dumb idea? Message-ID: Hi everyone - I like playing around with language syntax and semantics. I'm thinking about pulling down the PyPy code and messing around to see what I can accomplish. My first idea is most succinctly described by example: class IBlockProtocol: def __block__(self, func): # NO RETURN VALUES! pass # my_IBlockProtocol is an expression that evaluates to an implementor of IBlockProtocol my_IBlockProtocol: expr # becomes: my_IBlockProtocol.__block__(lambda: expr) ### my_IBlockProtocol: expr # becomes: my_IBlockProtocol.__block__(lambda param1, paramN: expr) ### my_IBlockProtocol: stmt1 stmt2 # becomes: def anon(): stmt1 stmt2 my_IBlockProtocol.__block__(anon) ### my_IBlockProtocol: stmt1 stmt2 # becomes: def anon(param1, paramN): stmt1 stmt2 my_IBlockProtocol.__block__(anon) ############### Has this already been done? Is it a stupid idea? I think it could be used to simplify event handling and some Twisted stuff. I'm mainly looking for reasons why I _wouldn't_ want to take the time to get my hands dirty with the PyPy code (or even CPython) and try to implement this syntax. Thanks. Pete From gh at ghaering.de Thu Jun 26 07:31:40 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 26 Jun 2008 13:31:40 +0200 Subject: extend getattr() In-Reply-To: <0d1da457-b026-4e38-824b-c8cbde172bf7@m36g2000hse.googlegroups.com> References: <0d1da457-b026-4e38-824b-c8cbde172bf7@m36g2000hse.googlegroups.com> Message-ID: Rotlaus wrote: > Hello, > > lets assume i have some classes: > [...] > > a=A() > c=getattr(a, 'b.c') > > I know this doesn't work, but what can i do to get this or a similar > functionality to get it work for this sample and for even more nested > classes? Just recursively apply the getattr(), like this: class A(object): def __init__(self): self.b = B() class B(object): def __init__(self): self.c = C() class C(object): def __init__(self): pass def ext_getattr(obj, attr): for subattr in attr.split("."): obj = getattr(obj, subattr) return obj a=A() c = ext_getattr(a, 'b.c') -- Gerhard From news at prodata.co.uk Thu Jun 19 09:13:39 2008 From: news at prodata.co.uk (John Dann) Date: Thu, 19 Jun 2008 14:13:39 +0100 Subject: Simple Python class questions References: Message-ID: Many thanks for the speedy replies. On Thu, 19 Jun 2008 14:14:02 +0200, C?dric Lucantis wrote: >Le Thursday 19 June 2008 13:54:03 John Dann, vous avez ?crit?: >> Let's say I define the class in a module called comms.py. The class >> isn't really going to inherit from any other class (except presumably >> in the most primitive base-class sense, which is presumably automatic >> and implicit in using the class keyword). > >No it's not :) It is recommended to always use new-style classes, and thus to >give the object base explicitely : > >class serial_link (object) : > ... Can I just confirm: between the parentheses should be the literal 'object' - ie (object) - you're not just using 'object' as a placeholder where there should be a more specific class name or object? -------------- On Thu, 19 Jun 2008 14:21:46 +0200, Ulrich Eckhardt wrote: >Stop, this can't work. Other than VB, Python actually is case sensitive, so >you must write 'try' and not 'Try' and also 'import' and not 'Import'. >Further, many (all?) statements that cause an indention are usually >terminated with a colon, so like with 'class ..:' and 'def ..:' you also >must use 'try:' and not just 'try'. Fix all these and try again, I guess >this will already help a lot. Sorry - the original code was syntactically correct - I just re-keyed it rather quickly for the original newsgroup post here, rather than copy/paste a larger chunk. I'll try to be more careful with any future posts. >One more thing: you are abusing exceptions. Typically, in such a short >program you only have one try-except pair in the main entry function and >all other code only throws the exceptions. In particular the __init__ >function of a class should always signal errors using exceptions. However, >this is not a strict yes/no question but rather a stylistic one. Thanks - I need to think more clearly about the best way of doing this. JGD From bruno.desthuilliers at gmail.com Sat Jun 14 16:17:43 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sat, 14 Jun 2008 13:17:43 -0700 (PDT) Subject: Comments on my first script? References: <7e3a7c92-6204-46dd-8df8-90218f2fb314@26g2000hsk.googlegroups.com> <48522d35$0$10417$426a74cc@news.free.fr> <2c362bb8-7b56-4c41-b8a9-0b36b4f51203@q27g2000prf.googlegroups.com> Message-ID: On 13 juin, 17:24, Lie wrote: > On Jun 13, 3:19 pm, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: > > Phillip B Oldham a ?crit : > (snip) > > > try: > > > for line in rec.split("\n"): > > > bits = line.split(': ') > > > a = bits.pop(0) > > > b = bits.pop(0) > > > if you expect only one ': ', then: > > a, b = line.split(': ') > > > if you can have many but don't care about the others: > > bits = line.split(': ') > > a, b = bits[0], bits[1] > > or: > a, b = line.split(': ')[:1] > ValueError: need more than 1 value to unpack You probably meant: a, b = line.split(': ')[:2] From nir1408 at gmail.com Fri Jun 6 23:35:40 2008 From: nir1408 at gmail.com (Nir) Date: Fri, 6 Jun 2008 20:35:40 -0700 (PDT) Subject: Cannot use Winpdb (or PyDev) to trace embedded Python script in MSVC++ application - ImportError: No module named _socket References: <8a739206-1f72-47ee-8a9f-50ec2c91bde2@j33g2000pri.googlegroups.com> <82989ee9-f9ce-4a88-84b8-c5a0fa2e784e@t12g2000prg.googlegroups.com> <12599118-73c9-45af-94fc-5a791713445d@v1g2000pra.googlegroups.com> Message-ID: <11bfa01e-16d5-4bfb-8bbf-80d66742f3eb@p39g2000prm.googlegroups.com> Can you check another hypothesis? I currently do not have a Python installation to verify this but if my memory does not fail me there is a DLL library somewhere under c: \python25 and _socket might be there as well. Copy any DLLs you find there to the same folder as your embedded interpreter DLL and see if the problem is resolved. Nir On Jun 6, 11:25 am, Chris8B... at gmail.com wrote: > On Jun 6, 1:13 am, Nir wrote: > > > > > You seem to be having a problem with the import path of the embedded > > interpreter. I suppose the embedded interpreter includes some modules > > in a particular folder and _socket is not one of them. For the sake of > > debugging try adding the c:\python25\lib path to the sys.path variable > > of the interpreter before attempting to import rpdb2. > > > Does this work? > > > Nir > > > On Jun 5, 2:52 pm, Chris8B... at gmail.com wrote: > > > > I am embedding Python in a MSVC++ (2005) application. The application > > > creates some environment and then launches a Python script that will > > > call some functions exported from the MSVC++ application. > > > > I want to be able to debug the Python script by using a debug server, > > > likeWinpdb(winpdb.org). > > > > I use ActivePython 2.5.2.2, Microsoft Visual Studio 2005, andWinpdb > > > 1.3.8. > > > > When I launch a script like "e:>python test.py" everything is O'K and > > > I can useWinpdbto trace/debug. > > > > When I run the same script from the MSVC++ application, there is > > > always a complain "ImportError: No module named _socket". > > > > Here is the basic test script I use: > > > > def Process( something ): > > > print "\n\nStarted debugging\n=================\n" > > > #pydevd.settrace() > > > import rpdb2; rpdb2.start_embedded_debugger("1") > > > print "\n\nStopped debugging\n=================\n" > > > > if __name__ == '__main__': > > > Process( "test" ) > > > <<< > > > > In the MSVC++ application I tried many approaches, as suggested by > > > many people, and all of them work to launch the script, but none of > > > them works withWinpdb(or PyDev for Eclipse - same problem). Just for > > > completeness - here is one: > > > > PyRun_SimpleString("import sys"); > > > PyRun_SimpleString("import os"); > > > PyRun_SimpleString( "fullpath = os.path.abspath(\"E:/Test.py\")" ); > > > PyRun_SimpleString( "g = globals().copy()" ); > > > PyRun_SimpleString( "g['__file__'] = fullpath"); > > > PyRun_SimpleString( "execfile(fullpath, g) "); > > > <<< > > > > If I use pdb (import pdb + pdb.runcall(something) ) everything works > > > fine, but I need the performance and convinience ofWinpdb. > > > > What am I doing wrong? > > > > Your help is highly appreciated! > > > > Best regards, > > > Chris > > Nir, > > > Does this work? > > Unfortunately, not. > > I did some experiments to check the sys.path hypothesis: > > - In my MSVC++ application I did PyRun_SimpleString("import cgi"); - > it complained about missing _socket. > > - Did PyRun_SimpleString("print sys.path") to get the sys.path as seen > from within the application environment (that does not find _socket) > > - Did the same in "test.py" and ran ...>Python test.py to get the > sys.path for the environment that _does_ find _socket > > - Compared the two - the working environment had two more paths: > > C:\\WINDOWS\\system32\\python25.zip > C:\\Python25\\lib\\plat-win > > - Added the missing path to the embedded environment: > > PyRun_SimpleString("import sys"); > PyRun_SimpleString("import os"); > > PyRun_SimpleString("sys.path.append(\"C:\\WINDOWS\\system32\ > \python25.zip\")"); > PyRun_SimpleString("sys.path.append(\"C:\\Python25\\lib\\plat-win > \")"); > > PyRun_SimpleString("print sys.path"); > > PyRun_SimpleString("import cgi"); > > Not all paths that are in the working environment are present in the > embedded environment, but still there is a problem: > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\Lib\cgi.py", line 40, in > import urllib > File "c:\Python25\lib\urllib.py", line 26, in > import socket > File "c:\Python25\lib\socket.py", line 45, in > import _socket > ImportError: No module named _socket > > Chris From mark.m.mcmahon at gmail.com Wed Jun 4 19:36:54 2008 From: mark.m.mcmahon at gmail.com (Mark) Date: Wed, 4 Jun 2008 16:36:54 -0700 (PDT) Subject: how should i use this function? References: <99ed3c04-bd62-4456-ae12-eca4179005dc@r66g2000hsg.googlegroups.com> <5a09fa94-b3ce-4a13-af42-b9a1e6980900@25g2000hsx.googlegroups.com> <7573acc5-8b66-45ff-8561-e62200b02446@s50g2000hsb.googlegroups.com> Message-ID: <0cc27c08-77ad-4f24-9bed-2e719405a564@34g2000hsf.googlegroups.com> On Jun 4, 6:58 pm, Gandalf wrote: > > > > But I pywin32 use it all the time i havepywinauto > As the author of pywinauto - I can safely say that just because you have and use pywinauto does NOT mean you have pywin32. pywin32 is not needed for pywinauto. (it uses ctypes to access what it needs). You might find that there are more people who can help you at http://clearspace.openqa.org/community/pywinauto/pywinauto_users (though I do not give the best support in the world - so messages have sat there for a while unanswered!) Thanks Mark From maric at aristote.info Mon Jun 23 04:39:48 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 23 Jun 2008 10:39:48 +0200 Subject: An idiom for code generation with exec In-Reply-To: <485f4f35$0$28417$426a74cc@news.free.fr> References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485f4f35$0$28417$426a74cc@news.free.fr> Message-ID: <200806231039.50348.maric@aristote.info> Le Monday 23 June 2008 09:22:29 Bruno Desthuilliers, vous avez ?crit?: > > With some help from the guys at IRC I came to realize your way doesn't > > do the same. It creates a function that, when called, creates 'foo' on > > globals(). This is not exactly what I need. > > I possibly messed up a couple things in the arguments, flags etc - I > very seldom use compile() and function(). The point was that ?it didn't > require any extra step. In the argument list of function type, the code object in first place is expected to be created directly (no exec - eval) with the python type 'code' (either found as types.CodeType or new.code). In [24]: types.CodeType? Type: type Base Class: String Form: Namespace: Interactive Docstring: code(argcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, lnotab[, freevars[, cellvars]]) Create a code object. Not for the faint of heart. ^^^^^^^^^^^^^^^ Even if it looks more "object oriented", I'm not sure it's actually the good solution for the original problem. I think these interface are not a replacement for the quick eval-exec idiom but more intended to make massive code generation programs object oriented and closer to python internals. AFAIK, the only use case I see code generation (eval - exec, playing with code objects) as legitime in python is in programs that actually do code generation, that is, parse and compile code from textual inputs (application buillders). If code generation is not the best, and I fail to see any performance issue that could explain such a choice, except a misunderstanding of what "compilation" means in python, just don't use it, use closures or callable instances, there are many way to achieve this. -- _____________ Maric Michaud From gabriela.soares.fcup at gmail.com Wed Jun 11 11:18:55 2008 From: gabriela.soares.fcup at gmail.com (Gabriela Soares) Date: Wed, 11 Jun 2008 16:18:55 +0100 Subject: [Tutor] python gui In-Reply-To: <333efb450806110818g134b930cj6e36f7bd79a9083@mail.gmail.com> References: <9d68e4e90806110603v7da96761t21445523d07ab6a3@mail.gmail.com> <333efb450806110818g134b930cj6e36f7bd79a9083@mail.gmail.com> Message-ID: <9d68e4e90806110818q18c57bd2v8b3219de9b2a1ca1@mail.gmail.com> How ? Any references ? On Wed, Jun 11, 2008 at 4:18 PM, W W wrote: > On Wed, Jun 11, 2008 at 8:03 AM, Gabriela Soares > wrote: > > Greetings, > > > > I want to make a dynamic dashboard, something like: > > > > http://examples.adobe.com/flex3/labs/dashboard/main.html# > > > > but using python. Is it possible ? > > Yes. > > -Wayne > -- Gabriela Soares "I learned that courage was not the absence of fear, but the triumph over it. The brave man is not he who does not feel afraid, but he who conquers that fear." Nelson Mandela -------------- next part -------------- An HTML attachment was scrubbed... URL: From basti.wiesner at gmx.net Tue Jun 17 13:24:06 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Tue, 17 Jun 2008 19:24:06 +0200 Subject: Context manager for files vs garbage collection References: <74f25d98-a6a5-4034-b3b7-06a8ca40ce04@e39g2000hsf.googlegroups.com> Message-ID: Floris Bruynooghe : > I was wondering when it was worthwil to use context managers for > file. Consider this example: > > def foo(): > t = False > for line in file('/tmp/foo'): > if line.startswith('bar'): > t = True > break > return t Using this code inside a jthon web application might hit the resource limits of the underlying operating system. While CPython has a fairly deterministic garbage collector, the JVM gc is non-deterministic, especially inside the server vm. It keeps objects around for quite a long time and only frees them, if available memory runs low or the application is idle. Since file objects don't consume much memory, they might be hanging around for quite some time still claiming resources, which are a rare thing on many restricted server environments. Relying on garbage collection on Python means relying on a non-portable implementation detail. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From pfreixes at gmail.com Thu Jun 26 07:01:22 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Thu, 26 Jun 2008 13:01:22 +0200 Subject: Threads, GIL and re.match() performance In-Reply-To: References: <25be11e7-157c-4af0-be3a-fa7a6c9c3acc@m3g2000hsc.googlegroups.com> <207312b70806260020j6a4c5d4dt3af0625c27ec3cc2@mail.gmail.com> Message-ID: <207312b70806260401j1b2770d9s8b7cc2b7bd3f3190@mail.gmail.com> Hi Ok, if I understand between Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS is not possible use a C/Python api functions ? Sorry, but when thread enter another time with Py_END_ALLOW_THREADS this thread enter to competition to lock GIL ? Thks Thks On Thu, Jun 26, 2008 at 12:16 PM, Matthieu Brucher < matthieu.brucher at gmail.com> wrote: > Hi, > > The C-API uses references counts as well, so it is not threadsafe. > > Matthieu > > 2008/6/26 Pau Freixes : > > But Python C-API[1] it's the main base for extent python with C/c++, and > > this is not not threadsafe.? I dont understand > > > > [1] http://docs.python.org/api/api.html > > > > On Thu, Jun 26, 2008 at 4:49 AM, Benjamin > > wrote: > >> > >> On Jun 25, 9:05 am, Mirko Dziadzka wrote: > >> > > >> > 1) Is there a reason for this? > >> > >> I think it is because the Python re library uses the Python C-API > >> which is not threadsafe. > >> > 2) Is the regex library not thread-safe? > >> > 3) Is it possible, to release the GIL in re.match() to > >> > get more performance? > >> > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > > > > > > > > -- > > Pau Freixes > > Linux GNU/User > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > French PhD student > Website : http://matthieu-brucher.developpez.com/ > Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 > LinkedIn : http://www.linkedin.com/in/matthieubrucher > -- > http://mail.python.org/mailman/listinfo/python-list > -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From manlio_perilloNO at SPAMlibero.it Sun Jun 29 07:30:59 2008 From: manlio_perilloNO at SPAMlibero.it (Manlio Perillo) Date: Sun, 29 Jun 2008 11:30:59 GMT Subject: problem with internationalized headers in email package Message-ID: Hi. >From RFC 2047: + An 'encoded-word' MUST NOT appear in any portion of an 'addr-spec'. + An 'encoded-word' MUST NOT appear within a 'quoted-string'. + An 'encoded-word' MUST NOT be used in a Received header field. + An 'encoded-word' MUST NOT be used in parameter of a MIME Content-Type or Content-Disposition field, or in any structured field body except within a 'comment' or 'phrase'. However (Python 2.5.2): >>> h = Header(u'Andr? ') >>> h.encode() '=?utf-8?b?QW5kcsOoIDxhbmRyZUBsb2NhbGhvc3Q+?=' I'm not sure if this can be considered a bug, but surely this is an invalid header. Thanks Manlio Perillo From bearophileHUGS at lycos.com Mon Jun 16 19:12:03 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 16 Jun 2008 16:12:03 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> <4856e80c$0$30401$9b622d9e@news.freenet.de> Message-ID: <2d1e9b84-3dc7-4822-9c61-73991a527c67@s50g2000hsb.googlegroups.com> Martin v. L.: > For this API, I think it's important to make some performance guarantees. I may appreciate them for all Python collections :-) > It seems fairly difficult to make byindex O(1), and > simultaneously also make insertion/deletion better than O(n). It may be possible to make both of them O(log n), but I may appreciate byindex O(n) and insertion/deletion O(1). Bye, bearophile From deets at nospam.web.de Tue Jun 10 02:51:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 10 Jun 2008 08:51:00 +0200 Subject: PEP on breaking outer loops with StopIteration In-Reply-To: References: Message-ID: <6b6mimF3a25g4U1@mid.uni-berlin.de> Kris Kowal schrieb: > I had a thought that might be pepworthy. Might we be able to break > outer loops using an iter-instance specific StopIteration type? > > This is the desired, if not desirable, syntax:: > > import string > letters = iter(string.lowercase) > for letter in letters: > for number in range(10): > print letter, number > if letter == 'a' and number == 5: > raise StopIteration() > if letter == 'b' and number == 5: > raise letters.StopIteration() > > The first StopIteration would halt the inner loop. The second > StopIteration would halt the outer loop. The inner for-loop would > note that the letters.StopIteration instance is specifically targeted > at another iteration and raise it back up. For the record: I share GvR's opinion on the general usefulness. Additionally, your syntax is impossible. There isn't always a containing variable for the iterable. And if you meant "letter", it's ambigous. It is perfectly legal in python to do this: class Foo(object): StopIteration = StopIteration for letter in [Foo(), Foo()]: for number in range(10): raise letter.StopIteration Diez From wmcbrine at users.sf.net Thu Jun 12 04:04:52 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Thu, 12 Jun 2008 08:04:52 GMT Subject: Converting a simple python script to a simple windows executable References: Message-ID: On Wed, 11 Jun 2008 12:25:29 -0700, geoffbache wrote: > (1) py2exe. This is really for when python isn't installed on the remote > user's machine, so it requires you to distribute a large amount of DLLs > etc which are part of the python installation. A bit silly when I know > that the remote user has python anyway. If you know the target user has Python installed, why don't you just distribute the .pyw file? (Use ".pyw" instead of ".py" to avoid the extra console window.) -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From ggpolo at gmail.com Fri Jun 20 12:41:35 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Fri, 20 Jun 2008 13:41:35 -0300 Subject: Tkinter canvas drag/drop obstacle In-Reply-To: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> References: <07udnXjTKIU4S8bVnZ2dnUVZ_jSdnZ2d@supernews.com> Message-ID: On Fri, Jun 20, 2008 at 1:11 PM, Peter Pearson wrote: > Tkinter makes it very easy to drag jpeg images around on a > canvas, but I would like to have a "target" change color when > the cursor dragging an image passes over it. I seem to be > blocked by the fact that the callbacks that might tell the > target that the mouse has entered it (, , > even ) aren't called if the mouse's button is down. > What am I missing? Have I failed to find the right Tkinter > document? Is Tkinter the wrong tool for this job? Thanks. > I believe the only way to achieve this is binding to the entire canvas, then checking if the x, y coords are inside the "target". > -- > To email me, substitute nowhere->spamcop, invalid->net. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From danielpaul.simon at gmail.com Mon Jun 16 07:33:40 2008 From: danielpaul.simon at gmail.com (Dantheman) Date: Mon, 16 Jun 2008 04:33:40 -0700 (PDT) Subject: SPAM References: <09d39508-f2b3-49c8-9c11-255b5151396e@h1g2000prh.googlegroups.com> Message-ID: <07d7f769-1cc4-4357-8fb2-12ab9c082fa3@d77g2000hsb.googlegroups.com> SPAM From __peter__ at web.de Mon Jun 9 03:48:03 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Jun 2008 09:48:03 +0200 Subject: More than one element of list changing when only one should be References: Message-ID: Chuckk Hubbard wrote: > I can't think of any reason these lines: > > self.regionlist[self.hregion][0] = self.curnum > self.regionlist[self.hregion][1] = self.curden > self.regionlist[self.hregion][3] = self.octave11 = self.yadj > > should change self.regionlist[0] AND self.regionlist[2] in the same > call, but they do. ?Also, if I add more regions in series, they all > update each other. The likely explanation is that regionlist[0] and regionlist[2] are actually the same list. Throw in a print self.regionlist[0] is self.regionlist[2] to verify. The two most common reasons for that: class A: items = [] # class attribute, shared between all instances def f(items=[]): # default argument, shared between all calls # without explicit items argument return items Peter From fonnesbeck at gmail.com Thu Jun 19 01:02:35 2008 From: fonnesbeck at gmail.com (hardcoreUFO) Date: Wed, 18 Jun 2008 22:02:35 -0700 (PDT) Subject: Why doesnt PDB allow me to view the current line? Message-ID: I have some code that I am trying to debug (Python 2.5.2 on OSX) using pdb. However, when the code reaches the pdb.set_trace(), it does not allow me to view the current line: > /Users/chris/Research/ISEC/build/bdist.macosx-10.3-i386/egg/pyrl/reinforcement.py(943)__call__() (Pdb) n > /Users/chris/Research/ISEC/build/bdist.macosx-10.3-i386/egg/pyrl/reinforcement.py(946)__call__() (Pdb) l [EOF] (Pdb) l [EOF] It steps through the code fine, but for some reason returns end-of- file when I want to look at the code. From fetchinson at googlemail.com Thu Jun 26 23:11:59 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 26 Jun 2008 20:11:59 -0700 Subject: warning for unused packages/modules/objects Message-ID: How difficult would it be to implement a system in python that would warn if there are unnecessarily imported packages/modules/objects in the code? I mean that when developing some code one frequently imports stuff, deletes the import, changes stuff here and there, imports other stuff, later decides to change things and consequently delete the line with the import, etc, etc. As a result there can stay packages/modules/objects that are in the end not used. It would be great if python would issue a warning once the program finishes. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From constant.beta at gmail.com Sat Jun 21 09:47:29 2008 From: constant.beta at gmail.com (Michal Kwiatkowski) Date: Sat, 21 Jun 2008 06:47:29 -0700 (PDT) Subject: sys.settrace 'call' event behavior Message-ID: <08d43695-093f-4573-ab8b-8da035b3fdae@2g2000hsn.googlegroups.com> I'm building a tool to trace all function calls using sys.settrace function from the standard library. One of the awkward behaviors of this facility is that the class definitions are reported as 'call' events.[1] Since I don't want to catch class definitions, only function calls, I'm looking for a way to differentiate between those two. So far I have only vague clues about how to do that. At the bottom of this mail is a simple script that prints all attributes (except for the bytecode) of the traced code. In the sample code Bar class is defined and foo function is called after that. The following trace output is reported: Bar, 0, 0, (), (), (), (None,), ('__name__', '__module__', 'None'), foo.py, 21, , 1, 66 foo, 0, 0, (), (), (), (None,), (), foo.py, 25, , 1, 67 Class definition and function call differs on four attributes. Two of them, co_name and co_firstlineno are not very helpful. Other two are co_names and co_flags. The latter differs only by the CO_OPTIMIZED flag, which is for "internal use only"[2]. So we're left with co_names, which "is a tuple containing the names used by the bytecode". Is that helpful in distinguishing between class definitions and function calls? Do you have any other ideas on how to tell them apart? Source of the sample script I used follows. def trace(frame, event, arg): if event == 'call': print ', '.join(map(str, [frame.f_code.co_name, frame.f_code.co_argcount, frame.f_code.co_nlocals, frame.f_code.co_varnames, frame.f_code.co_cellvars, frame.f_code.co_freevars, frame.f_code.co_consts, frame.f_code.co_names, frame.f_code.co_filename, frame.f_code.co_firstlineno, frame.f_code.co_lnotab, frame.f_code.co_stacksize, frame.f_code.co_flags])) return trace import sys sys.settrace(trace) class Bar(object): None pass def foo(): pass foo() [1] It is strange for me, but documented properly. http://docs.python.org/lib/debugger-hooks.html says that call event happens when "a function is called (or some other code block entered)." [2] http://docs.python.org/ref/types.html#l2h-145 Cheers, mk From arne at vajhoej.dk Sun Jun 1 19:04:35 2008 From: arne at vajhoej.dk (=?ISO-8859-1?Q?Arne_Vajh=F8j?=) Date: Sun, 01 Jun 2008 19:04:35 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <4840ab73$0$90274$14726298@news.sunsite.dk> <4841f0aa$0$90274$14726298@news.sunsite.dk> Message-ID: <48432b01$0$90272$14726298@news.sunsite.dk> szr wrote: > Arne Vajh?j wrote: >> szr wrote: >>> Peter Duniho wrote: >>>> On Fri, 30 May 2008 22:40:03 -0700, szr >>>> wrote: >>>>> Arne Vajh?j wrote: >>>>>> Stephan Bour wrote: >>>>>>> Lew wrote: >>>>>>> } John Thingstad wrote: >>>>>>> } > Perl is solidly based in the UNIX world on awk, sed, } > bash >>>>>>> and C. I don't like the style, but many do. >>>>>>> } >>>>>>> } Please exclude the Java newsgroups from this discussion. >>>>>>> >>>>>>> Did it ever occur to you that you don't speak for entire news >>>>>>> groups? >>>>>> Did it occur to you that there are nothing about Java in the >>>>>> above ? >>>>> Looking at the original post, it doesn't appear to be about any >>>>> specific language. >>>> Indeed. That suggests it's probably off-topic in most, if not all, >>>> of the newsgroups to which it was posted, inasmuch as they exist for >>>> topics specific to a given programming language. >>> Perhaps - comp.programming might of been a better place, but not all >>> people who follow groups for specific languages follow a general >>> group like that - but let me ask you something. What is it you >>> really have against discussing topics with people of neighboring >>> groups? Keep in mind you don't have to read anything you do not want >>> to read. [1] >> I very much doubt that the original thread is relevant for the Java >> group. >> >> But the subthread Lew commente don was about Perl and Unix. That is >> clearly off topic. > > I agree with and understand what you are saying in general, but still, > isn't it possible that were are people in the java group (and others) > who might of been following the thread, only to discover (probably not > right away) that someone decided to remove the group they were reading > the thread from? I know I would not like that, even if it wasn't on > topic at the branch. > > Personally, I find it very annoying to have to switch news groups in > order to resume a thread and weed my way down the thread to where it > left off before it was cut off from the previous group. I am relative tolerant towards threads that are a bit off topic, if the S/N ratio overall is good. But I accept and respect that other people has a more strict attitude against off topic posts. And I am very little tolerant towards people that think they can attack those that want only on topic posts. One thing is to ask for a bit of slack regarding the rules something else is attacking those that want the rules kept. Arne From tgrav at mac.com Fri Jun 6 18:48:06 2008 From: tgrav at mac.com (Tommy Grav) Date: Fri, 6 Jun 2008 18:48:06 -0400 Subject: how to build a street with more than 1 house ? In-Reply-To: <4849BDF3.3010902@gmail.com> References: <4849BDF3.3010902@gmail.com> Message-ID: On Jun 6, 2008, at 6:45 PM, Stef Mientki wrote: > hello, > > In the code below, I can build a large street like this: > large_street = house * 25 > but not a small street. like this: > small_street = 5 * house This calls the int.__mul__() code i believe. > Why is this different ? > And more interesting, how do I get the right results ? If memory serves me right look into __rmul__(). Cheers Tommy From hniksic at xemacs.org Thu Jun 5 17:57:53 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 05 Jun 2008 23:57:53 +0200 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> <4847d203$0$32733$426a74cc@news.free.fr> Message-ID: <87lk1jzgri.fsf@mulj.homelinux.net> "Russ P." writes: > By the way, my recollection is that in C++ access defaults to private > if nothing is declared explicity. So normally the "private" > declaration is unnecessary. If it is left out, your little trick won't > work. How about #define class struct From precisionreplicas at gmail.com Mon Jun 2 03:17:30 2008 From: precisionreplicas at gmail.com (Best Replica Watches) Date: Mon, 2 Jun 2008 15:17:30 +0800 Subject: fake Watches Message-ID: fake Watches Http://www.precisionreplicas.com We offer you a World of Luxury at very affordable prices and you can rest easy about your satisfaction of quality and service. Now, with just a few simple steps, you can own something that will make you feel and look great! You can go to that business meeting, sales conference, or cocktail party wearing a beautiful watch and be sure to catch people's attention. The way you act, dress and present yourself will always be looked upon by others. By choosing from our selection of fine luxury items for a fraction of the cost you will look and feel successful, confident and you will be at your best. You will have all the class, prestige and luxury of a wealthy successful individual, and not spend a fortune to get there. Most of all you can improve your self esteem and feel confident to move in new circles of business associates and friends. Theses products will surely enhance your style and fashion. No one but you will know the beautiful item you wear is a replica, but you. Many of our customers buy from us and leave the Real One at home...... CATALOG OF REPLICA WATCHES ON: Http://www.precisionreplicas.com Rolex Replica Watches All Rolex Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Rolex Rolex Air King Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Air%20King Rolex Cosmograph Daytona Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Cosmograph%20Daytona Rolex Datejust Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Datejust%20Lady Rolex Datejust Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Datejust%20Man Rolex Datejust Two-Tone Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Datejust%20Two-Tone%20Lady Rolex Datejust Two-Tone Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Datejust%20Two-Tone%20Man Rolex Day-Date Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Day-Date Rolex Day-Date Full Gold Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Day-Date%20Full%20Gold%20Man Rolex Explorer Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Explorer Rolex GMT-Master II Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=GMT-Master%20II Rolex Oyster Perpetual Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Oyster%20Perpetual Rolex Submariner Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Submariner Rolex Yacht-Master Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Yacht-Master%20Lady Rolex Yacht-Master Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Yacht-Master%20Man Rolex Yachtmaster Two-tone Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Rolex&EnSmallclassname=Yachtmaster%20Two-tone%20Lady Cartier Replica Watches All Cartier Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Cartier Cartier Baignoire Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Baignoire%20Lady Cartier Ballon bleu Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Ballon%20bleu%20Lady Cartier Ballon bleu Men Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Ballon%20bleu%20Men Cartier Classic - Mid Size Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Classic%20-%20Mid%20Size Cartier Classic Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Classic%20Lady Cartier Classic Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Classic%20Man Cartier Divan Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Divan Cartier Divan Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Divan%20Lady Cartier Pacha Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Pacha%20Man Cartier Roadster Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Roadster Cartier Santos Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Santos%20Lady Cartier Santos Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Santos%20Man Cartier Tank American Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Tank%20American%20Lady Cartier Tank American Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Tank%20American%20Man Cartier Tank Francaise Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Tank%20Francaise%20Lady Cartier Tank Francaise Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Cartier&EnSmallclassname=Tank%20Francaise%20Man Bvlgari Replica Watches All Bvlgari Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Bvlgari Bvlgari Aluminium Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Bvlgari&EnSmallclassname=Aluminium%20Man Bvlgari B.Zero1 Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Bvlgari&EnSmallclassname=B.Zero1 Bvlgari Classic Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Bvlgari&EnSmallclassname=Classic%20Lady Bvlgari Classic Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Bvlgari&EnSmallclassname=Classic%20Man Bvlgari Diagono Scuba Professional Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Bvlgari&EnSmallclassname=Diagono%20Scuba%20Professional Bvlgari Rettangolo Lady Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Bvlgari&EnSmallclassname=Rettangolo%20Lady Bvlgari Rettangolo Man Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Bvlgari&EnSmallclassname=Rettangolo%20Man Omega Replica Watches All Omega Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Omega Omega Constellation Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Omega&EnSmallclassname=Constellation Omega De Ville Co Axial Chronometer Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Omega&EnSmallclassname=De%20Ville%20Co%20Axial%20Chronometer Omega James Bond Seamaster Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Omega&EnSmallclassname=James%20Bond%20Seamaster Omega Seamaster Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Omega&EnSmallclassname=Seamaster Omega Seamaster Co-Axial Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Omega&EnSmallclassname=Seamaster%20Co-Axial Omega Speedmaster Replica Watches http://www.precisionreplicas.com/En_Product.asp?EnBigClassName=Omega&EnSmallclassname=Speedmaster Breitling Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Breitling Tag Heuer Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Tag%20Heuer Officine Panerai Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Officine%20Panerai A. Lange Sohne Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=A.Lange%20Sohne Franck Muller Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Franck%20Muller Hermes Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Hermes Jacob Co. Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Jacob%20Co. Audemars Piguet Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Audemars%20Piguet Chanel Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Chanel Corum Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Corum Emporio Armani Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Emporio%20Armani Gucci Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Gucci Longines Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Longines Louis Vuitton Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Louis%20Vuitton Patek Philippe Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Patek%20Philippe Piaget Replica Watches http://www.precisionreplicas.com/products_all.asp?EnBigClassName=Piaget From alexnbryan at gmail.com Sat Jun 21 20:49:05 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Sat, 21 Jun 2008 19:49:05 -0500 Subject: Connecting a Desktop App to a Web App Message-ID: Okay, this is my first post to this mailing list, so first off if I shouldn't be sending something here, PLEASE correct me. Okay, so I want to create an app that has a GUI (most likely Tkinter) and will prompt the user to choose files and such and then will upload those files, either regularly or one time, whatever. But I don't know how to go abou doing such a thing, that is creating a app that will automatically upload to a back-up website(online storage). So if anyone can help me out or point me in the right direction that would be great. Thanks! From mdw at distorted.org.uk Sun Jun 8 08:30:05 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Sun, 8 Jun 2008 12:30:05 +0000 (UTC) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> <4847d203$0$32733$426a74cc@news.free.fr> <87lk1jzgri.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: > How about #define class struct Won't work. Consider `template ...'. -- [mdw] From gherron at islandtraining.com Mon Jun 23 11:59:31 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 23 Jun 2008 08:59:31 -0700 Subject: Passing arguments to subclasses In-Reply-To: <7pgv54l0pfaa2l05c4l8f3bld1rskd4dtf@4ax.com> References: <7pgv54l0pfaa2l05c4l8f3bld1rskd4dtf@4ax.com> Message-ID: <485FC863.7070502@islandtraining.com> John Dann wrote: > May I ask a simple newbie question, which I presume is true, but for > which I can't readily find confirmation: > > Let's say I have a parent class with an __init__ method explicitly > defined: > > class ParentClass(object): > def __init__(self, keyword1, keyword2): > etc > > and I subclass this: > > class ChildClass(ParentClass): > # No __init__ method explicitly defined > > Now I presume that I can instantiate a child object as: > > child = ChildClass(arg1, arg2) > > and arg1, arg2 will be passed through to the 'constructor' of the > antecedent ParentClass (there being no overrriding __init__ method > defined for ChildClass) and mapping to keyword1, keyword2 etc. > > Have I understood this correctly? Yes, but... The nice things about Python is that you can use the interactive interpreter to test such things in an instant. (And not have to wait for a response from python-list. Like this: >>> class ParentClass(object): ... def __init__(self, keyword1, keyword2): ... print 'ParentClass.__init__ called with', keyword1, keyword2 ... >>> class ChildClass(ParentClass): ... pass ... >>> child = ChildClass(123,456) ParentClass.__init__ called with 123 456 >>> Gary Herron From pichulin85 at hotmail.com Tue Jun 17 06:29:43 2008 From: pichulin85 at hotmail.com (Petertos) Date: Tue, 17 Jun 2008 03:29:43 -0700 (PDT) Subject: New widget Message-ID: Hello, here's a new casual game that looks interesting. It's called Smilies Invasion and you have to eat as much green smilies as you can: http://www.dolmenent.com/smiliesinvasion/ Greetings from a newbie developer. From metaperl at gmail.com Tue Jun 17 15:45:36 2008 From: metaperl at gmail.com (Terrence Brannon) Date: Tue, 17 Jun 2008 12:45:36 -0700 (PDT) Subject: 2d graphics - drawing a vescica piscis in Python Message-ID: <02c29cf2-5281-4c6f-966c-cb47101529ee@26g2000hsk.googlegroups.com> Hello, I have written a program to draw a vescica piscis from turtle import * def main(): setup(width=400, height=400) r = 50 color("black") circle(r) color("white") forward(r) color("black") circle(r) x = raw_input('please enter a string:') if __name__ == '__main__': main() ... but I would like the following: 1 - I dont like how the bottom of the first circle is not complete 2 - I would like for the left circle to be filled with verticle lines and the right circle to be filled with horizontal lines, so that the vescica piscis is cross-hatched. And finally, is turtle the "best" option for what I'm doing? pyCairo looked a bit hard to get going with, but very powerful. sping looked a bit alpha/beta. From sjmachin at lexicon.net Mon Jun 30 16:43:22 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 30 Jun 2008 13:43:22 -0700 (PDT) Subject: Freeze problem with Regular Expression References: <6cf614F3f8ocoU1@mid.individual.net> <0e1a9726-cc1d-4bd2-b0ba-b2bcc1c27ee8@f24g2000prh.googlegroups.com> <6cs9rtF3g9fsvU1@mid.individual.net> Message-ID: <08a8164c-fb82-4265-a84e-c0ccd92a01db@a32g2000prf.googlegroups.com> On Jul 1, 12:45 am, Kirk wrote: > On Wed, 25 Jun 2008 15:29:38 -0700, John Machin wrote: > > Several problems: > > Ciao John (and All partecipating in this thread), > first of all I'm sorry for the delay but I was out for business. > > > (1) lose the vertical bars (as advised by others) (2) ALWAYS use a raw > > string for regexes; your \s* will match on lower- case 's', not on > > spaces > > right! thanks! > > > (3) why are you using findall on a pattern that ends in "$"? > > Yes, you are right, I started with a different need and then it changed > over time... > > > (6) as remarked by others, you haven't said what you are trying to do; > > I reply here to all of you about such point: that's not important, > although I appreciate very much your suggestions! > My point was 'something that works in Perl, has problems in Python'. It *is* important; our point was 'you didn't define "works", and it was near-impossible (without transcribing your regex into verbose mode) to guess at what you suppose it might do sometimes'. From trepca at gmail.com Fri Jun 20 20:09:07 2008 From: trepca at gmail.com (Sebastjan Trepca) Date: Sat, 21 Jun 2008 02:09:07 +0200 Subject: Weird local variables behaviors Message-ID: Hey, can someone please explain this behavior: The code: def test1(value=1): def inner(): print value inner() def test2(value=2): def inner(): value = value inner() test1() test2() [trepca at sauron ~/dev/tests]$ python locals.py 1 Traceback (most recent call last): File "locals.py", line 13, in test2() File "locals.py", line 10, in test2 inner() File "locals.py", line 9, in inner value = value UnboundLocalError: local variable 'value' referenced before assignment Why can't he find the variable in the second case? Thanks, Sebastjan From mwilson at the-wire.com Mon Jun 9 09:07:03 2008 From: mwilson at the-wire.com (Mel) Date: Mon, 09 Jun 2008 09:07:03 -0400 Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: Frank Millman wrote: > Hi all > > I have a standard requirement for a 'decimal' type, to instantiate and > manipulate numeric data that is stored in a database. I came up with a > solution long before the introduction of the Decimal type, which has > been working well for me. I know the 'scale' (number of decimal > places) of the number in advance. When I read the number in from the > database I scale it up to an integer. When I write it back I scale it > down again. All arithmetic is done using integers, so I do not lose > accuracy. > > There is one inconvenience with this approach. For example, if I have > a product quantity with a scale of 4, and a price with a scale of 2, > and I want to multiply them to get a value with a scale of 2, I have > to remember to scale the result down by 4. This is a minor chore, and > errors are quickly picked up by testing, but it does make the code a > bit messy, so it would be nice to find a solution. > > I am now doing some refactoring, and decided to take a look at the > Decimal type. My initial impressions are that it is quite awkward to > use, that I do not need its advanced features, and that it does not > help solve the one problem I have mentioned above. > > I therefore spent a bit of time experimenting with a Number type that > suits my particular requirements. I have come up with something that > seems to work, which I show below. > > I have two questions. > > 1. Are there any obvious problems in what I have done? > > 2. Am I reinventing the wheel unnecessarily? i.e. can I do the > equivalent quite easily using the Decimal type? > > -------------------- > from __future__ import division > > class Number(object): > def __init__(self,value,scale): > self.factor = 10.0**scale > if isinstance(value,Number): > value = value.value / value.factor I think this could lead to trouble. One complaint against binary floating point is that it messes up low-order decimal digits, and this ensures that all calculations are effectively done in binary floating point. Better, I think would be if isinstance (value, Number): self.value = value.value self.scale = scale + value.scale and be done with it. Of course, this means self.scale no longer gives the preferred number of fractional digits. My bias: I did a DecimalFloat class way back when, when Decimal was being discussed, and separated the exponent for calculations from the rounding precision for display. Cheers, Mel From s0suk3 at gmail.com Sun Jun 15 12:22:03 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Sun, 15 Jun 2008 09:22:03 -0700 (PDT) Subject: Making wxPython a standard module? References: <48512f69$0$11262$c3e8da3@news.astraweb.com> <0bb2d727-4bd8-4baf-be34-716daec1ddff@d1g2000hsg.googlegroups.com> <87y756ahn2.fsf@benfinney.id.au> Message-ID: <0e2b604c-769b-4191-87ea-948566412094@34g2000hsh.googlegroups.com> On Jun 15, 9:37 am, Ben Finney wrote: > s0s... at gmail.com writes: > > I know there must be at least a few very solid answers to this, but, > > just to hear it from the Pythonistas: Why can't there be several GUI > > toolkits on the standard library? > > Because the Zen of Python advises against it: > > >>> import this > > The Zen of Python, by Tim Peters > ? > There should be one-- and preferably only one --obvious way to do it. > I agree with that concept. But there already is more than one way to do it, only that the other ways are being made less accessible (by not being on the standard library), don't you think? Anyway, as I said earlier, I'm sure there must be very solid reasons for this, so I don't intend to argue on this. Just a thought :). From alexnbryan at gmail.com Sat Jun 28 19:05:24 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Sat, 28 Jun 2008 18:05:24 -0500 Subject: Testing for Null? Message-ID: <268ac2770806281605n663670e9n29620f344ed66e4d@mail.gmail.com> I am having a problem with a list value that is empty. I have a list of definitions called mainList. the 5th value in the list doesn't have anything in it. In this case, the values are definitions; also, in this case just the word cheese is defined. Here is my output to the console: 5. a sprawling,weedy plant having small lavender or white flowers and round, flat, segmented fruits thought to resemble little wheels of cheese. 6. 7. an ingot or billet made into a convex, circular form by blows at the ends. I've made it so where the numbers, the period, and two spaces follow that, then the definition. However, as you can see in 6, there is nothing. Here is the code to print all this: n=0 for x in mainList: if mainList[n] == "": print "Error on this definition" else: print str(n+1)+". "+str(mainList[n]) n=n+1 Now the two "" is where I need to figure out if it is empty. What is up right now doesn't work; or at least doesn't give the desired result. So I need to know how to write the if statement to make it work. This should be simple, but I just don't know how to do it, never had this problem before. -------------- next part -------------- An HTML attachment was scrubbed... URL: From segfaulthunter at gmail.com Sun Jun 29 15:21:07 2008 From: segfaulthunter at gmail.com (name) Date: Sun, 29 Jun 2008 12:21:07 -0700 (PDT) Subject: gelato - nvidia and python References: <65fcd6a4-131e-4d7c-96b3-402296bf2a18@y21g2000hsf.googlegroups.com> Message-ID: <72a4698c-45ea-4fe1-a54f-52a4835f0672@d45g2000hsc.googlegroups.com> On Jun 29, 5:34?pm, "catalinf... at gmail.com" wrote: > Did somebody worked with gelato from nvidia and python? > I have some C cod from books nvidia . > This is : > " > GelatoAPI *r = GelatoAPI::CreateRenderer(); > r->Camera ("main"); > ... API calls through r ... > r->Render ("main"); > delete r; ? // Finished with this renderer > " > the code for python i create is only this : > " > python > Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) > [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> import gelato > >>> from gelato import * > >>> r=gelato.CreateRenderer > >>> print r > > >>> dir(r) > > ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', > '__getattribute__', '__hash__', '__init__', '__module__', '__name__', > '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', > '__setattr__', '__str__'] > " > And I blocked here... > Thank you . Maybe you should execute the CreateRenderer, like r=gelato.CreateRenderer() dir(r) I don't have gelato but it might work.. From pavel.uvarov at gmail.com Mon Jun 2 12:41:34 2008 From: pavel.uvarov at gmail.com (pavel.uvarov at gmail.com) Date: Mon, 2 Jun 2008 09:41:34 -0700 (PDT) Subject: ThreadPoolingMixIn References: <3d9dac72-ce4d-4ce5-9213-4bb17aff2f9e@r66g2000hsg.googlegroups.com> <1c4d113e-b375-471d-9d54-1401c8844352@t12g2000prg.googlegroups.com> Message-ID: <03ba6980-55d6-433a-a41f-f36a2edb4d72@f36g2000hsa.googlegroups.com> On Jun 2, 7:15 pm, Michael Str?der wrote: > pavel.uva... at gmail.com wrote: > > To benchmark this I used a simple tcp server which writes a small > > (16k) > > string to the client and closes the connection. > > Just a general note: When benchmarking such a network service it would > be valuable to see benchmark results for several data sizes. I'd expect > better numbers for a ThreadPoolingMixIn when there are more requests > with smaller data size. > > Ciao, Michael. Here are benchmarks for FreeBSD 6.2, amd64 packet_size x y 0 499.57 1114.54 1024 499.29 1130.02 3072 500.09 1119.14 7168 498.20 1111.76 15360 499.29 1086.73 31744 500.04 1036.46 64512 499.43 939.60 130048 499.28 737.44 261120 498.04 499.03 523264 307.54 312.04 1047552 173.57 185.32 2096128 93.61 94.39 x = ThreadingMixIn replies/s y = ThreadPoolingMixIn replies/s From bkasterm at gmail.com Sun Jun 15 10:03:04 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Sun, 15 Jun 2008 07:03:04 -0700 (PDT) Subject: Explaining Implementing a Binary Search Tree. Message-ID: I wrote a binary search tree in python, explaining as I was doing it how and why I did it. I am very interested in receiving comments on the code, process, and anything else that will improve my coding or writing. I wrote this all up in my blog at: http://kasterma.wordpress.com/2008/06/15/implementing-a-binary-search-tree/ The code of the class has been copied below, but the description of the process (mostly an attempt at approaching test driving development for as far as I understand the term) has not been copied. Any and all comments are appreciated. Best, Bart *********** python code ************************ import re class BSTree: def __init__ (self, value = None): self.value = value self.left = None self.right = None def __str__ (self): string = "(" if not self.value == None: string += str (self.value) if not (self.left == None and self.right == None): if self.left != None: string += str (self.left) else: string += "()" if self.right != None: string += str (self.right) else: string += "()" string += ")" return string def FromString (self, string): """ parses the string and builds the corresponding tree. If the parsing fails we print an error message and make no guarantees about the state of the tree. """ def readNumber (string, index): """ reads the number starting at index. Returns the number (as a string) that starts at index and the index that is just after the number. It expects the index to point to the first numberal. """ isdigit = re.compile ("\d") number = "" while isdigit.match (string [index]): number += string[index] index += 1 return number, index def FromString_Help (string, index): """ The function that actually does the parsing of the string. Variable index indicates where in the string we start working, it should be pointing to an open paren, and in returning point to just after the corresponding closing paren. """ if not string [index] == "(": print "FromString_Help: ERROR: no opening paren", print string, index tree = BSTree () tree.value, index = readNumber (string, index + 1) if string [index] == "(": tree.left, index = FromString_Help (string, index) tree.right, index = FromString_Help (string, index) if not string[index] == ")": print "FromString_Help: ERROR: no closing paren" print string, index if tree.value == '' and tree.left == None and tree.right == None: return None, index + 1 else: tree.value = int (tree.value) return tree, index + 1 index = 0 tree, index = FromString_Help (string, index) if tree == None: print "FromString: ERROR: empty tree passed" return self.value = tree.value self.left = tree.left self.right = tree.right def inOrder (self): """ gives a generator that runs through the tree inOrder """ values = [] if self.left != None: values += self.left.inOrder () if self.value != None: values.append (self.value) if self.right != None: values += self.right.inOrder () return values def Insert (self, value): """ add value to the tree in BSTree fashion. We add the value so that the values of the tree will be in order. We do not duplicate values in the tree. """ if self.value == None: # first value added to this tree self.value = value if self.value < value: if self.right == None: self.right = BSTree (value) else: self.right.Insert (value) if self.value > value: if self.left == None: self.left = BSTree (value) else: self.left.Insert (value) def Delete (self, value, parent = None, RL = None): """ remove value from the tree in BSTree fashion. Note: we might end up with an empty tree. """ if self.value == value: if self.left == None and self.right == None: if parent != None: if RL == "right": parent.right = None else: parent.left = None else: self.value = None # created an empty tree, note only # happens at the root. return if self.left == None: self.value = self.right.value self.left = self.right.left self.right = self.right.right elif self.left.right == None: self.value = self.left.value self.left = self.left.left else: moveup = self.left while moveup.right != None: # note that by the elif above at least one step is taken # we are here looking for the node to move up to the root moveup_parent = moveup moveup = moveup.right moveup_parent.right = moveup.left self.value = moveup.value return if self.value < value: self.right.Delete (value, self, "right") if self.value > value: self.left.Delete (value, self, "left") def Search (self, value): if self.value == value: return "yes" if self.value < value: if self.right == None: return "no" else: return self.right.Search (value) if self.value > value: if self.left == None: return "no" else: return self.left.Search (value) From fuzzyman at gmail.com Mon Jun 30 16:25:13 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 30 Jun 2008 13:25:13 -0700 (PDT) Subject: URLLIb2 problem References: <156e077b-1305-476c-885f-0b798f4ce699@s21g2000prm.googlegroups.com> Message-ID: On Jun 30, 9:11?pm, leechat2... at gmail.com wrote: > I am trying to write somecode of this kind :) > > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) > opener.addheaders = [('User-Agent','Mozilla/5.0 (Windows; U; Windows > NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14'), > ('Accept','text/xml,application/xml,application/xhtml+xml,text/ > html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'),('Accept- > Language','en-us,en;q=0.5'),('Accept-Encoding','gzip,deflate'), > ('Accept-Charset','ISO-8859-1,utf-8;q=0.7,*;q=0.7'),('Keep- > Alive','300'),('Connection','keep-alive'),('Content-Type','application/ > x-www-form-urlencoded')] > urllib2.install_opener(opener) > > fu = urllib2.urlopen('http://www.google.com') > print fu.read() > > I am not able to open any webpage as the content is junk > characters.something like below..what could be the > problem????????????? I think you'll find that the problem is caused by this part: ('Accept-Encoding','gzip,deflate') You may also find that these cause you some fun as well. ('Keep-Alive','300'),('Connection','keep-alive') Michael Foord http://www.ironpythoninaction.com/ http://www.trypython.org/ > > if I don't install the 'opener' I get everything properly > > ?]?s?H? ?T? ?Cj2????x:&? ?c???????~J ? ??????I??w???????ZB??q?? > ?T9?R???????????4 > ?7?????V??.i??"?????????W>? > ??y?=vm??)?????6??y???????9????l????>?????????(?g[??? > L?S??????????e???????GcS??w > s????/??G??|???9??F`??????*?????BV,????????o??pzn??;?y9?4 > ???f????z8???b?n??K}|? From n.emami at gmail.com Thu Jun 12 06:58:53 2008 From: n.emami at gmail.com (Nader) Date: Thu, 12 Jun 2008 03:58:53 -0700 (PDT) Subject: get keys with the same values Message-ID: Hello, I have a dictionary and will get all keys which have the same values. d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} I will something as : d.keys(where their values are the same) With this statement I can get two lists for this example: l1= ['a','e'] l2=['b','d'] Would somebody tell me how I can do it? Regards, Nader From KKatreena at gmail.com Sat Jun 21 06:20:34 2008 From: KKatreena at gmail.com (Katreena) Date: Sat, 21 Jun 2008 03:20:34 -0700 (PDT) Subject: earn money from Blogs Message-ID: Hello friends.., Welcome to the world of Information Technology,Enjoy the fragrance of Modern Life style&Make ur Living more comfortable than everbefore! Earn Millions of Dollars legal Income With Little Efforts In ur Spare time! Success usually comes to those who are too busy to be looking for it. Visit Related sites,Hollywood Movies and Videos etc.., - Hide quoted text - www.hollywoodmoviespot4u.blogspot.com
    Hii?Click image xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Hi..Click me

    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Hi..Click me

    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Hi..Click me

    From python-url at phaseit.net Tue Jun 3 10:27:25 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 3 Jun 2008 14:27:25 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Jun 3) Message-ID: QOTW: "PS: in some ways it's interesting and relevant that there has been no discussion on psf-members of Google's AppEngine, which many people I've talked to think is the most important thing that's ever happened to Python ever." - David Ascher Alternatives for a multi dimensional dictionary: http://groups.google.com/group/comp.lang.python/browse_thread/thread/91056401e4dbdadc/ Threads and memory usage: http://groups.google.com/group/comp.lang.python/browse_thread/thread/44c20f2595fe298b/ Should Python provide "real" data hiding? http://groups.google.com/group/comp.lang.python/browse_thread/thread/188467d724b48b32/ In response to a requirement for a data structure with fast inserts, no duplicates, and sorted items, several alternatives emerge: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ab429c0221994e2d/ How to read utf-8 encoded input from sys.stdin: http://groups.google.com/group/comp.lang.python/browse_thread/thread/44bb63456be8c331/ Looking for something similar to "classic" ASP web development in Python - and why it may not be a good idea: http://groups.google.com/group/comp.lang.python/browse_thread/thread/9bd633032e5709a8/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From __peter__ at web.de Sun Jun 15 08:17:23 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Jun 2008 14:17:23 +0200 Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> Message-ID: ram.rachum at gmail.com wrote: > On Jun 15, 2:48?pm, Peter Otten <__pete... at web.de> wrote: >> ram.rac... at gmail.com wrote: >> > Quick question: >> > I have python code that does a lot of floating point arithmetic. How >> > do I make it do the arithmetic in 64 bit? (I have a 64 bit CPU.) If >> > I'll install a 64-bit operating system, will that do the trick? >> >> The Python float type uses a C double internally which is 64 bit even on >> 32 bit CPUs. >> >> Peter > > Does it mean that even now it does arithmetic in 64 bit? Yes. See http://en.wikipedia.org/wiki/IEEE_floating-point_standard#Double-precision_64_bit for details. > I'm not getting enough precision. Is there any way to increase it? http://gmpy.sourceforge.net/ If by "not enough precision" you mean you are bothered by >>> .1 0.10000000000000001 have a look at the decimal module, see http://docs.python.org/lib/module-decimal.html Peter From tdahsu at gmail.com Fri Jun 13 11:56:12 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Fri, 13 Jun 2008 08:56:12 -0700 (PDT) Subject: Iterate creating variables? References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> <6bfhj5F3b47fmU1@mid.uni-berlin.de> <6bfj7bF3c3npoU1@mid.uni-berlin.de> Message-ID: On Jun 13, 11:48?am, "Diez B. Roggisch" wrote: > tda... at gmail.com schrieb: > > > > > On Jun 13, 11:21 am, "Diez B. Roggisch" wrote: > >> tda... at gmail.com schrieb: > > >>> I have twenty-five checkboxes I need to create (don't ask): > >>> self.checkbox1 = ... > >>> self.checkbox2 = ... > >>> . > >>> . > >>> . > >>> self.checkbox25 = ... > >>> Right now, my code has 25 lines in it, one for each checkbox, since > >>> these are all variables. > >>> Is there a way to write a loop so that I can have fewer lines of code > >>> but still keep the variables? > >>> I've tried: > >>> for o in xrange(25): > >>> ? ? self.checkbox[o] = ... > >>> which didn't work, and > >>> for o in xrange(25): > >>> ? ? self.checkbox[''%d'%(o)] = ... > >>> which also didn't work. > >>> Both give the error message: "Attribute error: Main.App has no > >>> attribute "checkbox"", which clearly indicates that I'm not keeping > >>> the "variability" aspect I want. > >>> Is there a way? > >> Keep either a list or dictionary around. Like this: > > >> checkboxes = [] > > >> for o in xrange(25): > >> ? ? ?checkboxes.append(....create a checkbox...) > > >> self.checkboxes = checkboxes > > >> Diez > > > I don't understand... how do I then complete the assignment statement? > > > If I have: > > > self.checkbox1 = xrc.XRCCTRL(self.panel01, 'Checkbox1') > > . > > . > > . > > self.checkbox25 = xrc.XRCCTRL(self.panel01, 'Checkbox25') > > > using your method, wouldn't I still need to figure out my original > > question? > > > If I have a list of checkboxes, then I'll have: > > > checkboxes = [checkbox1, checkbox2 ... checkbox25] > > > in which case I'd still need to figure out how to get the variable at > > the end of checkbox to do the rest of the "=" statement. > > I don't fully understand that. But if your code is uniform and looks > like the above, it appears that > > for o in xrange(25): > ? ? ?checkboxes.append(xrc.XRCCTRL(self.panel01, 'Checkbox%i' % o)) > > is the way to go. > > Diez Thank you, this is much closer to where I need to be... The issue is (and this is the part that you don't know, because I didn't tell you!) is that I later need to call methods on "self.checkbox1", for instance: self.checkbox1.GetValue() to determine if the box is checked or not. I should have included that piece in the initial problem description; my apologies. From wizzardx at gmail.com Sun Jun 22 07:11:01 2008 From: wizzardx at gmail.com (David) Date: Sun, 22 Jun 2008 13:11:01 +0200 Subject: Storing value with limits in object In-Reply-To: References: Message-ID: <18c1e6480806220411u391e6dc9t34465e5d5a468440@mail.gmail.com> On Sun, Jun 22, 2008 at 12:24 PM, Josip wrote: >> Not with normal vars, because = is a rebinding operator in Python, >> rather than assignment. >> >> You can do (close to) the above with object properties. >> >> David. > > Yes, but it's done with built-in types like int and float. I suspect I could > subclass from them and implement limits, but I would have to make > seperate class for each type. Can I override conversion methods like int() > and float() within my class? > I think I may have misread your original post. ints and floats are internal , immutable types, with some class goodness on top (so you can treat them like objects to a degree, subclass from them, etc). Python's interpreter has built-in logic which 'knows' how to use ints and floats variables, without calling their special "__" methods. Python would be a lot slower if it worked this way. To do exactly what you want, you'd need to add a new internal numeric type to Python. You can subclass from float, and redefine __float__ and __int__, but those will only be called when your code actually calls the builtin float() and int() builtins, eg: import math class Float(float): def __float__(self): raise NotImplementedError a = Float(1) print math.sin(a) # Outputs 0.841470984808 a = Float(1) print math.sin(float(a)) # Throws a NotImplementedError exception There is no way (afaik) for an object to tell Python to call one of it's methods to get a reference, or 'value' to the object (if there was, it would make things really complicated). In Python you generally need to update the logic used during a lookup to get that effect (ie, in a.b.c, you can customise the a.b lookup, or the a.b.c lookup, but not the a lookup itself). In theory you could hack Python's internal locals or globals dictionary so that it did something unusual while looking up your object. But in practice this doesn't work, because the returned objects (when you call globals() or locals()) attributes are readonly. Probably because those internal lookup dicts are implemented in optimized C not Python, and the C implementation doesn't let you redefine it's internals via the Python interface. David. From rhamph at gmail.com Wed Jun 11 01:59:42 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Tue, 10 Jun 2008 22:59:42 -0700 (PDT) Subject: Producer-consumer threading problem References: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> Message-ID: <9482cbb7-297e-4429-b7a1-6d7c1dcc9070@t12g2000prg.googlegroups.com> Why not use a normal Queue, put a dummy value (such as None) in when you're producer has finished, and have the main thread use the normal Thread.join() method on all your child threads? From bignose+hates-spam at benfinney.id.au Sun Jun 15 10:37:37 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 16 Jun 2008 00:37:37 +1000 Subject: Making wxPython a standard module? References: <48512f69$0$11262$c3e8da3@news.astraweb.com> <0bb2d727-4bd8-4baf-be34-716daec1ddff@d1g2000hsg.googlegroups.com> Message-ID: <87y756ahn2.fsf@benfinney.id.au> s0suk3 at gmail.com writes: > I know there must be at least a few very solid answers to this, but, > just to hear it from the Pythonistas: Why can't there be several GUI > toolkits on the standard library? Because the Zen of Python advises against it: >>> import this The Zen of Python, by Tim Peters ? There should be one-- and preferably only one --obvious way to do it. -- \ "Tis more blessed to give than to receive; for example, wedding | `\ presents." -- Henry L. Mencken | _o__) | Ben Finney From dullrich at sprynet.com Wed Jun 4 17:39:38 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Wed, 04 Jun 2008 16:39:38 -0500 Subject: re References: <6anvi4F38ei08U1@mid.uni-berlin.de> Message-ID: In article , "Russell Blau" wrote: > "Diez B. Roggisch" wrote in message > news:6anvi4F38ei08U1 at mid.uni-berlin.de... > > David C. Ullrich schrieb: > >> Say I want to replace 'disc' with 'disk', but only > >> when 'disc' is a complete word (don't want to change > >> 'discuss' to 'diskuss'.) The following seems almost > >> right: > >> > >> [^a-zA-Z])disc[^a-zA-Z] > >> > >> The problem is that that doesn't match if 'disc' is at > >> the start or end of the string. Of course I could just > >> combine a few re's with |, but it seems like there should > >> (or might?) be a way to simply append a \A to the first > >> [^a-zA-Z] and a \Z to the second. > > > > Why not > > > > ($|[\w])disc(^|[^\w]) > > > > I hope \w is really the literal for whitespace - might be something > > different, see the docs. > > No, \s is the literal for whitespace. > http://www.python.org/doc/current/lib/re-syntax.html > > But how about: > > text = re.sub(r"\bdisc\b", "disk", text_to_be_changed) > > \b is the "word break" character, Lovely - that's exactly right, thanks. I swear I looked at the docs... I'm just blind or stupid. No wait, I'm blind _and_ stupid. No, blind and stupid and slow... Doesn't precisely fit the _spec_ because of digits and underscores, but it's close enough to solve the problem exactly. Thanks. >it matches at the beginning or end of any > "word" (where a word is any sequence of \w characters, and \w is any > alphanumeric > character or _). > > Note that this solution still doesn't catch "Disc" if it is capitalized. Thanks. I didn't mention I wanted to catch both cases because I already knew how to take care of that: r"\b[dD]isc\b" > Russ -- David C. Ullrich From goon12 at gmail.com Mon Jun 23 09:38:40 2008 From: goon12 at gmail.com (Joe Riopel) Date: Mon, 23 Jun 2008 09:38:40 -0400 Subject: Distutils and unit test files Message-ID: <6a2ccd190806230638m27206217k2ac181b4999bc2e5@mail.gmail.com> Hi, I am using Distutils to build and distribute some packages. I do write unit tests, but I am confused as to where to put them and how to run them prior to the package being installed (The modules being tested would not be in my sys.path). I would rather not put the test cases in the same files as the modules being tested, I want keep them in a sub directory of the module, or in a separate "test" directory. What are some of the strategies for dealing with this? Thanks. From larry.bates at websafe.com` Sat Jun 7 16:06:39 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 07 Jun 2008 15:06:39 -0500 Subject: simple question on list manipulation from a newbie In-Reply-To: <76ccc0a8-90de-4717-9e6f-06836827b1e1@i18g2000prn.googlegroups.com> References: <76ccc0a8-90de-4717-9e6f-06836827b1e1@i18g2000prn.googlegroups.com> Message-ID: <2IOdnfa0D533d9fVnZ2dnUVZ_sKqnZ2d@comcast.com> Sengly wrote: > Dear all, > > I am working with wordnet and I am a python newbie. I'd like to know > how can I transfer a list below > > In [69]: dog > Out[69]: > [{noun: dog, domestic_dog, Canis_familiaris}, > {noun: frump, dog}, > {noun: dog}, > {noun: cad, bounder, blackguard, dog, hound, heel}, > {noun: frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, > weenie}, > {noun: pawl, detent, click, dog}, > {noun: andiron, firedog, dog, dog-iron}] > > to a list like this with python: > > [dog, domestic_dog, Canis_familiaris, > frump, dog, > dog, > cad, bounder, blackguard, dog, hound, heel, > frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, > weenie}, > pawl, detent, click, dog}, > andiron, firedog, dog, dog-iron] > > Thank you. > > Sengly > You should at least tell us what you have tried and where this information is coming from and in what format. Assumptions: 1) is a string containing what is shown (not a list of dictionaries) 2) the result you want is also a string (not a list) out = '[{noun: dog, domestic_dog, Canis_familiaris},{noun: frump, dog},' \ '{noun: dog},{noun: cad, bounder, blackguard, dog, hound, heel},' \ '{noun: frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, ' \ 'weenie}, {noun: pawl, detent, click, dog}, {noun: andiron, firedog, ' \ 'dog, dog-iron}]' l = out.replace('}', '')[1:-1].split('{noun: ')[1:] results = [] for entry in l: words = [x.strip() for x in entry.split(',')] results.extend(words) print results Note: this is very specific to the contents you show. If you need a general solution you will either need to use regexes or look a pyparsing. -Larry From larry.bates at websafe.com` Sat Jun 14 19:11:36 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 14 Jun 2008 18:11:36 -0500 Subject: os.walk Value Error? In-Reply-To: References: Message-ID: tdahsu at gmail.com wrote: > Hi, > > I'm using os.walk as follows: > > (basedir, pathnames, files) = os.walk("results", topdown=True) > > and I'm getting the error: > > ValueError: too many values to unpack > > From my googling, that means: > > This is the standard message when Python tries to unpack a tuple > into fewer variables than are in the tuple. > > From what I can see of the examples on the python site, I'm using it > correctly. I have commas in my original code, and the "results" > directory exists and is directly under the directory from which my > script is run. > > I'm assuming that 12 files (the number of files in the "results" > directory) is not too many for Python to handle! ;-) > > Is there any other reason I might get that error? os.walk is a generator so you need to make it a loop target: for basedir, pathnames, files in os.walk("results"): # # Do you work inside the loop # -Larry From prabhuragav.b at gmail.com Fri Jun 6 02:10:36 2008 From: prabhuragav.b at gmail.com (BABLU) Date: Thu, 5 Jun 2008 23:10:36 -0700 (PDT) Subject: EARN DOLLARS NO INVESTMENT NO SALES 100% HOME BASED BUSINESS Message-ID: <15b38591-fc8d-40f3-9402-1808ef6130f7@l17g2000pri.googlegroups.com> Hi, I am doing home based business and earning a good amount of money and found that business through internet is amazing to earn during leisure.Its just easy and relaxing. Just login in the link below and register yourself. register is free. then they will promote job for you. I have provided three site links for you so that you can earn money in which you want. Every job is genuine, good easy and interesting too. Make a try and fill your pockets with dollars. FREE ! FREE ! FULLY GENUINE HOME BASED ? CLICK HERE http://www.ezinfocenter.com/10122618/CB http://Prabhiya.dubaimlm.com? http://www.CashBlasterPro.com/earndollars http://www.webupgrade7.com/earndollars http://www.webupgrade9.com/earndollars http://www.webupgrade10.com/earndollars http://www.www2upgrade.com/earndollars http://www.BizOpSpace.com/earndollars http://www.BizOpBuilder.com/earndollars http://www.MyWebToo.com/earndollars http://www.Web2Wow.com/earndollars While you've been reading the above, thousands of people all over the world have been working. I even make money while I sleep! By this time next week, so could YOU. Get full info here http://www.ezinfocenter.com/10122618/CB http://Prabhiya.dubaimlm.com http://www.CashBlasterPro.com/earndollars http://www.webupgrade7.com/earndollars http://www.webupgrade9.com/earndollars http://www.webupgrade10.com/earndollars http://www.www2upgrade.com/earndollars http://www.BizOpSpace.com/earndollars http://www.BizOpBuilder.com/earndollars http://www.MyWebToo.com/earndollars http://www.Web2Wow.com/earndollars Network Marketing is BOOMING on the Web! Learn how we're sponsoring OVER 100,000 monthly worldwide without mailing anything, without faxing anything, without calling anyone! Totally Internet and system- driven and we've only scratched the surface. Get started FREE! Sign up as an affiliate at: http://www.ezinfocenter.com/10122618/CB ?http://Prabhiya.dubaimlm.com http://www.CashBlasterPro.com/earndollars http://www.webupgrade7.com/earndollars http://www.webupgrade9.com/earndollars http://www.webupgrade10.com/earndollars http://www.www2upgrade.com/earndollars http://www.BizOpSpace.com/earndollars http://www.BizOpBuilder.com/earndollars http://www.MyWebToo.com/earndollars http://www.Web2Wow.com/earndollars For More Details : Contact us at: Priya Prabhu No.75/31,Ist Floor , Subramanianm Swamy Koil Street West Saidapet chennai-600015 prabhuragav.b at gmail.com http://www.ezinfocenter.com/10122618/CB http://Prabhiya.dubaimlm.com http://www.CashBlasterPro.com/earndollars http://www.webupgrade7.com/earndollars http://www.webupgrade9.com/earndollars http://www.webupgrade10.com/earndollars http://www.www2upgrade.com/earndollars http://www.BizOpSpace.com/earndollars http://www.BizOpBuilder.com/earndollars http://www.MyWebToo.com/earndollars http://www.Web2Wow.com/earndollars From mensanator at aol.com Tue Jun 17 16:36:29 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 17 Jun 2008 13:36:29 -0700 (PDT) Subject: 2d graphics - drawing a vescica piscis in Python References: <02c29cf2-5281-4c6f-966c-cb47101529ee@26g2000hsk.googlegroups.com> Message-ID: <4d8959ac-4f28-4291-8208-d4b0ed9f5480@l64g2000hse.googlegroups.com> On Jun 17, 2:45?pm, Terrence Brannon wrote: > Hello, I have written a program to draw a vescica piscis en.wikipedia.org/wiki/Vesica_piscis> > > from turtle import * > > def main(): > ? ? setup(width=400, height=400) > > ? ? r = 50 > ? ? color("black") > ? ? circle(r) > ? ? color("white") > ? ? forward(r) > ? ? color("black") > ? ? circle(r) > ? ? x = raw_input('please enter a string:') > > if __name__ == '__main__': > ? ? main() > > ... but I would like the following: > > 1 - I dont like how the bottom of the first circle is not complete Because you overwrote that portion of the circle when you changed the color to white. Instead, you should have done up() (which lifts the pen) and then down() after you've moved to the start of the second circle. No need to change the pen color. > 2 - I would like for the left circle to be filled with verticle lines > and the right circle to be filled with horizontal lines, so that the > vescica piscis is cross-hatched. That would be the fill() command, but it's not documented how to fill with anything other than a solid color. > > And finally, is turtle the "best" option for what I'm doing? pyCairo > looked a bit hard to get going with, but very powerful. sping looked a > bit alpha/beta. From ethan at stoneleaf.us Tue Jun 17 15:42:20 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 17 Jun 2008 11:42:20 -0800 Subject: 'string'.strip(chars)-like function that removes from the middle? In-Reply-To: <48569B9E.6030206@admailinc.com> References: <48569B9E.6030206@admailinc.com> Message-ID: <4858139C.6090201@stoneleaf.us> Ethan Furman wrote: > Greetings. > > The strip() method of strings works from both ends towards the middle. > Is there a simple, built-in way to remove several characters from a > string no matter their location? (besides .replace() ;) > > For example: > .strip --> 'www.example.com'.strip('cmowz.') > 'example' > .??? --> --- 'www.example.com'.strip('cmowz.') > 'exaple' Thanks for all the ideas! -- Ethan From nmiyasato at gmail.com Sun Jun 29 22:26:45 2008 From: nmiyasato at gmail.com (miya) Date: Sun, 29 Jun 2008 19:26:45 -0700 (PDT) Subject: How to invoke the Python idle References: <08484763-05df-49ee-b308-2dd64b7e2379@e39g2000hsf.googlegroups.com> Message-ID: <6cf3de4e-e279-4aa3-99d3-7a32a6baeebe@27g2000hsf.googlegroups.com> On Jun 29, 10:01?pm, Only-Trouble wrote: > Hi all > I am running openSUSE 10.3 > I am learning python on my own, it seems like ?the system has already > installed a python IDLE > The question is how to invoke it? > > Thanks > > Only-Trouble how about executing from the terminal idle -- Nicol?s Miyasato (miya) http://nmiyasato.blogspot.com From Lie.1296 at gmail.com Tue Jun 3 06:22:35 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 3 Jun 2008 03:22:35 -0700 (PDT) Subject: Misuse of list comprehensions? References: <038e4418$0$27258$c3e8da3@news.astraweb.com> <7aa231e6-2f9c-4e90-8cd1-e839dc6940f2@x35g2000hsb.googlegroups.com> <69g3bmF31ttuuU3@mid.uni-berlin.de> Message-ID: On May 20, 8:51?pm, "Diez B. Roggisch" wrote: > bearophileH... at lycos.com wrote: > > John Salerno: > >> What does everyone think about this? > > > The Example 2 builds a list, that is then thrown away. It's just a > > waste of memory (and time). > > No, it doesn't. It uses append because it refers to itself in the > if-expression. So the append(c) is needed - and thus the assignment > possible but essentially useless. > > Diez Yes it does, it build a list of 'None's. And if list.append is concerned, the example given has no use, since: x = [c for c in cs] is essentially the same as x = [] [x.append(c) for c in cs] If, you're talking about other function calls, it might be an abuse or not depending on personal preference. From thomasmallen at gmail.com Tue Jun 3 15:16:47 2008 From: thomasmallen at gmail.com (tmallen) Date: Tue, 3 Jun 2008 12:16:47 -0700 (PDT) Subject: New variable? References: <18105511-7ae1-45e9-8c43-f34c1c4f5aeb@c58g2000hsc.googlegroups.com> <0dabbe7c-5754-4b2a-ae69-e92939fa682b@r66g2000hsg.googlegroups.com> Message-ID: <2c47defa-52b3-4bbc-8286-9e266df80eb7@26g2000hsk.googlegroups.com> On Jun 3, 3:03 pm, Chris wrote: > On Jun 3, 8:40 pm, tmallen wrote: > > > What's the proper way to instantiate a new variable? x = ""? > > You don't need to pre-declare your variables. Just assign them as you > need them and they will take the correct type. unless I'm using the += or a similar operator, right? That doesn't seem to instantiate a variable. From jstroud at mbi.ucla.edu Fri Jun 6 17:20:37 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 06 Jun 2008 14:20:37 -0700 Subject: Learning which modules were loaded Message-ID: I am rolling up a distribution of a program I wrote. It uses matplotlib with tkagg so the bundle is HUGE (47 MB, 14 MB after bz compression). Is there any way to run the program, put it through all of its paces, and then inspect which modules were loaded. I would like to gather these in a list and delete any others that py2app and py2exe attempt to include. Currently, these (or py2app, at least) use dependency graphing and icnlude everything belonging to pylab, matplotlib, and numpy by default. I don't want everything, I only want what my program needs to run. For example, some modules are imported by functions (in Pmw, for example) that never get called. I don't want to include these. Thanks in advance for any help. James From theo at van-werkhoven.nl.invalid Sun Jun 8 06:58:07 2008 From: theo at van-werkhoven.nl.invalid (Theo v. Werkhoven) Date: Sun, 8 Jun 2008 12:58:07 +0200 Subject: time.clock() or Windows bug? Message-ID: hi, In this code I read out an instrument during a user determined period, and save the relative time of the sample (since the start of the test) and the readback value in a csv file. #v+ from datetime import * from time import * from visa import * from random import * [..] for Reading in range(Readings): RelTimeOfSample = "%.1f" % clock() #PwrMtr.write("READ?") #Sample = "%.3f" % float(PwrMtr.read()) Sample = "%.3f" % (uniform(8.9,9.3)) # Simulation of reading. print "Sample %s, at %s seconds from start; Output power is: %s dBm" % (Reading+1, RelTimeOfSample, Sample) writer.writerow([RelTimeOfSample, Sample]) ResultFile.flush() sleep(6.6) #v- Output: Sample 1, at 0.0 seconds from start; Output power is: 8.967 dBm Sample 2, at 6.6 seconds from start; Output power is: 9.280 dBm Sample 3, at 13.2 seconds from start; Output power is: 9.096 dBm Sample 4, at 19.8 seconds from start; Output power is: 9.166 dBm Sample 5, at 26.4 seconds from start; Output power is: 8.918 dBm Sample 6, at 33.0 seconds from start; Output power is: 9.183 dBm Sample 7, at 39.7 seconds from start; Output power is: 8.903 dBm Sample 8, at 46.3 seconds from start; Output power is: 9.138 dBm Sample 9, at 52.9 seconds from start; Output power is: 9.163 dBm Sample 10, at 59.5 seconds from start; Output power is: 9.075 dBm Sample 11, at 66.1 seconds from start; Output power is: 9.230 dBm Sample 12, at 72.7 seconds from start; Output power is: 9.225 dBm Sample 13, at 79.3 seconds from start; Output power is: 9.053 dBm Sample 14, at 85.9 seconds from start; Output power is: 9.066 dBm Sample 15, at 92.5 seconds from start; Output power is: 9.109 dBm Sample 16, at 99.1 seconds from start; Output power is: 9.286 dBm Sample 17, at 105.7 seconds from start; Output power is: 9.147 dBm Sample 18, at 112.4 seconds from start; Output power is: 9.284 dBm Sample 19, at 119.0 seconds from start; Output power is: 9.013 dBm Sample 20, at 125.6 seconds from start; Output power is: 8.952 dBm Sample 21, at 91852.8 seconds from start; Output power is: 9.102 dBm Sample 22, at 91862.7 seconds from start; Output power is: 9.289 dBm Sample 23, at 145.4 seconds from start; Output power is: 9.245 dBm Sample 24, at 152.0 seconds from start; Output power is: 8.936 dBm Sample 25, at 158.8 seconds from start; Output power is: 9.139 dBm Sample 26, at 165.4 seconds from start; Output power is: 9.241 dBm Sample 27, at 172.1 seconds from start; Output power is: 8.938 dBm Sample 28, at 178.7 seconds from start; Output power is: 8.947 dBm Sample 29, at 185.3 seconds from start; Output power is: 9.252 dBm Sample 30, at 191.9 seconds from start; Output power is: 9.082 dBm Sample 31, at 198.5 seconds from start; Output power is: 9.224 dBm Sample 32, at 205.1 seconds from start; Output power is: 8.902 dBm Sample 33, at 211.7 seconds from start; Output power is: 9.182 dBm Sample 34, at 218.3 seconds from start; Output power is: 8.974 dBm Sample 35, at 224.9 seconds from start; Output power is: 9.129 dBm Sample 36, at 231.5 seconds from start; Output power is: 9.214 dBm Sample 37, at 238.1 seconds from start; Output power is: 9.188 dBm Sample 38, at 244.8 seconds from start; Output power is: 8.909 dBm Sample 39, at 251.4 seconds from start; Output power is: 9.197 dBm Sample 40, at 258.0 seconds from start; Output power is: 8.946 dBm Sample 41, at 264.6 seconds from start; Output power is: 9.228 dBm Sample 42, at 271.2 seconds from start; Output power is: 8.938 dBm Sample 43, at 92071.3 seconds from start; Output power is: 8.964 dBm Sample 44, at 284.4 seconds from start; Output power is: 9.276 dBm Sample 45, at 291.0 seconds from start; Output power is: 8.932 dBm Sample 46, at 297.6 seconds from start; Output power is: 9.158 dBm But look at the timestamps of samples 21, 22 and 43. What is causing this? I've replaced the time.clock() with time.time(), and that seems to solve the problem, but I would like to know if it's something I misunderstand or if it's a problem with the platform (Windows Server 2003) or the time.clock() function. T:\Theo\Python>ver Microsoft Windows [Version 5.2.3790] T:\Theo\Python>c:\Python25\python.exe --version Python 2.5.1 Thanks, Theo From bob at mellowood.ca Wed Jun 11 19:38:58 2008 From: bob at mellowood.ca (bvdp) Date: Wed, 11 Jun 2008 16:38:58 -0700 Subject: Simple and safe evaluator Message-ID: I'm finding my quest for a safe eval() quite frustrating :) Any comments on this: Just forget about getting python to do this and, instead, grab my set of values (from a user supplied text file) and call an external program like 'bc' to do the dirty work. I think that this would avoid someone from embedding os.system("rm ...") in what I thought would be a math expression and having it maybe do damage? Perhaps I'm getting too paranoid in my old age. I guess this would slow things down a bit, but that is not a big concern. Bigger concern would be that I'm not sure if 'bc' or whatever is guaranteed to be on other platforms than *nix. And if I want to be really paranoid, I could worry that someone had planted a bad 'bc' on the target. From paddy3118 at googlemail.com Fri Jun 13 00:53:06 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 12 Jun 2008 21:53:06 -0700 (PDT) Subject: Mapping None. Why? References: Message-ID: On Jun 12, 9:48 pm, Robert Kern wrote: > Paddy wrote: > > On looking up map on Wikipedia there is no mention of this special > > behaviour, > > So my question is why? > > My question is why you are looking up the semantics of Python functions on > Wikipedia instead of the Python documentation. I don't see any particular > discussion of map() there at all. Am I missing something? > > -- > Robert Kern As I said in an answer to Diez B. Roggish, I had been reminded of the behaviour, thought it odd, and looked for other implementations that might have the behaviour via wikipedia. My intension was most definitely NOT to say that Pythons map should do what Wikipedia says slavishly. Sometimes when I pick at these seeming inconsistencies I learn a lot from the c.l.p replies. Someone elses thread on -0.0 versus +0.0 taught me some more on floating point for example. - Paddy. From eliben at gmail.com Fri Jun 20 08:03:00 2008 From: eliben at gmail.com (eliben) Date: Fri, 20 Jun 2008 05:03:00 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> Message-ID: <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> On Jun 20, 9:17 am, Bruno Desthuilliers wrote: > eliben a ?crit :> Hello, > > > In a Python program I'm writing I need to dynamically generate > > functions[*] > > (snip) > > > [*] I know that each time a code generation question comes up people > > suggest that there's a better way to achieve this, without using exec, > > eval, etc. > > Just to make things clear: you do know that you can dynamically build > functions without exec, do you ? > Yes, but the other options for doing so are significantly less flexible than exec. > > But in my case, for reasons too long to fully lay out, I > > really need to generate non-trivial functions with a lot of hard-coded > > actions for performance. > > Just out of curiousity : could you tell a bit more about your use case > and what makes a simple closure not an option ? Okay. I work in the field of embedded programming, and one of the main uses I have for Python (and previously Perl) is writing GUIs for controlling embedded systems. The communication protocols are usually ad-hoc messages (headear, footer, data, crc) built on top of serial communication (RS232). The packets that arrive have a known format. For example (YAMLish syntax): packet_length: 10 fields: - name: header offset: 0 length: 1 - name: time_tag offset: 1 length: 1 transform: val * 2048 units: ms - name: counter offset: 2 length: 4 bytes-msb-first: true - name: bitmask offset: 6 length: 1 bit_from: 0 bit_to: 5 ... This is a partial capability display. Fields have defined offsets and lengths, can be only several bits long, can have defined transformations and units for convenient display. I have a program that should receive such packets from the serial port and display their contents in tabular form. I want the user to be able to specify the format of his packets in a file similar to above. Now, in previous versions of this code, written in Perl, I found out that the procedure of extracting field values from packets is very inefficient. I've rewritten it using a dynamically generated procedure for each field, that does hard coded access to its data. For example: def get_counter(packet): data = packet[2:6] data.reverse() return data This gave me a huge speedup, because each field now had its specific function sitting in a dict that quickly extracted the field's data from a given packet. Now I'm rewriting this program in Python and am wondering about the idiomatic way to use exec (in Perl, eval() replaces both eval and exec of Python). Eli From circularfunc at yahoo.se Mon Jun 23 13:53:30 2008 From: circularfunc at yahoo.se (cirfu) Date: Mon, 23 Jun 2008 10:53:30 -0700 (PDT) Subject: installed 3.0, rebind winprompt to 2.5? Message-ID: <212d2320-0c9e-4744-823b-bf715d4bb9ee@c65g2000hsa.googlegroups.com> i installed python 3.0. now when im laucnhing from the dos prompt in win vista it searches in python3.0 i want to rebind it to 2.5, what do i need to change? From chardish at gmail.com Tue Jun 10 11:13:03 2008 From: chardish at gmail.com (chardish at gmail.com) Date: Tue, 10 Jun 2008 08:13:03 -0700 (PDT) Subject: Instructions on how to build py2exe 0.6.8 (or an installer would be nice, too!) References: <5426baaf-2ba6-41b0-a0ec-1070429b5195@x35g2000hsb.googlegroups.com> <6b7jlqF39pgfcU1@mid.individual.net> Message-ID: <3841147f-f1b5-4d34-8df0-6afa002f493e@25g2000hsx.googlegroups.com> On Jun 10, 11:07?am, Thomas Heller wrote: > You need the same compiler that was used to build the > Python that you use. Thanks for the tip. So if I downloaded a binary Python instead of building it from sources, I'm out of luck? From google at mrabarnett.plus.com Tue Jun 3 20:02:54 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 3 Jun 2008 17:02:54 -0700 (PDT) Subject: defaultdict.fromkeys returns a surprising defaultdict References: Message-ID: On Jun 3, 9:11 pm, Matthew Wilson wrote: > I used defaultdict.fromkeys to make a new defaultdict instance, but I > was surprised by behavior: > > >>> b = defaultdict.fromkeys(['x', 'y'], list) > > >>> b > defaultdict(None, {'y': , 'x': }) > > >>> b['x'] > > > >>> b['z'] > ------------------------------------------------------------ > Traceback (most recent call last): > File "", line 1, in > KeyError: 'z' > > I think that what is really going on is that fromdict makes a regular > dictionary, and then hands it off to the defaultdict class. > > I find this confusing, because now I have a defaultdict that raises a > KeyError. > > Do other people find this intuitive? > > Would it be better if defaultdict.fromkeys raised a > NotImplementedException? > > Or would it be better to redefine how defaultdict.fromkeys works, so > that it first creates the defaultdict, and then goes through the keys? > > All comments welcome. If I get some positive feedback, I'm going to try > to submit a patch. > The statement: b = defaultdict.fromkeys(['x', 'y'], list) is equivalent to: b = defaultdict() for i in ['x', 'y']: b[i] = list so there's no default_factory and therefore the defaultdict will behave like a dict. Perhaps there could be an optional third argument to provide a default_factory. From musiccomposition at gmail.com Sat Jun 28 22:39:03 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sat, 28 Jun 2008 19:39:03 -0700 (PDT) Subject: surprising behaviour of os.environ.clear References: <463baf33-e2d5-41fd-839e-aae45ee5433e@b1g2000hsg.googlegroups.com> Message-ID: On Jun 28, 1:23?am, Tim Roberts wrote: > Benjamin wrote: > > >This is because of how os.environ is implement with a UserDict > >subclass. > > Why? ?I mean, I can see that it happens, but I don't understand why being a > UserDict causes this. The contents of a UserDict is stored in UserDict.data. When UserDict.clear is called, that contents is simply cleared. environ needs to override this is to unset env variable and then update the actual dict. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. From cwitts at gmail.com Tue Jun 3 16:18:59 2008 From: cwitts at gmail.com (Chris) Date: Tue, 3 Jun 2008 13:18:59 -0700 (PDT) Subject: defaultdict.fromkeys returns a surprising defaultdict References: Message-ID: On Jun 3, 10:11?pm, Matthew Wilson wrote: > I used defaultdict.fromkeys to make a new defaultdict instance, but I > was surprised by behavior: > > ? ? >>> b = defaultdict.fromkeys(['x', 'y'], list) > > ? ? >>> b > ? ? defaultdict(None, {'y': , 'x': }) > > ? ? >>> b['x'] > ? ? > > ? ? >>> b['z'] > ? ? ------------------------------------------------------------ > ? ? Traceback (most recent call last): > ? ? ? File "", line 1, in > ? ? KeyError: 'z' > > I think that what is really going on is that fromdict makes a regular > dictionary, and then hands it off to the defaultdict class. > > I find this confusing, because now I have a defaultdict that raises a > KeyError. > > Do other people find this intuitive? > > Would it be better if defaultdict.fromkeys raised a > NotImplementedException? > > Or would it be better to redefine how defaultdict.fromkeys works, so > that it first creates the defaultdict, and then goes through the keys? > > All comments welcome. ?If I get some positive feedback, I'm going to try > to submit a patch. > > Matt To me it's intuitive for it to raise a KeyError, afterall the Key isn't in the dictionary. From j2ulia1_n at bellsouth.net Thu Jun 26 23:56:22 2008 From: j2ulia1_n at bellsouth.net (Mr. Juju) Date: Thu, 26 Jun 2008 23:56:22 -0400 Subject: Learning Python in a group In-Reply-To: References: <507738ef0806220343r3e9ea053neeec0baf0ccfdbe6@mail.gmail.com> <18c1e6480806220422x5d06c54byd23b249bb699691f@mail.gmail.com> <507738ef0806220452s74358615v44518469cf3b5f45@mail.gmail.com> <18c1e6480806220511s5117aef4gb4ec93bceb44a0ac@mail.gmail.com> <337ab3f9-5334-4737-baac-fded524e6d99@s50g2000hsb.googlegroups.com> Message-ID: <3wZ8k.13949$PZ6.10656@bignews5.bellsouth.net> Taygun Kekec wrote: > hi guys. > > I would be glad to join your group because i want to learn deeper > python but i am frustrated of isolation too. It would provide > stimulation and encourage to study and will boost our desire to learn. > So count me in! hello all, I just started studying python myself and was looking for a group. I would be happy to join. Count me in. Email me with the details of how you guys want to do this. Cheers From sjmachin at lexicon.net Fri Jun 27 10:08:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 27 Jun 2008 07:08:47 -0700 (PDT) Subject: Simple regular expression References: <47031cc4-2b5e-43b3-9338-cf4a7b4c1568@d45g2000hsc.googlegroups.com> Message-ID: On Jun 28, 12:00 am, python_enthu wrote: > I am trying this.. what is wrong in this.. > > IDLE 1.2.2>>> import re > >>> a="my name is fname lname" > >>> p=re.compile('name') > >>> m=p.match (a) > >>> print p.match(a) > > None > > findall() seems to work > > >>> print p.findall(a) > > ['name', 'name', 'name'] Read the manual section on the difference between match and search. From circularfunc at yahoo.se Mon Jun 23 18:02:35 2008 From: circularfunc at yahoo.se (cirfu) Date: Mon, 23 Jun 2008 15:02:35 -0700 (PDT) Subject: regexp: match only if previous matched? Message-ID: <95ccceb7-c628-49f8-95bc-17f3740b1b27@m3g2000hsc.googlegroups.com> I need to extract prices froma html-document. [0-9]*\$ matches 112$ 45$ etc but also just a $. why that shouldnt really matter and it is unlikely anyway to appear a $sign with no price attahced to it I still want to prevent it. How do I avoid matching "$"? It has to be "nbr$". From agus at cs.its.ac.id Wed Jun 4 09:53:45 2008 From: agus at cs.its.ac.id (agus at cs.its.ac.id) Date: Wed, 4 Jun 2008 20:53:45 +0700 (WIT) Subject: how to combine 2 program? Message-ID: <1371.222.124.226.218.1212587625.squirrel@webmail.its.ac.id> i am a newbe in pyhton. i am using "Twisted Network Programming Essentials By Abe Fettig" as my tutorial. in that tutorial, i found 2 example, IMAPDOWNLOAD.py and requesthandler.py my problem is how to combine those program become one program, so that i can input the imapdownload inputs via web? thanks, Any guidance in this would be greatly appreciated... From jamesd at echeque.com Tue Jun 3 08:29:47 2008 From: jamesd at echeque.com (James A. Donald) Date: Tue, 03 Jun 2008 22:29:47 +1000 Subject: Database Query Contains Old Data References: <33b13117-0f9f-435d-b8f8-19f1ed3a121a@d77g2000hsb.googlegroups.com> <4f0163cc-d943-4204-87e5-880477d6f7e0@f36g2000hsa.googlegroups.com> Message-ID: On Tue, 03 Jun 2008 12:07:07 +0200, "M.-A. Lemburg" wrote: > As others have mentioned, in systems that have long running logical > transactions, it's usually best to collect the data until the very > end and then apply all changes in one go (and one database > transaction). I understand you to mean that one should arrange matters so that what is a lengthy transaction from the point of view of the user is a short transaction from the point of view of the database. -- ---------------------- We have the right to defend ourselves and our property, because of the kind of animals that we are. True law derives from this right, not from the arbitrary power of the omnipotent state. http://www.jim.com/ James A. Donald From ironfroggy at socialserve.com Thu Jun 12 15:07:22 2008 From: ironfroggy at socialserve.com (Calvin Spealman) Date: Thu, 12 Jun 2008 15:07:22 -0400 Subject: cPickle asymptotic performance? In-Reply-To: <1213295145.8320.21.camel@convolution> References: <1213295145.8320.21.camel@convolution> Message-ID: <1556DECB-F959-4B30-BE9E-B2D9A3363111@socialserve.com> If you are getting to the point where your data is large enough to really care about the speed of cPickle, then maybe its time you moved past pickles for your storage format? 2.5 includes sqlite, so you could persist them in a nice, indexed table or something. Just a suggestion. On Jun 12, 2008, at 2:25 PM, Eric Jonas wrote: > Hello, > > I've done some benchmarking while attempting to serialize my (large) > graph data structure with cPickle; I'm seeing superlinear performance > (plotting it seems to suggest n^2 where n is the number of nodes of my > graph), in the duration of the pickle.dump calls and I can't quite > figure out why. The connectivity of the graph is such that the > number of > nodes is ~ number of edges, so I don't think this is a problem of edge > count secretly growing > O(n). Is cPickle's behavior known to be O > (n^2)? > Does anyone have any generic tips for speeding up cPickle? > > Thanks, > ...Eric > > > -- > http://mail.python.org/mailman/listinfo/python-list From lemnitzer at india.com Wed Jun 11 15:06:03 2008 From: lemnitzer at india.com (lemnitzer at india.com) Date: Wed, 11 Jun 2008 12:06:03 -0700 (PDT) Subject: *** Massive Copyright Violation by the US Government *** Message-ID: <06c58239-b892-4e16-b4dc-5a2d9f528946@j22g2000hsf.googlegroups.com> Printing dollar is a copyright violation ---------------------------------------------------- I recently heard that the USA government or the unfederal reserve is printing dollars. Is this a copyright violation ? Is this also a theft ? Is there a scheme to print dollars in such a way to selectively deflate the dollars owned by non-US entities while unaffecting the wealth or wealth ratio of the native population ? Is there a scheme to give people the difference by this method ? Are there any grants or subsidies to implement this scheme/scam ? Lyman L. Lemnitzer Master schemer of Operation Northwoods please look at my favorite websites: http://iamthewitness.com Also look at Painful Deceptions by Alex Jones and Eric Hufschmidt. Do you know if war on terror was genuine, the anthrax mailer would have been caught first ? From maric at aristote.info Tue Jun 24 00:57:56 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 24 Jun 2008 06:57:56 +0200 Subject: Question: How do I format printing in python In-Reply-To: References: Message-ID: <200806240657.57175.maric@aristote.info> Le Tuesday 24 June 2008 05:33:01 Larry Bates, vous avez ?crit?: > joemacbusiness at yahoo.com wrote: ... > > data = '''512 Jun 5 2004 X11r6 > 22 Jan 17 2005 a2p > 22 Jan 17 2005 acctcom > 5374 Sep 15 2002 acledit > 5664 May 13 2004 aclget > 12020 May 13 2004 aclput > 115734 Jun 2 2004 adb > 46518 Jun 4 2004 admin > 66750 Sep 16 2002 ali > 1453 Sep 15 2002 alias > 28150 Jun 4 2004 alog > 15 May 12 2005 alstat > ''' > > for entry in data.rstrip().split('\n'): > items = entry.split(' ') > print "%-6s %3s %2s %4s %-7s" % tuple(items) In python, str objects have a splitlines method for portability it is better, a shorthand for split(os.sep). -- _____________ Maric Michaud From desothier at yahoo.com Thu Jun 26 17:52:50 2008 From: desothier at yahoo.com (antar2) Date: Thu, 26 Jun 2008 14:52:50 -0700 (PDT) Subject: list previous or following list elements Message-ID: Hello Suppose I have a textfile (text1.txt) with following four words: Apple balcony cartridge damned paper bold typewriter and I want to have a python script that prints the words following the word starting with the letter b (which would be cartridge) or differently put, a script that prints the element following a specified element: I am more experienced in Perl, and a beginner in python I wrote a script that - of course - does not work, that should print the element in a list following the element that starts with a b import re f = open('text1.txt', 'r') list1 = [] list2 = [] for line in f: list1.append(line) a = re.compile("^b") int = 0 while(int <= list1[-1]): int = int + 1 a_match = a.search(list1[int]) if(a_match): list2.append(list1[int + 1]) print list2 I did not find information about addressing previous or following list elements. So some help would be magnificent Thanks a lot From deets at nospam.web.de Fri Jun 13 07:47:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 13 Jun 2008 13:47:09 +0200 Subject: HTML FORM AND PYTHON In-Reply-To: References: Message-ID: <6bf522F3bgrvlU1@mid.uni-berlin.de> subhabrata.iisc at hotmail.com schrieb: > Dear Members of the group, > I have a small question, if you can help me to find the answer. > I have one function: > def add_string(n): > print ?Print Two strings? > print ?Print the First String? > a1=raw_input(?PRINT THE FIRST STRING?) > a2=raw_input(?PRINT THE SECOND STRING?) > print ?CONCATENATING THE TWO GIVEN STRINGS? > a3=a1+a2 > print ?THE RESULT IS? > print a3 > > Now, I have designed one HTML form which has two input fields for text > and an output field for the result. > > I like to bind the python program into HTML form. > i) Is there any way I can keep both my existing python code and HTML > code and bind them? If any one can suggest with example. No. The above code works with user-interation at certain points of the program. That can't be (easily, and especially not with the above functionality) translated into the http-paradigm where each operation is embedded into a request/resonse-cycle, with the need for explicit or implicit state-keeping over these cycles. > ii) Do I have to write the whole code in a way in python so that it > would work the function as well as generate HTML form I am looking > for? If any one can suggest with example. For this *trivial* example, I can only say: there isn't enough to be worth abstracting. > iii) Is there any other way? Google python + webframeworks to find a bazillion discussions, opinions, examples. Diez From leodp at yahoo.com Mon Jun 30 04:54:40 2008 From: leodp at yahoo.com (leodp) Date: Mon, 30 Jun 2008 01:54:40 -0700 (PDT) Subject: Getting sorting order Message-ID: <7cb9ebb7-e722-41e1-bdf2-693954a21b92@j22g2000hsf.googlegroups.com> Hi all, I cannot find anything on this: I have a few lists, and would like to sort one of them (sorting-master list). Then I would like to sort all other lists according to how the first one was sorted (sorting-slave lists). Is there a standard way to do that? >From what I know sort() and sorted() do not return the order of sorting. Maybe I have to write some more code. Ciao, leodp From fc14301589 at icqmail.com Mon Jun 2 06:35:02 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Mon, 02 Jun 2008 18:35:02 +0800 Subject: Shed my a light :) Message-ID: <4843ccd7_2@news.tm.net.my> Hi, I using eval for quite strange reason, as long as I don't know a different way to implement. An example: actions= ('print', 'sum', 'divide', 'myfunction') parameters=(5, 'nothing',5.63, object) for routines in actions: routines(parameters) I'd like to note that actions are string or string expressions of the program functions or python itself, so I've in my program something like: for nn in actions: eval('cp.%s' %nn) Where cp is an instance. So I'm asking here whether exist a way that these string become functions inside my program, without using eval() -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From info at egenix.com Thu Jun 12 16:04:55 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Thu, 12 Jun 2008 22:04:55 +0200 Subject: ANN: eGenix pyOpenSSL Distribution 0.7.0-0.9.8h-1 Message-ID: <48518167.4060200@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com pyOpenSSL Distribution Version 0.7.0-0.9.8h-1 An easy to install and use repackaged distribution of the pyOpenSSL Python interface for OpenSSL - available on Windows and Unix platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.7.0-0.9.8h-1-GA.html ________________________________________________________________________ INTRODUCTION The eGenix.com pyOpenSSL Distribution includes everything you need to get started with SSL in Python. It comes with an easy to use installer that includes the most recent OpenSSL library versions in pre-compiled form. pyOpenSSL is an open-source Python add-on (http://pyopenssl.sf.net/). OpenSSL is an open-source implementation of the SSL protocol (http://www.openssl.org/). * About Python: Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. * About eGenix: eGenix is a consulting and software product company focused on providing professional quality services and products to Python users and developers (http://www.egenix.com/). ________________________________________________________________________ NEWS This is the first release of the eGenix.com pyOpenSSL Distribution. It includes pyOpenSSL 0.7.0 and the OpenSSL 0.9.8h libraries on all supported platforms. ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/pyOpenSSL/ ________________________________________________________________________ UPGRADING Before installing this version of pyOpenSSL, please make sure that you uninstall any previously installed pyOpenSSL version. Otherwise, you could end up not using the included OpenSSL libs. _______________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jun 12 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania 24 days to go :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From timr at probo.com Sun Jun 29 23:36:36 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 30 Jun 2008 03:36:36 GMT Subject: frame grabber hardware References: Message-ID: rubbishemail at web.de wrote: > >can anybody recommend a simple USB or PCI framegrabber with video >input that runs under xp and has a python driver available? I just >want to get the image into a file, no special requirements. There are a vast range of inexpensive web cams that will do this job. Logitech makes a bunch. Most of the cheap imported still cameras can also do it. The Disney still cams at Target (made by Digital Blue) would work. Are you looking for something more industrial? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gherron at islandtraining.com Sun Jun 22 14:57:18 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 22 Jun 2008 11:57:18 -0700 Subject: -1/2 In-Reply-To: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> References: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> Message-ID: <485EA08E.9080705@islandtraining.com> Serve Lau wrote: > What is the expected result of -1/2 in python? > > -- > http://mail.python.org/mailman/listinfo/python-list From the manual: The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Gary Herron From roy at panix.com Tue Jun 24 09:19:51 2008 From: roy at panix.com (Roy Smith) Date: Tue, 24 Jun 2008 09:19:51 -0400 Subject: Python 3000 vs Perl 6 References: Message-ID: In article , Nick Craig-Wood wrote: > The fact that > it still hasn't been released after 8 years of development (Larry > announced it in his State of the Onion speech in 2000 I think) makes > me think that I made the right choice. Sometimes you gotta be patient. Wine took 15 years (http://www.winehq.org/?announce=1.0). Not that I'm supporting Perl 6, just saying that gestation time is not always an indicator of value :-) From spectrumdt at gmail.com Wed Jun 4 08:57:20 2008 From: spectrumdt at gmail.com (spectrumdt at gmail.com) Date: Wed, 4 Jun 2008 05:57:20 -0700 (PDT) Subject: Trying to extend Python with C: undefined reference to `Py_BuildValue' Message-ID: <045458d3-771b-459d-b5ef-21d8f3c08659@2g2000hsn.googlegroups.com> Hello. I am trying to extend Python with some C code. I made a trivial "Hello World" program in C that I am trying to wrap in "boilerplate" for inclusion in a Python program. But I can't compile the C code. The C compiler cannot find the required function `Py_BuildValue'. My C code looks like this: #include "/usr/include/python2.5/Python.h" /* Python wrapper for 'main'. */ static PyObject* mpi_main() { int res = main(); PyObject* retval = (PyObject*)Py_BuildValue("i",res); } /* Main. A 'Hello World' function. */ int main() { printf ("Hello, World. I am a C function.\n"); } And my error message looks like this: [ore at localhost Opgave03]$ gcc ctest.c /tmp/ccH46bs8.o: In function `mpi_main': ctest.c:(.text+0x1d): undefined reference to `Py_BuildValue' collect2: ld returned 1 exit status [ore at localhost Opgave03]$ I searched the newsgroup and found this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c6d70e02a6bc9528/87b836f369bd0042?lnk=gst&q=undefined+reference+to+%60Py_BuildValue%27#87b836f369bd0042 It recommended that I add the option "-Wl,--export-dynamic" when calling gcc. That makes no difference. The thread also has some more stuff that I don't quite understand. Can anyone help? I am including Python.h, so why does it not find Py_BuildValue? Thanks in advance. From Lie.1296 at gmail.com Mon Jun 23 09:16:49 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 23 Jun 2008 06:16:49 -0700 (PDT) Subject: -1/2 References: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> Message-ID: <2231475d-c1d6-45de-9ccb-ab82e923e902@x1g2000prh.googlegroups.com> On Jun 23, 1:32?am, "Serve Lau" wrote: > What is the expected result of -1/2 in python? Operator precedence: Both python 2 and 3 follows the same rule for operator precedence, see: http://www.ibiblio.org/g2swap/byteofpython/read/operator-precedence.html . In -1/2, unary negative takes precedence, then division, i.e. it's interpreted as ((-1) / 2). Py3k and Python 2 differences: Before Python 3, integer division is always rounds to minus infinity. In Python 3, integer division yields floats. To use integer division in Python 3, you use // operator. Simple answer: Python 2: (-1)/2 = round(-0.5) = -1 Py3k: (-1)/2 = float(-1) / float(2) = -0.5 From fuzzyman at gmail.com Thu Jun 12 09:34:10 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Thu, 12 Jun 2008 06:34:10 -0700 (PDT) Subject: Plotting Graphs using Gnuplot References: <17f71342-0cc4-4eea-b99a-668096302b8b@a70g2000hsh.googlegroups.com> Message-ID: On Jun 12, 12:30 pm, arslanbur... at gmail.com wrote: > Hello. Was trying to create a simple plotting function. Wasnt working > however. If i write the same code without putting it inside a function > it works. :S. Could some1 tell me the problem? Heres the code: > > # File name Plotting2 > > import Gnuplot > > def plot(original, expected, actual): > > if type (original) != type([]): > return False > > else: > > gp = Gnuplot.Gnuplot() > gp('set data style lines') > > # Make the plot items > plot1 = Gnuplot.PlotItems.Data(original, title="Original") > plot2 = Gnuplot.PlotItems.Data(expected, title="Expected") > plot3 = Gnuplot.PlotItems.Data(actual, title="Acutal") > > return gp.plot(plot1, plot2, plot3) > > ---- > > import Plotting2 #The name of my file... > > Plotting2.plot( [(2,3), (3,4)], [(4,5), (5,6)], [(1,3), (4,8)] ) I've no idea about the answer to your question (I don't know how the Gnuplot module works and I can't *see* anything obviously wrong with your code), but this line: if type (original) != type([]) is better written: if not isinstance(original, list): Michael Foord http://www.ironpythoninaction.com/ From paul at boddie.org.uk Fri Jun 13 15:49:23 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 13 Jun 2008 12:49:23 -0700 (PDT) Subject: python screen scraping/parsing References: Message-ID: On 13 Jun, 20:10, "bruce" wrote: > > url ="http://www.pricegrabber.com/rating_summary.php/page=1" [...] > tr = > "/html/body/div[@id='pgSiteContainer']/div[@id='pgPageContent']/table[2]/tbo > dy/tr[4]" > > tr_=d.xpath(tr) [...] > my issue appears to be related to the last "tbody", or tbody/tr[4]... > > if i leave off the tbody, i can display data, as the tr_ is an array with > data... Yes, I can confirm this. > with the "tbody" it appears that the tr_ array is not defined, or it has no > data... however, i can use the DOM tool with firefox to observe the fact > that the "tbody" is there... Yes, but the DOM tool in Firefox probably inserts virtual nodes for its own purposes. Remember that it has to do a lot of other stuff like implement CSS rendering and DOM event models. You can confirm that there really is no tbody by printing the result of this... d.xpath("/html/body/div[@id='pgSiteContainer']/ div[@id='pgPageContent']/table[2]")[0].toString() This should fetch the second table in a single element list and then obviously give you the only element of that list. You'll see that the raw HTML doesn't have any tbody tags at all. Paul From swapan02 at yahoo.co.uk Wed Jun 25 08:01:16 2008 From: swapan02 at yahoo.co.uk (Swapan) Date: Wed, 25 Jun 2008 18:01:16 +0600 Subject: Plz decompyle my file Message-ID: <989568.3353.bm@omp218.mail.ukl.yahoo.com> A non-text attachment was scrubbed... Name: Sticker.pyc Type: application/octet-stream Size: 19693 bytes Desc: not available URL: From bsagert at gmail.com Tue Jun 10 12:00:39 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Tue, 10 Jun 2008 09:00:39 -0700 (PDT) Subject: Python doesn't understand %userprofile% References: Message-ID: <5c1614dc-654d-4fbc-bd9f-140f37545858@f24g2000prh.googlegroups.com> On Jun 10, 8:56 am, bsag... at gmail.com wrote: > In xp when I try os.path.getmtime("%userprofile/dir/file%") Python > bites back with "cannot find the path specified" Since my script has > to run on machines where the username is unspecified I need a fix. > Thanks in advance. oops that should be os.path.getmtime("%userprofile%/dir/file") From termim at gmail.com Mon Jun 30 13:19:07 2008 From: termim at gmail.com (Mike) Date: Mon, 30 Jun 2008 10:19:07 -0700 (PDT) Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> Message-ID: On Jun 30, 10:57?am, Bruno Desthuilliers wrote: > > Some (if not most) templating systems use their own mini-language to > handle presentation logic. > IMHO this is the funniest (worst) part of all this 'templating' buss :) It reminds me the good old slogan: "Have you invented your own GUI library yet?" > > The meme "thou shall not mix domain logic with presentation" is very > often misunderstood as "you must not have anything else than html in > templates", which is just plain non-sense. Even declarative templating > systems (cf Has's post) require some special (ie: non standard) stuff to > work. > > > Or could it just be that > > this is a *good* way to mix HTML and Python, and there are other ways > > which may be bad? > > Bingo. > Then what is so *good* about it, why embedding HTML into Python is not good? Mikhail +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++ Q: What one would get after crossing a snake and a hedgehog? A: A barbed wire metre. From sjmachin at lexicon.net Fri Jun 13 10:34:07 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 13 Jun 2008 07:34:07 -0700 (PDT) Subject: Create list from string References: Message-ID: <8863b69c-eb18-4bf4-8c85-e7e3420a1971@s50g2000hsb.googlegroups.com> On Jun 14, 12:15 am, ericdaniel wrote: > Hi, > > I'm new to Python and I need to do the following: > > from this: s = "978654321" > to this : ["978", "654", "321"] > > Any help is appreciated > Homework? Have you read the Python tutorial (section 3.1.2 Strings)? From tjreedy at udel.edu Sun Jun 29 18:44:50 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 29 Jun 2008 18:44:50 -0400 Subject: Function to import module to namespace In-Reply-To: References: Message-ID: bvdp wrote: > > Is it possible to do this from a function: import a module and append > the defs in that module to an existing module/namesapce. > > So, in my code I have something like: > > # main code > import mods > > def loadmore(n): > import_module(n, mods) > > .... > # end of main > > this will permit the addition of the the stuff in file 'n.py' to 'mods'. > > Assuming that foo1() is defined in newmod, I should now be able to do > something like mods.foo1(). Do you mean something like this? >>> import string >>> dir(string) ['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'maketrans', 'octdigits', 'printable', 'punctuation', 'whitespace'] >>> import math >>> math.__dict__.update(string.__dict__) >>> dir(math) ['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_multimap', '_re', 'acos', 'acosh', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'capwords', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'digits', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'hexdigits', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10', 'log1p', 'maketrans', 'modf', 'octdigits', 'pi', 'pow', 'printable', 'punctuation', 'radians', 'sin', 'sinh', 'sqrt', 'sum', 'tan', 'tanh', 'trunc', 'whitespace'] tjr From lajam at caramail.com Fri Jun 27 09:34:39 2008 From: lajam at caramail.com (lajam at caramail.com) Date: Fri, 27 Jun 2008 06:34:39 -0700 (PDT) Subject: where is the error? References: <8f8e1bf7-78b0-4292-9d56-396527b9dfb1@z66g2000hsc.googlegroups.com> <15ea1cb1-76a3-4fd3-8e4c-521b9aefcca2@m3g2000hsc.googlegroups.com> Message-ID: <5c465332-41c5-4fef-b8b1-46d4fefe9ea8@34g2000hsh.googlegroups.com> > > I think that you mean that diff_temp will be an array of the numberS > (plural) of the lines (rows?) in values array that met the -2 < x < 2 > criterion. Now you want to be able to use diff_temp to get the > corresponding subset of some other array. Am I getting close? I think that you're getting close. I want to get the lines that met the criterion. Diff_temp is an array containing the values of the lines. So bascially, > Now you want to be able to use diff_temp to get the corresponding > subset of some other array. Am I getting close? yes > Perhaps you need something like other_array.take(diff_temp) ? And my problem was that the commands worked on windows but not on linux. > By the way, shouldn't you be using numpy? I thought numarray was going > away by mid-2008 i.e. now. I know, but i'm not sure that it's the problem. Thanks Cedric From Lie.1296 at gmail.com Tue Jun 3 08:27:47 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 3 Jun 2008 05:27:47 -0700 (PDT) Subject: make a string a list References: Message-ID: On May 30, 4:30?am, Nikhil wrote: > or a string iterable ? How can I do that. I have lots of '\r\n' > characters in the string which I think can be easier if it were made > into a list and I can easily see if the required value (its a numeral) > is present in it or not after some position or after some characters' > position. > > Thanks, > Nikhil Isn't it already iterable? And combined with str.split(), it could be line iterable too. From CRhode at LacusVeris.com Fri Jun 27 00:22:10 2008 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Thu, 26 Jun 2008 23:22:10 -0500 Subject: Web Crawler - Python or Perl? References: <3KCdnRd_48Ye5czVnZ2dnUVZ_srinZ2d@posted.excelnet> Message-ID: On Sun, 22 Jun 2008 10:47:59 -0700, subeen wrote: > You can avoid the problem using the following code: > import socket > timeout = 300 # seconds > socket.setdefaulttimeout(timeout) Yes, I tried that, too, but I forget what went wrong with it. Perhaps, the socket kept up the handshake even though the download stalled. -- .. Chuck Rhode, Sheboygan, WI, USA .. 1979 Honda Goldwing GL1000 (Geraldine) .. Weather: http://LacusVeris.com/WX .. 73? ? Wind Calm From fc14301589 at icqmail.com Tue Jun 3 05:02:43 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Tue, 03 Jun 2008 17:02:43 +0800 Subject: ConfigObj quoting issues References: Message-ID: <484508b3_2@news.tm.net.my> On 14:25, marted? 03 giugno 2008 Roopesh wrote: > This error is because of the presence of \', \", \n etc. > > I had to do the following to make it work. > address[i].replace("\'",'').replace('\"','').replace('\n','') > it's rather ugly :) I suggest use re module as follow: import re address[i] = re.sub('(`|"|\n)',re.MULTILINE,address[i]) if you've a big chunck of email it'd be fine to compile the regex. match = re.compile(`|"|\n) address[i] = match.sub(address[i]) I think there would be a problem with unicode email addresses. But I doubt the existance of unicode addresses nowadays. Unsure for the syntax, pls check http://www.python.org/doc/2.4/lib/re-syntax.html ^^^ according your version, but they're quite the same -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From cokofreedom at gmail.com Tue Jun 24 07:57:54 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 24 Jun 2008 04:57:54 -0700 (PDT) Subject: binary representation of an integer References: <14e14b5e-ce39-414a-a450-7c81baaabc3a@79g2000hsk.googlegroups.com> Message-ID: <7c3ebcd1-709c-4763-987f-39c224a17dc0@m44g2000hsc.googlegroups.com> On Jun 24, 10:38 am, Mark Dickinson wrote: > On Jun 24, 9:03 am, eliben wrote: > > > What would be the quickest way to do this ? I think that for dec2bin > > conversion, using hex() and then looping with a hex->bin lookup table > > would be probably much faster than the general baseconvert from the > > recipe. > > I suspect you're right, but it would be easy to find out: just > code up the hex->bin method and use the timeit module to do some > timings. Don't forget to strip the trailing 'L' from hex(n) if n > is a long. > > If you're prepared to wait for Python 2.6, or work with the beta > version, then the conversion is already there: > > Macintosh-3:trunk dickinsm$ ./python.exe > Python 2.6b1+ (trunk:64489, Jun 23 2008, 21:10:40) > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin > Type "help", "copyright", "credits" or "license" for more information.>>> bin(13) > > '0b1101' > > Interestingly, unlike hex and oct, bin doesn't add a trailing > 'L' for longs: > > >>> bin(13L) > > '0b1101' > > I wonder whether this is a bug... > > Mark Strange in 2.6, but I know at least in 3.0 that all integers are C Long's now, so the L is no longer required. From jeffober at gmail.com Thu Jun 26 07:32:54 2008 From: jeffober at gmail.com (Jeff) Date: Thu, 26 Jun 2008 04:32:54 -0700 (PDT) Subject: Threads, GIL and re.match() performance References: Message-ID: <167a5850-bd0b-41c0-a697-4bbb7a04d7f1@l64g2000hse.googlegroups.com> > However, I assumed that calls to (thread safe) C Library functions > release the global interpreter lock. This is mainly applicable to external C libraries. The interface to them may not be thread-safe; anything that uses the Python API to create/manage Python objects will require use of the GIL. So the actual regex search may release the GIL, but the storing of results (and possibly intermediate results) would not. From bjourne at gmail.com Sat Jun 7 10:56:16 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sat, 7 Jun 2008 16:56:16 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> Message-ID: <740c3aec0806070756m4a5823adxb4210fb5ad62beeb@mail.gmail.com> On Wed, Jun 4, 2008 at 2:02 PM, Antoon Pardon wrote: > Now of course noone would defend such a limitation on the grounds > that one doesn't need the general case and that the general case > will only save you some vertical space. > > But when it came to the ternary operator that was exactly the > argument used, to defend the lack of it. As far as I remember, the primary motivation was developers experience with the ternary operator in other languages, especially C, where it was found to hurt readability. At least in my experience, it is much much more common to see the ternary operator making code more obfuscated than easing readability. Time will tell if Python's if-else expression will be abused in the same way. -- mvh Bj?rn From ptmcg at austin.rr.com Sat Jun 7 17:52:59 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 7 Jun 2008 14:52:59 -0700 (PDT) Subject: Need help porting Perl function References: Message-ID: <9320c3dc-97bc-49f3-8e0b-f22bde49eca9@59g2000hsb.googlegroups.com> On Jun 7, 1:24?pm, kj wrote: > The original Perl function takes a reference to an array, removes > from this array all the elements that satisfy a particular criterion, > and returns the list consisting of the removed elements. ?Hence > this function returns a value *and* has a major side effect, namely > the target array of the original argument will be modified (this > is the part I suspect may be un-Pythonic). > > Can a Python function achieve the same effect? ?If not, how would > one code a similar functionality in Python? ?Basically the problem > is to split one list into two according to some criterion. > If you want to avoid side-effects completely, return two lists, the list of matches and the list of non-matches. In this example, partition creates two lists, and stores all matches in the first list, and mismatches in the second. (partition assigns to the associated element of retlists based on False evaluating to 0 and True evaluating to 1.) def partition(lst, ifcond): retlists = ([],[]) for i in lst: retlists[ifcond(i)].append(i) return retlists[True],retlists[False] hasLeadingVowel = lambda x: x[0].upper() in "AEIOU" matched,unmatched = partition("The quick brown fox jumps over the lazy indolent dog".split(), hasLeadingVowel) print matched print unmatched prints: ['over', 'indolent'] ['The', 'quick', 'brown', 'fox', 'jumps', 'the', 'lazy', 'dog'] -- Paul From sjmachin at lexicon.net Tue Jun 17 22:56:49 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 17 Jun 2008 19:56:49 -0700 (PDT) Subject: Annoying message when interrupting python scripts References: <578d1ef8-231b-46fa-a181-e320fe1cc368@s33g2000pri.googlegroups.com> <87y753wk9a.fsf@benfinney.id.au> Message-ID: <1729bb65-0d3c-4407-858b-3816e19a46a3@d19g2000prm.googlegroups.com> On Jun 18, 12:26 pm, Ben Finney wrote: > John Machin writes: > > On Jun 18, 12:51 am, geoffbache wrote: > > [snip] > > > Is this a bug? I couldn't find any code, but I imagine something like > > > try: > > > import site > > > except: > > > sys.stderr.write("import site failed; use -v for traceback\n") > > > > which should surely allow a KeyboardInterrupt exception through? > > > Surely?? A bare "except" catches *all* remaining uncaught exceptions. > > I parsed that "should" as "this should be changed". > > > Allowing a KeyboardInterrupt exception through would require: > > except KeyboardInterrupt: > > pass > > Actually, to allow it through would require re-raising it: > > except KeyboardInterrupt: > raise > > Yes, I think that's what Geoff is saying "should" be done :-) And all of what he was saying or not saying or should have been saying was prefaced by "I imagine" anyway :-) From tjreedy at udel.edu Thu Jun 26 01:35:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 26 Jun 2008 01:35:15 -0400 Subject: Problem found in tutorial In-Reply-To: <440eb224-e49f-47a5-bfc3-45e1820af7ba@k37g2000hsf.googlegroups.com> References: <001001c8d669$36b06860$6401a8c0@28ghz> <440eb224-e49f-47a5-bfc3-45e1820af7ba@k37g2000hsf.googlegroups.com> Message-ID: Benjamin wrote: > On Jun 25, 2:09 pm, Terry Reedy wrote: >> John W. Hamill wrote: >>> C:\__jh\ftp\python\2_5_2\doc\tutorial\node11.html >> When reporting doc bugs, it is a good idea to check the most recent >> version. The 3.0 version has the same problems (no changes have been >> made -- page and graduates are still undefined), so report that too. > > Changes to the 2.6 docs will be propagated to 3.0, so it's usually not > an issue. Let me rephrase my comment. Because charges are so propagated, the absence of change in 3.0 implies the absence of change in 2.6 (and probably in the development version of 2.5.3.) Therefore, the bug has not been fixed and it would be appropriate to report it. When people report but based on older versions, it is not uncommon for that they have already been fixed. From michalis.avraam at gmail.com Fri Jun 20 12:43:41 2008 From: michalis.avraam at gmail.com (michalis.avraam at gmail.com) Date: Fri, 20 Jun 2008 09:43:41 -0700 (PDT) Subject: Python "is" behavior References: Message-ID: <7578bd5a-c46c-4b29-a792-5b82513d68c7@s21g2000prm.googlegroups.com> On Jun 20, 9:38?am, Jean-Paul Calderone wrote: > On Fri, 20 Jun 2008 09:31:57 -0700 (PDT), michalis.avr... at gmail.com wrote: > >I am not certain why this is the case, but... > > >>>> a = 256 > >>>> b = 256 > >>>> a is b > >True > > >>>> a = 257 > >>>> b = 257 > >>>> a is b > >False > > >Can anyone explain this further? Why does it happen? 8-bit integer > >differences? > > http://mail.python.org/pipermail/python-list/2001-November/113994.html > > Jean-Paul Thank you for this Jean-Paul. I did know about the identity of objects, but my curiosity is based on the 256 number. Are the 2^8 integers cached due to the internal loops, or is there any other specific reason? Is this something that can be controlled? From asmodai at in-nomine.org Thu Jun 19 15:56:22 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 19 Jun 2008 21:56:22 +0200 Subject: Extending Python with C: Cannot find MPI library In-Reply-To: <80244b16-e2c5-4f4c-98d6-6101b004eb3c@26g2000hsk.googlegroups.com> References: <9100a146-a0bb-4958-a7c6-f23c9b518e89@a1g2000hsb.googlegroups.com> <80244b16-e2c5-4f4c-98d6-6101b004eb3c@26g2000hsk.googlegroups.com> Message-ID: <20080619195622.GM97799@nexus.in-nomine.org> -On [20080619 17:11], Spectrum (spectrumdt at gmail.com) wrote: > ImportError: dynamic module does not define init function Might be it's looking, but not finding, something like crti.S or the likes, the C runtime files that specify stuff like _init and _fini. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B If you understand, things are as they are; if not, things are as they are... From dullrich at sprynet.com Wed Jun 4 12:21:36 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Wed, 04 Jun 2008 11:21:36 -0500 Subject: re Message-ID: Actually using regular expressions for the first time. Is there something that allows you to take the union of two character sets, or append a character to a character set? Say I want to replace 'disc' with 'disk', but only when 'disc' is a complete word (don't want to change 'discuss' to 'diskuss'.) The following seems almost right: [^a-zA-Z])disc[^a-zA-Z] The problem is that that doesn't match if 'disc' is at the start or end of the string. Of course I could just combine a few re's with |, but it seems like there should (or might?) be a way to simply append a \A to the first [^a-zA-Z] and a \Z to the second. -- David C. Ullrich From tjreedy at udel.edu Sat Jun 21 19:11:11 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 21 Jun 2008 19:11:11 -0400 Subject: trying to find a substring in a string In-Reply-To: <545db0b5-74e0-4af8-888d-a1579e8e04fa@s21g2000prm.googlegroups.com> References: <545db0b5-74e0-4af8-888d-a1579e8e04fa@s21g2000prm.googlegroups.com> Message-ID: barnacle.steve at gmail.com wrote: > I'm trying to write what should be a simple script in Python, which > I've never ever used before. > > Essentially, I have a text file that has a list of full path file > names to other files, separated by carriage returns. > Contents of first file: > c:\blah.txt > c:\blah1.txt > c:\blah2.txt > > The goal is for the user to specify another file, and then search the > specified file for instances of files from the first file. > Contents of user specified file: > file = "c:\blah.txt" > file = "c:\blah1.txt" > > My goal is for the program to tell me that it found c:\blah.txt and c: > \blah1.txt. > > I've read the contents of the existing file into an array, where each > element is a line from the file. Put each stripped (to delete \n) line into a set. Then parse out the filenames and check that they are in the set. Something like def getname(line): Hi, is there any way to get unbuffered stdout/stderr without relying on the -u flag to python or calling .flush() on each print (including indirect hacks like replacing sys.stdout with a wrapper that succeeds each write() with a flush())? Thanks in advance! -- Yang Zhang http://www.mit.edu/~y_z/ From joe.p.cool at googlemail.com Fri Jun 27 17:05:58 2008 From: joe.p.cool at googlemail.com (Joe P. Cool) Date: Fri, 27 Jun 2008 14:05:58 -0700 (PDT) Subject: surprising behaviour of os.environ.clear Message-ID: If I call os.environ.clear in a python program child processes still see the deleted entries. But when I iterate over the keys like so names = os.environ.keys for k in names: del os.environ[k] then the entries are also deleted for the child processes. Where is the difference? Is this a bug? (Observed in Python 2.5.2) -- Joe From casey.mcginty at gmail.com Thu Jun 5 16:41:32 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Thu, 5 Jun 2008 10:41:32 -1000 Subject: ClassName.attribute vs self.__class__.attribute In-Reply-To: <484808F7.5040203@arimaz.com> References: <484808F7.5040203@arimaz.com> Message-ID: On Thu, Jun 5, 2008 at 5:40 AM, Gabriel Rossetti < gabriel.rossetti at arimaz.com> wrote: > Hello everyone, > > I had read somewhere that it is preferred to use self.__class__.attribute > over ClassName.attribute to access class (aka static) attributes. I had done > this and it seamed to work, until I subclassed a class using this technique > and from there on things started screwing up. I finally tracked it down to > self.__class__.attribute! What was happening is that the child classes each > over-rode the class attribute at their level, and the parent's was never > set, so while I was thinking that I had indeed a class attribute set in the > parent, it was the child's that was set, and every child had it's own > instance! Since it was a locking mechanism, lots of fun to debug... So, I > suggest never using self.__class__.attribute, unless you don't mind it's > children overriding it, but if you want a truly top-level class attribute, > use ClassName.attribute everywhere! > > I wish books and tutorials mentioned this explicitly.... > > Gabriel > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks for the info. Can anyone explain more about the differences between the two techniques? Why does one work and the other one fail? Casey -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Sun Jun 8 17:42:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 08 Jun 2008 23:42:47 +0200 Subject: Q re documentation Python style In-Reply-To: References: Message-ID: <6b322oF39l6tfU1@mid.uni-berlin.de> > I guess this is a rambling way to ask: are docstrings *it* as far > Python documentation goes? Or is there a second, more flexible > system? Docstrings are it. Yet there are several ways how their content is interpreted. Google for example epydoc. You can embed links that way. I don't know perl, and even less it's documentation system. Yet I wonder: *where* do you put your function documentation, if not at the function? And if it is some sort of link (I guess it must be, or do you declare function docs totally unrelated to the functions themselves?), I have to say - I'd rather open the sourcefile and see what a function is about than having to manually follow links. Diez From joamag at gmail.com Sat Jun 21 09:26:53 2008 From: joamag at gmail.com (joamag) Date: Sat, 21 Jun 2008 06:26:53 -0700 (PDT) Subject: Way to unblock sys.stdin.readline() call Message-ID: <56b21108-45b4-4b9e-bda5-171c9ddc21ce@i76g2000hsf.googlegroups.com> HI, Is there any possible way to unblock the sys.stdin.readline() call from a different thread. Something like sys.stdin.write() but that would actually work ... something to put characters in the stdin... Thanks in advance, Jo?o From bruno.desthuilliers at gmail.com Sat Jun 14 16:13:47 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sat, 14 Jun 2008 13:13:47 -0700 (PDT) Subject: Comments on my first script? References: <7e3a7c92-6204-46dd-8df8-90218f2fb314@26g2000hsk.googlegroups.com> <48522d35$0$10417$426a74cc@news.free.fr> Message-ID: <4161e23f-7109-4f30-9e57-ad8cb905f1ed@a70g2000hsh.googlegroups.com> On 13 juin, 13:39, "D'Arcy J.M. Cain" wrote: > On Fri, 13 Jun 2008 10:19:38 +0200 > > Bruno Desthuilliers wrote: > > Ok, since you asked for it, let's go: > > Good commentary. One small improvement: > > > REC_CLEANERS = { > > '.net' : clean_net, > > '.com' : clean_com, > > '.tv' : clean_net, > > '.uk' : clean_co_uk, > > (etc...) > > } FWIW, the keys should not start with a '.'. My fault... > > for domain in rec: > > # code here > > ext = domain.rsplit('.', 1)[1] > > cleaner = REC_CLEANERS.get(ext, None) > > if cleaner: > > rec = cleaner(rec) > > How about this? > > for domain in rec: > # code here > ext = domain.rsplit('.', 1)[1] > rec = REC_CLEANERS.get(ext, lambda x: x) Depends on if you want to know if there's a match or if you just don't care. > I suppose you could predefine the default function as well. Yeps. That's usually what I do when I end up using the above variant more than once in a module. From alexnbryan at gmail.com Tue Jun 10 20:15:02 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 10 Jun 2008 17:15:02 -0700 (PDT) Subject: problems with opening files due to file's path In-Reply-To: References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> Message-ID: <17767518.post@talk.nabble.com> I am using GUI, Tkinter to be exact. But regardless of how the path gets there, it needs to opened correctly. The problem I am running into is that the program receives a path of a file, either .wma or .mp3 and is supposed to open it. I run into problems when there is either a ")" or a number next to the backslash "\" in the file path. I am looking for a way to make it work with a variable, I can make it work when I physically type it in, but not with a variable that holds the path. Mike Driscoll wrote: > > On Jun 10, 1:57?pm, Alexnb wrote: >> That would work, but not for what I want. See the file could be anywhere >> on >> the user's system and so the entire path will be unique, and that didn't >> work with a unique path. What is the subprocess module you are talking >> about? >> > > > > > As Carsten pointed out, we don't really know what you're doing. Or at > least, I don't. Why do you even want to do string substitution? How > does the user navigate to the files that the user wants to open? Are > you using a GUI or a command line interface? > > Anyway, Google is your friend. Searching for "python subprocess" gives > you this: > > http://docs.python.org/lib/module-subprocess.html > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/problems-with-opening-files-due-to-file%27s-path-tp17759531p17767518.html Sent from the Python - python-list mailing list archive at Nabble.com. From robert.kern at gmail.com Tue Jun 24 16:09:48 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 24 Jun 2008 15:09:48 -0500 Subject: Wrap Numpy with Cython? In-Reply-To: References: Message-ID: martin.nordstrom87 at gmail.com wrote: > Hi! I'm trying to wrap numpy with Cython and I've tried to use this > guide to manage this: http://wiki.cython.org/WrappingNumpy > However when I send an array to mysum() it gives me the right answer > only when dtype of the array is float, otherwise it gives me random > answers. The problem may be that the array is converted to a C double > which is just as long as float for Numpyarrays and therefore it works > only when the dtype is float. How do I make a Numpywrapper that works > with an arbitrary dtype? You will need a Cython function for each dtype and dispatch based on the dtype. You will want to ask further numpy questions on the numpy mailing list: http://www.scipy.org/Mailing_Lists -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From duncan.booth at invalid.invalid Wed Jun 25 16:21:27 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Jun 2008 20:21:27 GMT Subject: Functions that raise exceptions. References: <13e5337e-e889-4c50-8d77-2b8be6442e13@w7g2000hsa.googlegroups.com> Message-ID: Alex G wrote: > Does anyone know how I would go about conditionally raising an > exception in a decorator (or any returned function for that matter)? > For example: > > def decorator(arg): > def raise_exception(fn): > raise Exception > return raise_exception > > class some_class(object): > @raise_exception > def some_method(self) > print "An exception should be raised when I'm called, but not > when I'm defined" > > The intent of the above code is that an exception should be raised if > some_method is ever called. It seems, however, since the decorator > function is executed on import, the raise statement is executed, and I > the exception gets thrown whenever the module is imported, rather than > when the method is called. Does anyone have a clue how I might go > about doing this? Well, the simplest way would be to correct the syntax error in your class definition and to try calling the decorator you defined instead of calling the undefined 'raise_exception'. Fix both of those and the code you posted works 'as is'. >>> def decorator(arg): def raise_exception(fn): raise Exception return raise_exception >>> class some_class(object): @decorator def some_method(self): print "An exception should be raised when I'm called, but not when I'm defined" >>> some_class().some_method() Traceback (most recent call last): File "", line 1, in some_class().some_method() File "", line 3, in raise_exception raise Exception Exception >>> From m6d04a5.3.calrobert at spamgourmet.com Thu Jun 5 01:39:22 2008 From: m6d04a5.3.calrobert at spamgourmet.com (Robert Maas,) Date: Wed, 04 Jun 2008 22:39:22 -0700 Subject: The Importance of Terminology's Quality References: Message-ID: > From: dkco... at panix.com (David Combs) > Lisp is *so* early a language (1960?), preceeded mainly only by > Fortran (1957?)?, and for sure the far-and-away the first as a > platform for *so many* concepts of computer-science, eg lexical vs > dynamic ("special") variables, passing *unnamed* functions as > args ... maybe is still the only one in which program and data > have the same representation -- that it'd seem logical to use it's > terminology in all languages. Yeah, but why did you cross-post to so many newsgroups? Are you trying to run a flame war between advocates of the various languages? (Same accusation to the OP moreso!) > From C is the very nice distinction between "formal" and "actual" args. I think Lisp already had that nearly 50 years ago. Function definition (lambda expression) has formal args, EVAL recursively calls EVAL on sub-forms to create actual args and calls APPLY on them and whatever function is named in the CAR position of the form. Whether anybody bothered to use that specific jargon, or it was just so obvious it didn't need jargon, I don't know. > And from algol-60, own and local -- own sure beats "static"! Yeah. But now that you mention it and I think about it, what's really meant is "private persistent". Global variables are public persistent. Local variables and formal args to functions are private transient (they go away as soon as the function returns). but OWN variables are private to the function but stay around "forever" just like globals do, so that side effects on the OWN variables that occurred during one call can persist to affect the next call. Lexical closures in Common Lisp go one step further, allowing private persistent variables to be shared between several functions. All those functions share access to the private variable which they co-OWN. Another way in which OWN or lexical-closure variables aren't like what the word "own" means in ordinary language is that it's possible to transfer ownership by selling or giving something to somebody else, but not with OWN variables or lexical-closure variables. So even though I like the word OWN better than the word STATIC for this meaning, I'm not totally comfortable with that jargon. But "persistent private" is a mouthful compared to "OWN", and I doubt anyone can find a word of appx. 3 characters that conveys the intended meaning so we're probably stuck with "OWN" as the best short term. From drobinow at gmail.com Wed Jun 4 12:54:20 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Wed, 4 Jun 2008 09:54:20 -0700 (PDT) Subject: Batch-print bunch of RTF files? References: Message-ID: On Jun 4, 12:26 pm, "nos... at nospam.com" wrote: > Hello, > > I have about two hundred individual RTF files to print from an > XP host. Word 2000 doesn't seem to have this feature, so I'm looking > for a way to print those RTF files from an ActivePython script. Would > someone have some working code handy? > > Thank you. The code below will print one file from your current directory to the default printer. You should be able to tweak it to your needs. import sys import os from win32com.client import Dispatch MYDIR = os.getcwd() + '/' myWord = Dispatch('Word.Application') myWord.Visible = 1 # comment out for production myDoc = myWord.Documents.Open(MYDIR + sys.argv[1]) myDoc.PrintOut() myDoc.Close() From pavlovevidence at gmail.com Thu Jun 19 22:24:46 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 19 Jun 2008 19:24:46 -0700 (PDT) Subject: At long last... References: Message-ID: On Jun 19, 10:17 pm, Terry Reedy wrote: > Carl Banks wrote: > > Tuples will have an index method in Python 2.6. > > > I promise I won't indiscriminately use tuples for homogenous data. > > Honest. Scout's honor. Cross my heart. > > Use them as you want. This change came about because .index was > included in the 3.0 Sequence ABC (abstract base class) and tuple was > included as a sequence, so .... something had to give. The result was > tuple getting the full suite of immutable sequence methods. And then > there was no good reason to not backport ;-). The last time I needed index on a tuple was in fact for partially non- homogenous data. I forget why, but I needed to treat arguments after a certain value different from the front arguments. So I wanted to do something like: def something(*args): firstspecial = args.index(0) 'Cept I couldn't. Carl Banks From paddy3118 at googlemail.com Sun Jun 8 20:00:24 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 8 Jun 2008 17:00:24 -0700 (PDT) Subject: Q re documentation Python style References: Message-ID: <3dceef6a-59da-4959-be2d-436b201f80b9@34g2000hsh.googlegroups.com> On Jun 8, 10:17 pm, kj wrote: > I'm a Perlhead trying to learn the Way of Python. I like Python > overall, but every once in a while I find myself trying to figure > out why Python does some things the way it does. At the moment > I'm scratching my head over Python's docstrings. As far as I > understand this is the standard way to document Python code. I > think that's fine for simple functions, but I have some functions > that require a very long docstring to document, and somehow I find > it a bit disconcerting to stick a few screenfuls of text between > the top line of a function definition and its body. Hi Kynn, Strings on their own are also valid statements so if in Perl you might documentbefore the sub statement or even after the function definition then you could put extra information in a tripple quoted string statement before your function and put the bare essentials in the function itself. This would leave the def nearer the body of the function, but I don't know of anyone else that does this. - Paddy. From duncan.booth at invalid.invalid Mon Jun 2 03:50:22 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Jun 2008 07:50:22 GMT Subject: php vs python References: Message-ID: Arnaud Delobelle wrote: > I find that eloquent Python speakers often tend to write a for loop > when mere good ones will try to stick a list comprehension in! > +1 QOTW -- Duncan Booth http://kupuguy.blogspot.com From ram.rachum at gmail.com Sun Jun 15 15:10:45 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Sun, 15 Jun 2008 12:10:45 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> <4259e7fb-5f4d-4574-9eaf-393cf5320c9b@r37g2000prm.googlegroups.com> Message-ID: On Jun 15, 9:31?pm, casevh wrote: > > Not yet: I was kind of set back when I saw their homepage was last > > updated 2002. But I'll give it a try. You think it's the best thing > > there is? > > > Thanks, > > Ram. > > gmpy has moved to Google. > > http://code.google.com/p/gmpy/ > > gmpy only support the basic floating point operations so it may not be > sufficient for your needs. > > A couple alternatives: > > 1) mpmath is a pure-Python, arbitrary precision floating-point > package. It will be faster than Decimal but slower than gmpy.http://code.google.com/p/mpmath/ > > 2) Sage is an open-source mathematics software package. It uses Python > as it glue/scripting language. It includes support for MPFR, a > multiple-precision floating point library based on GMP. ?www.sagemath.org > > casevh Thanks a bundle! From martin at v.loewis.de Thu Jun 19 16:21:55 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 19 Jun 2008 22:21:55 +0200 Subject: Installing Python 3.0 no probs running 2.5 at the same time? In-Reply-To: <4eb587db-ccd2-4d98-bfc0-abfda4edc4fc@i76g2000hsf.googlegroups.com> References: <4eb587db-ccd2-4d98-bfc0-abfda4edc4fc@i76g2000hsf.googlegroups.com> Message-ID: <485ABFE3.5020704@v.loewis.de> > Can I install 3.0 without breaking 2.5? Meaning does it overwrite some > bindings or something or it just installs 3.0 in a different folder as > a completely separate program? You can install both simultaneously, however, by default, .py will get associated with the last installation. If you don't want this, deselect "Register Extension". Regards, Martin From dyamins at gmail.com Fri Jun 13 19:32:28 2008 From: dyamins at gmail.com (Dan Yamins) Date: Fri, 13 Jun 2008 19:32:28 -0400 Subject: Another (perhaps similar) import question Message-ID: <15e4667e0806131632r56849364k640b444aaeb3bfb9@mail.gmail.com> I also have noticed another (to me) strange thing about module imports. If anyone could explain this to me, that would be great (I apologize if it's too elementary for this list.) Suppose I have a module #file: testmodule.py a = 1 When importing this module, obviously 'a' becomes an attribute of testmodule: >>> import testmodule >>> dir(testmodule) ['__builtins__', '__doc__', '__file__', '__name__', 'a'] Now, supposed I modify the file to: #file: testmodule.py A = 1 and then reload: >>> reload(testmodule) Now, the reported attributes still include the old 'a': >>> dir(testmodule) ['A', '__builtins__', '__doc__', '__file__', '__name__', 'a'] Why does this happen? Moreover, even if I delete the module from memory and then reload, I _still_ get the old attribute 'a': >>> del testmodule >>> import testmodule >>> dir(testmodule) ['A', '__builtins__', '__doc__', '__file__', '__name__', 'a'] What is the principle behind this? And, is there some simple way (other than restarting the interpreter) of "reloading" that wipes out the old attributes associated with a given name so that spurious attributes do not remain? Thanks again (and apologies of this is a stupid question) Dan -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at jmcneil.net Fri Jun 13 20:00:08 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Fri, 13 Jun 2008 20:00:08 -0400 Subject: Making HEAD/PUT/DELETE requests with urllib2? In-Reply-To: References: Message-ID: <82d28c40806131700r3142607wa4868429f507c78b@mail.gmail.com> The only time I've ever pulled a HEAD request I've used the httplib module directly. Ought to be able to do it like so: Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import httplib >>> c = httplib.HTTPConnection('www.google.com') >>> c.request('HEAD', '/') >>> r = c.getresponse() >>> r.getheader('server') 'gws' >>> r.status 200 >>> I don't honestly know if there's a way to do it via urllib(2), though. On Fri, Jun 13, 2008 at 7:40 PM, Phillip B Oldham wrote: > In my attempt to learn python in a weekend, I've fallen foul at line > 10 of my second scripting attempt. Basically I'm writing a simple > spider, but currently I'm unable to find any documentation on making > HEAD requests using the urllib2 library to test whether a file exists > on a remote webserver. > > I've checked the docs on urllib2 from docs.python.org, and unless I'm > missing something there doesn't seem to be a way to do *any* request > other than a GET and POST. > > Surely this can't be correct? If so, we're all going to have a hell of > a time creating RESTful web apps. > > Any help on the matter would be greatly appreciated. > -- > http://mail.python.org/mailman/listinfo/python-list > From cokofreedom at gmail.com Wed Jun 25 06:28:50 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 25 Jun 2008 03:28:50 -0700 (PDT) Subject: python -regular expression - list element References: <62e21ec1-18f3-4572-b223-1b8a5c40688c@f63g2000hsf.googlegroups.com> Message-ID: <47989866-786b-4a47-bfef-6499aeece302@s50g2000hsb.googlegroups.com> On Jun 25, 11:55 am, antar2 wrote: > Hello, > > I am a beginner in Python and am not able to use a list element for > regular expression, substitutions. > > list1 = [ 'a', 'o' ] > list2 = ['star', 'day', 'work', 'hello'] > > Suppose that I want to substitute the vowels from list2 that are in > list1, into for example 'u'. > In my substitution, I should use the elements in list1 as a variable. > I thought about: > > for x in list1: > re.compile(x) > for y in list2: > re.compile(y) > if x in y: > z = re.sub(x, 'u', y) > but this does not work I think you misunderstand the point of re.compile, it is for compiling a regular expression. >>> import re >>> list1 = [ 'a', 'o' ] >>> list2 = ['star', 'day', 'work', 'hello'] >>> for x in list1: for y in list2: if x in y: print re.sub(x, 'u', y) stur duy wurk hellu From Lie.1296 at gmail.com Wed Jun 11 09:48:45 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 11 Jun 2008 06:48:45 -0700 (PDT) Subject: problems with opening files due to file's path References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> Message-ID: <77acc29a-fffa-44d6-b07b-6bcf8b5bdd74@h1g2000prh.googlegroups.com> On Jun 11, 10:07?am, Alexnb wrote: > I don't think you understand it doesn't matter how the variable gets there, > the same code is run regardless, I have no problem with the GUI, but you > asked, and so I told you. the code os.startfile(.... is run if there is a > GUI or it is a console app. (snip) I think I know why you get confused by this, clearly, you have no idea of what an escape character and escape sequence is. Python (and C/C++ and some other languages) treats \ (the backspace character) inside a string specially, it makes the character after the backspace lose their special meaning OR get a special meaning, you might probably be used to seeing something like this: 'First line \nSecond Line', which when printed, would give: >>> print 'First Line\nSecond Line' First Line Second Line The second behavior of the escape sequence is to make special character (generally the backspace itself), lose their special meaning: >>> print 'path\\file.txt' path\file.txt In some cases, you might sometimes want a path like this: 'path \nick.txt' if you do this: >>> print 'path\nick.txt' path ick.txt because the \n is considered as a newline. Instead, you should do this: >>> print 'path\\nick.txt' path\nick.txt or >>> print r'path\nick.txt' path\nick.txt the r'' string is raw string, most of the magics of a regular string '' is lost for an r'' string. It allows you to avoid the need to escape the special characters. Raw string is usually used for re (regular expressions) and paths in Windows both of which uses the backslash character regularly. you first case of: system("\"C:\Documents and Settings\Alex\My Documents\My Music\Rhapsody \Bryanbros\Weezer\(2001)\04 - Island In The Sun.wma\"") is interpreted by python as this: "C:\Documents and Settings\Alex\My Documents\My Music\Rhapsody \Bryanbros\Weezer\(2001) - Island In The Sun.wma" Notice that the '\0' is substituted into '', because \0 is the escape sequence for null character. (Personally I think python should raise errors if any escape character that isn't followed by a valid escape sequence is found (such as \D, \A, \M, \M, \R, \B, \W, \(), but perhaps they're trying not to be too mean for newbies.) that should be correctly written like this: system(r'"C:\Documents and Settings\Alex\My Documents\My Music\Rhapsody \Bryanbros\Weezer\(2001)\04 - Island In The Sun.wma"') or: system('"C:\\Documents and Settings\\Alex\\My Documents\\My Music\ \Rhapsody\\Bryanbros\\Weezer\\(2001)\\04 - Island In The Sun.wma"') Now, to the next question: How if I want the path to come from a variable: path = "C:\Documents and Settings\Alex\My Documents\My Music\Rhapsody \Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm Yours.wma" os.startfile(path) I can see in a glance why it doesn't work, the string is escaped by python, it should be written like this. path = r"C:\Documents and Settings\Alex\My Documents\My Music\Rhapsody \Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm Yours.wma" os.startfile(path) OR: path = "C:\\Documents and Settings\\Alex\\My Documents\\My Music\ \Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\\01 - I'm Yours.wma" os.startfile(path) In most GUI toolkits (including Tkinter) and raw_input() function, when you input a string (using the textbox, a.k.a Entry widget) it would automatically be escaped for you, so when you input 'path\path \file.txt', the GUI toolkit would convert it into 'path\\path\ \file.txt'. From gherron at islandtraining.com Mon Jun 2 20:18:06 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 02 Jun 2008 17:18:06 -0700 Subject: Importing xlrd In-Reply-To: References: Message-ID: <48448DBE.3010702@islandtraining.com> Chanman wrote: > This is probably a simple question to most of you, but here goes. > I've downloaded the xlrd (version 0.6.1) module and placed in in the > site-packages folder. Now, when I write a script, I type: > > import sys > import xlrd > > When I run it, there is an import error saying there is no module > named xlrd. However when I type sys.path, the site-packages folder is > definitely in the path. Do I somehow need to run the xlrd setup.py > first before importing? > > Any help would be appreciated. > -- > http://mail.python.org/mailman/listinfo/python-list > On what system? Windows or Unix? Which download? The exe or the zip? I'm guessing you downloaded the zip file on a Unix or Linux system. If so, you should not copy the files into the site-package directory yourself. You are supposed to use the included setup.py file like this: unzip into some local directory cd into that directory python setup.py build python setup.py install Then your import should work fine. Gary Herron From exarkun at divmod.com Mon Jun 30 12:26:20 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 30 Jun 2008 12:26:20 -0400 Subject: ctypes - swig - pointer In-Reply-To: Message-ID: <20080630162620.4714.1927154859.divmod.quotient.15321@ohm> On Mon, 30 Jun 2008 09:13:42 -0700 (PDT), gianluca wrote: >I've a problem with dll function colled with python/ctypes. My >functions (C) requred a typedef int "value_type" in tree different >way: >same as value_type; - mydll.foo1(value_type) >same as *value_type; - mydll.foo2(*value_type) >same as **value_type; - mydll.foo3(**value_type) > >How can pass it in python. If i do that: >rules=POINTER(value_type) >opr=rsl.StrengthOfRules(rules,10) >R=POINTER(rules) POINTER takes a class and returns a new class which represents a pointer to input class. pointer takes an instance and returns a new object which represents a pointer to that instance. Jean-Paul From ivan.illarionov at gmail.com Wed Jun 4 10:10:51 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 4 Jun 2008 14:10:51 +0000 (UTC) Subject: printf in python References: Message-ID: On Mon, 02 Jun 2008 00:32:33 -0700, gianluca wrote: > Hy, I've a problem with may python library generated with swig from C > code. I works and I can access all function but a sim?ple function that > print a string don't work's. > The function is like this: > int PrintTEST() > { > printf("TEST "); > return 1; > } > > If I call the function (myDLL.PrintTEST() ) the function print only the > returned value, not the string "TEST". Could anybody help me? > > Thanks > > Gianluca Hi! Here's "Hello world" in Python C API: 1. create 'hello.c' file with the following content: #include PyObject* hello(PyObject* self) { printf("Hello world!\n"); Py_RETURN_NONE; } static PyMethodDef functions[] = { {"hello", (PyCFunction)hello, METH_NOARGS}, {NULL, NULL, 0, NULL}, }; DL_EXPORT(void) init_hello(void) { Py_InitModule("_hello", functions); } 2. create 'buildme.py' file with this content: import os import sys from distutils.core import Extension, setup os.chdir(os.path.dirname(os.path.abspath(__file__))) sys.argv = [sys.argv[0], 'build_ext', '-i'] setup(ext_modules = [Extension('_hello', ["hello.c"])]) 3. run "python buildme.py" That's all. >>> from _hello import hello >>> hello() Hello world! -- Ivan From xahlee at gmail.com Mon Jun 30 12:45:18 2008 From: xahlee at gmail.com (Xah) Date: Mon, 30 Jun 2008 09:45:18 -0700 (PDT) Subject: perl + python tutorial available for download Message-ID: <86c4090b-ed0b-4249-b3ee-517c94328741@z32g2000prh.googlegroups.com> my perl and python tutorial http://xahlee.org/perl-python/index.html is now available for download for offline reading. Download link at the bottom. Xah ? http://xahlee.org/ ? From auch-ich-m at g-kein-spam.com Thu Jun 19 16:23:13 2008 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Thu, 19 Jun 2008 22:23:13 +0200 Subject: Extending Python with C: Cannot find MPI library References: <9100a146-a0bb-4958-a7c6-f23c9b518e89@a1g2000hsb.googlegroups.com> <80244b16-e2c5-4f4c-98d6-6101b004eb3c@26g2000hsk.googlegroups.com> Message-ID: <2012805.PE4ZuOqaqP@news.perlig.de> * Jeroen Ruigrok van der Werven wrote: > -On [20080619 17:11], Spectrum (spectrumdt at gmail.com) wrote: >> ImportError: dynamic module does not define init function > > Might be it's looking, but not finding, something like crti.S or the > likes, the C runtime files that specify stuff like _init and _fini. Nah. It's just looking for the init function required by the python module loader. See: http://docs.python.org/ext/methodTable.html nd -- die (eval q-qq:Just Another Perl Hacker :-) # Andr? Malo, # From upton at virginia.edu Tue Jun 3 15:34:58 2008 From: upton at virginia.edu (Dan Upton) Date: Tue, 3 Jun 2008 15:34:58 -0400 Subject: New variable? In-Reply-To: <2c47defa-52b3-4bbc-8286-9e266df80eb7@26g2000hsk.googlegroups.com> References: <18105511-7ae1-45e9-8c43-f34c1c4f5aeb@c58g2000hsc.googlegroups.com> <0dabbe7c-5754-4b2a-ae69-e92939fa682b@r66g2000hsg.googlegroups.com> <2c47defa-52b3-4bbc-8286-9e266df80eb7@26g2000hsk.googlegroups.com> Message-ID: <5504f9ac0806031234x5b56fed1y2963502bfcdb969b@mail.gmail.com> On Tue, Jun 3, 2008 at 3:16 PM, tmallen wrote: > On Jun 3, 3:03 pm, Chris wrote: >> On Jun 3, 8:40 pm, tmallen wrote: >> >> > What's the proper way to instantiate a new variable? x = ""? >> >> You don't need to pre-declare your variables. Just assign them as you >> need them and they will take the correct type. > > unless I'm using the += or a similar operator, right? That doesn't > seem to instantiate a variable. Right... because you don't have anything to increment or append to. I guess this also comes up in the case of something like lists or dictionaries you want to uniformly create in a loop. I guess you could call it instantiating, but really it's more like going ahead and assigning to them as Chris mentioned and you're just starting them with a default value. Assuming you're working with strings, x="" should work just fine in that case. Lists, x=[], dictionaries, x={}, integers, probably x=1 or x=0... From rdabane at gmail.com Tue Jun 3 17:00:47 2008 From: rdabane at gmail.com (rdabane at gmail.com) Date: Tue, 3 Jun 2008 14:00:47 -0700 (PDT) Subject: help needed in subprocess communicate Message-ID: <29fb52c3-6212-4f4c-9bf8-f8b565da24dd@c65g2000hsa.googlegroups.com> I'm trying to perform following type of operation from inside a python script. 1. Open an application shell (basically a tcl ) 2. Run some commands on that shell and get outputs from each command 3. Close the shell I could do it using communicate if I concatenate all my commands ( separated by newline ) and read all the output in the end. So basically I could do following sequence: 1. command1 \n command2 \n command 3 \n 2. Read all the output But I want to perform it interactively. 1. command1 2. read output 3. command2 4. read output ...... Following is my code: from subprocess import * p2 = Popen('qdl_tcl',stdin=PIPE,stdout=PIPE) o,e = p2.communicate(input='qdl_help \n qdl_read /home/rokit/ svnproject/falcon/chip/blocks/intf/bitsif/rtl/m6_bitsif.qdl_cpp \n qdl_reg_group_list m6_bitsif') Please suggest a way to perform it interactively with killing the process each time I want to communicate with it. Thanks in advance, -Rahul. From roy at panix.com Sat Jun 28 23:00:37 2008 From: roy at panix.com (Roy Smith) Date: Sat, 28 Jun 2008 23:00:37 -0400 Subject: complex numbers should respect the "I" representation References: <6c674bf8-f16b-40f1-81ef-72c009c08465@w1g2000prd.googlegroups.com> Message-ID: In article <6c674bf8-f16b-40f1-81ef-72c009c08465 at w1g2000prd.googlegroups.com>, "narutocanada at gmail.com" wrote: > hi > > I think complex numbers should respect the "i" or "I" representation, > instead of "j". > No reason being cute and using a different character instead of the > traditional representation? Ask any electrical engineer what j means. From victor.herasme at gmail.com Wed Jun 4 17:57:05 2008 From: victor.herasme at gmail.com (victor.herasme at gmail.com) Date: Wed, 4 Jun 2008 14:57:05 -0700 (PDT) Subject: Tuples part 2 Message-ID: Hi Everyone, i have another question. What if i wanted to make n tuples, each with a list of coordinates. For example : coords = list() for h in xrange(1,11,1): for i in xrange(1, 5, 1) : for j in xrange(1, 5, 1) : for k in xrange(1,2,1) : coords.append((i,j,k)) lista+str(h)= tuple coords print tuple(coords) so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do it the way i show you above but it is not working properly. I wish you could help me with that. Thanks again, From ptmcg at austin.rr.com Tue Jun 24 05:32:12 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 24 Jun 2008 02:32:12 -0700 (PDT) Subject: String split with " and/or ' and/or \ References: Message-ID: On Jun 24, 3:56?am, Kurt Mueller wrote: > How to (super)split a string (literal) containing " and/or ' and/or \. > > example: > > ' a ?" ?b b ? " ?c\ c '.supersplit(' ') > -> > ['a', ' ?b b ? ', 'c c'] > > Thanks and Gr?essli > -- > Kurt M?ller: > kurt.muel... at aerodynamics.ch >>> re.split(r'''['"\\]''',' a " b b " c\ c ') [' a ', ' b b ', ' c', ' c '] From dan at catfolks.net Wed Jun 4 08:48:09 2008 From: dan at catfolks.net (Daniel Mahoney) Date: Wed, 04 Jun 2008 07:48:09 -0500 Subject: Handling some isolated iso-8859-1 characters References: <16ad09c5-5095-4444-8739-285f8d665fd3@q24g2000prf.googlegroups.com> Message-ID: > ... print ord(c), unicodedata.name(c) > ... > 65 LATIN CAPITAL LETTER A > 110 LATIN SMALL LETTER N > 97 LATIN SMALL LETTER A > 239 LATIN SMALL LETTER I WITH DIAERESIS > 115 LATIN SMALL LETTER S Looks like I need to explore the unicodedata class. Thanks! From eliben at gmail.com Tue Jun 24 04:03:58 2008 From: eliben at gmail.com (eliben) Date: Tue, 24 Jun 2008 01:03:58 -0700 (PDT) Subject: binary representation of an integer Message-ID: <14e14b5e-ce39-414a-a450-7c81baaabc3a@79g2000hsk.googlegroups.com> Hello, I'm interested in converting integers to a binary representation, string. I.e. a desired function would produce: dec2bin(13) => "1101" The other way is easily done in Python with the int() function. Perl has a very efficient way to do dec2bin, because its pack/unpack have a B format for binary representations, so it's done with: sub dec2bin { my $str = unpack("B32", pack("N", shift)); $str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros return $str; } Python's pack/unpack don't have the binary format for some reason, so custom solutions have to be developed. One suggested in the ASPN cookbook is: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 However, it is very general and thus inefficient. What would be the quickest way to do this ? I think that for dec2bin conversion, using hex() and then looping with a hex->bin lookup table would be probably much faster than the general baseconvert from the recipe. What do you think? From hat at se-162.se.wtb.tue.nl Tue Jun 24 06:58:36 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 24 Jun 2008 12:58:36 +0200 Subject: very large graph References: <135bba90-a9dd-4fcd-9220-6271e5a7c876@59g2000hsb.googlegroups.com> <02ef6dc2-9ddb-4fbc-b3ce-5e6247daab33@e39g2000hsf.googlegroups.com> Message-ID: On 2008-06-24, MRAB wrote: > On Jun 24, 1:26?am, chrispoliq... at gmail.com wrote: >> I need to represent the hyperlinks between a large number of HTML >> files as a graph. ?My non-directed graph will have about 63,000 nodes >> and and probably close to 500,000 edges. >> >> I have looked into igraph (http://cneurocvs.rmki.kfki.hu/igraph/doc/ >> python/index.html) and networkX (https://networkx.lanl.gov/wiki) for >> generating a file to store the graph, and I have also looked into >> Graphviz for visualization. ?I'm just not sure which modules are >> best. ?I need to be able to do the following: Afaik Graphviz is not good at abstracting the graph, which you may need here. A page with 63,000 circles on it, and 500,000 edges will probably come out of the printer as a black sheet of paper. (8"x11" paper, 1 circle is 1/5", then you have only 2200 circles at one sheet. You need a factor 28 more circles which leads to a circle of about 0.007".) Even when actual paper format would not be a problem, you will need some abstraction and/or tools, as you will not find anything manually in an ocean of 63,000 elements. One area you may want to start looking for tools is in state graphs, where the set of possible states of an entire system is unfolded. These things go up to over a million states, so you only have a 'small' problem there... >> 1) ?The names of my nodes are not known ahead of time, so I will >> extract the title from all the HTML files to name the nodes prior to >> parsing the files for hyperlinks (edges). >> >> 2) Every file will be parsed for links and nondirectional connections >> will be drawn between the two nodes. >> >> 3) ?The files might link to each other so the graph package needs to >> be able to check to see if an edge between two nodes already exists, >> or at least not double draw connections between the two nodes when >> adding edges. >> >> I'm relatively new to graph theory so I would greatly appreciate any >> suggestions for filetypes. ?I imagine doing this as a python >> dictionary with a list for the edges and a node:list paring is out of >> the question for such a large graph? > > Perhaps a dictionary where the key is a node and the value is a set of > destination nodes? For undirected edges, you could make an Edge class and have a set of Edge's (where two Edge objects are equal when they connect the same nodes). I don't expect 500,000 elements in a set to be a problem. Sincerely, Albert From bignose+hates-spam at benfinney.id.au Wed Jun 4 18:29:09 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 05 Jun 2008 08:29:09 +1000 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> <873antn9il.fsf@benfinney.id.au> <6ammujF38poe2U2@mid.uni-berlin.de> <87y75llp5x.fsf@benfinney.id.au> Message-ID: <87prqwltqi.fsf@benfinney.id.au> Roy Smith writes: > The only externally visible interface is pushTheButton(), yet you > don't really want to call that during testing. What you do want to > do is test that a random city really does get picked. Then what you're really testing is the interactions of the "push the button" function with its external interface: you're asserting that the "push the red button" function actually uses the result from "pick a random city" as its target. Thus, the "pick a random city" function is being defined by you as *interface* for the "push the button" function. Interfaces do need to be unit tested. This is done by having the unit test substitute a test double for the "pick a random city" function, rigging that double so that its behaviour is deterministic, and asserting that the "push the button" function uses that deterministically-generated result. It's at this point, of course, that the "pick a random city" function has come rather close to being public API. The designer needs to have a fairly good reason not to simply expose the "pick a random city" function in the API. > You can do one of two things at this point. You can say, "But, > that's not part of the externally visible interface" and refuse to > test it, or you can figure out a way to test it. Up to you. Note that the only thing I'm saying one shouldn't do is unit test the private function *directly*, since the design decision has been made that it's not part of the API. The *behaviour* of the function, as exposed via the "push the button" piblic API, should certainly be unit tested. Any behaviour of that function that's *not* exhibited through the behaviour of some public API should *not* be unit tested, and should in fact be removed during refactoring -- which will not break the unit test suite since no unit tests depend on it. Alternatively, as above, the design decision can be made that, in fact, this function *is* part of the public API since external things are depending on it directly. Then it needs full direct unit test coverage. -- \ "I got contacts, but I only need them when I read, so I got | `\ flip-ups." -- Steven Wright | _o__) | Ben Finney From grante at visi.com Wed Jun 11 18:48:12 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 11 Jun 2008 17:48:12 -0500 Subject: how to indent/dedent a region in emacs? References: Message-ID: On 2008-06-11, Grant Edwards wrote: > I've recently switched from Jed to Emacs for editing python > source, and I'm still stumped as to how one indents or dedents > a region of code. In Jed it's 'C-c <' or 'C-c >'. Google has > found several answers, but none of them work, for example I've > tried bot "C-c tab" and "C-c C-r" based on postings Google has > found, but neither appears to actually _do_ anyting. Doh! It's 'C-c <' and 'C-c >' just like in Jed. I swear that didn't work the first time I tried it... -- Grant Edwards grante Yow! An air of FRENCH FRIES at permeates my nostrils!! visi.com From jeff at jmcneil.net Fri Jun 27 16:10:03 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Fri, 27 Jun 2008 13:10:03 -0700 (PDT) Subject: using urllib2 References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> Message-ID: I stumbled across this a while back: http://www.voidspace.org.uk/python/articles/urllib2.shtml. It covers quite a bit. The urllib2 module is pretty straightforward once you've used it a few times. Some of the class naming and whatnot takes a bit of getting used to (I found that to be the most confusing bit). On Jun 27, 1:41 pm, Alexnb wrote: > Okay, I tried to follow that, and it is kinda hard. But since you obviously > know what you are doing, where did you learn this? Or where can I learn > this? > > > > > > Maric Michaud wrote: > > > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit : > >> I have never used the urllib or the urllib2. I really have looked online > >> for help on this issue, and mailing lists, but I can't figure out my > >> problem because people haven't been helping me, which is why I am here! > >> :]. > >> Okay, so basically I want to be able to submit a word to dictionary.com > >> and > >> then get the definitions. However, to start off learning urllib2, I just > >> want to do a simple google search. Before you get mad, what I have found > >> on > >> urllib2 hasn't helped me. Anyway, How would you go about doing this. No, > >> I > >> did not post the html, but I mean if you want, right click on your > >> browser > >> and hit view source of the google homepage. Basically what I want to know > >> is how to submit the values(the search term) and then search for that > >> value. Heres what I know: > > >> import urllib2 > >> response = urllib2.urlopen("http://www.google.com/") > >> html = response.read() > >> print html > > >> Now I know that all this does is print the source, but thats about all I > >> know. I know it may be a lot to ask to have someone show/help me, but I > >> really would appreciate it. > > > This example is for google, of course using pygoogle is easier in this > > case, > > but this is a valid example for the general case : > > >>>>[207]: import urllib, urllib2 > > > You need to trick the server with an imaginary User-Agent. > > >>>>[208]: def google_search(terms) : > > return urllib2.urlopen(urllib2.Request("http://www.google.com/search?" > > + > > urllib.urlencode({'hl':'fr', 'q':terms}), > > headers={'User-Agent':'MyNav > > 1.0 > > (compatible; MSIE 6.0; Linux'}) > > ).read() > > .....: > > >>>>[212]: res = google_search("python & co") > > > Now you got the whole html response, you'll have to parse it to recover > > datas, > > a quick & dirty try on google response page : > > >>>>[213]: import re > > >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

    class=r>.*?

    ', > > res) ] > > ...[229]: > > ['Python Gallery', > > 'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des Monty ...', > > 'Re: os x, panther, python & co: msg#00041', > > 'Re: os x, panther, python & co: msg#00040', > > 'Cardiff Web Site Design, Professional web site design services ...', > > 'Python Properties', > > 'Frees < Programs < Python < Bin-Co', > > 'Torb: an interface between Tcl and CORBA', > > 'Royal Python Morphs', > > 'Python & Co'] > > > -- > > _____________ > > > Maric Michaud > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > View this message in context:http://www.nabble.com/using-urllib2-tp18150669p18160312.html > Sent from the Python - python-list mailing list archive at Nabble.com. From fc14301589 at icqmail.com Sun Jun 1 12:37:26 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Mon, 02 Jun 2008 00:37:26 +0800 Subject: [Business apps for Windows] Good grid + calendar, etc.? References: Message-ID: <4842d046_1@news.tm.net.my> On 19:59, domenica 01 giugno 2008 Gilles Ganault wrote: > require rich widgets like (DB)grids, calendars, etc. Qt seems to go a bit further. Try Eric4 as SDK. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From brian_vanderburg2 at yahoo.com Wed Jun 18 02:28:44 2008 From: brian_vanderburg2 at yahoo.com (Allen) Date: Wed, 18 Jun 2008 02:28:44 -0400 Subject: Save turtle state? Message-ID: I'm using the turtle module in Python. Is there a way to save the turle state at any moment for recursive algorithms to easily return the turtle to an earlier point for another branch/etc? Brian Vanderburg II From pirata at mars.invalid Mon Jun 16 23:29:53 2008 From: pirata at mars.invalid (pirata) Date: Mon, 16 Jun 2008 22:29:53 -0500 Subject: Does '!=' equivelent to 'is not' Message-ID: I'm a bit confusing about whether "is not" equivelent to "!=" if a != b: ... if a is not b: ... What's the difference between "is not" and "!=" or they are the same thing? From ram.rachum at gmail.com Sun Jun 15 15:11:06 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Sun, 15 Jun 2008 12:11:06 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> <1f658382-1f45-41c2-a884-5478fef394bf@j22g2000hsf.googlegroups.com> Message-ID: On Jun 15, 9:41?pm, Mensanator wrote: > On Jun 15, 12:10?pm, "ram.rac... at gmail.com" > wrote: > > > > > On Jun 15, 7:43?pm, Peter Otten <__pete... at web.de> wrote: > > > > ram.rac... at gmail.com wrote: > > > > On Jun 15, 6:58?pm, Christian Meesters wrote: > > > >> > I do need speed. Is there an option? > > > > >> Mind telling us what you *actually* want to achieve? (What do you want to > > > >> calculate?) > > > > >> Christian > > > > > Physical simulations of objects with near-lightspeed velocity. > > > > How did you determine that standard python floats are not good enough? > > > I have a physical system set up in which a body is supposed to > > accelerate and to get very close to lightspeed, while never really > > attaining it. After approx. 680 seconds, Python gets stuck and tells > > me the object has passed lightspeed. I put the same equations in > > Mathematica, again I get the same mistake around 680 seconds. So I > > think, I have a problem with my model! Then I pump up the > > WorkingPrecision in Mathematica to about 10. I run the same equations > > again, and it works! At least for the first 10,000 seconds, the object > > does not pass lightspeed. > > I concluded that I need Python to work at a higher precision. > > > > Everything beyond that is unlikely to be supported by the hardware and will > > > therefore introduce a speed penalty. > > > I have thought of that as well. However I have no choice. I must do > > these calculations. If you know of any way that is supported by the > > hardware, it will be terrific, but for now the slower things will have > > to do. > > > > Did you try gmpy? > > > Not yet: I was kind of set back when I saw their homepage was last > > updated 2002. > > Try looking here: > > http://code.google.com/p/gmpy/ > > The developers have abandoned SourceForge. > > > But I'll give it a try. You think it's the best thing > > there is? > > I haven't tried everything, but it's very good. > You might also want to go to the GMP site itself > and get their manual. Likee anything else, your > results will be no better than your algorithms. > > > > > Thanks, > > Ram. I'll check it out, thanks. From robert.kern at gmail.com Wed Jun 18 19:05:08 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 18 Jun 2008 18:05:08 -0500 Subject: python string comparison oddity In-Reply-To: References: <3ebd170e-8686-4bb4-9e47-0fba2179feb3@p39g2000prm.googlegroups.com> Message-ID: Faheem Mitha wrote: > On Wed, 18 Jun 2008 12:57:44 -0700 (PDT), Lie wrote: >> On Jun 19, 2:26 am, Faheem Mitha wrote: >>> Hi everybody, >>> >>> I was wondering if anyone can explain this. My understanding is that 'is' >>> checks if the object is the same. However, in that case, why this >>> inconsistency for short strings? I would expect a 'False' for all three >>> comparisons. This is reproducible across two different machines, so it is >>> not just a local quirk. I'm running Debian etch with Python 2.4.4 (the >>> default). >>> Thanks, Faheem. >>> >>> In [1]: a = '--' >>> >>> In [2]: a is '--' >>> Out[2]: False >>> >>> In [4]: a = '-' >>> >>> In [5]: a is '-' >>> Out[5]: True >>> >>> In [6]: a = 'foo' >>> >>> In [7]: a is 'foo' >>> Out[7]: True >> Yes, this happens because of small objects caching. When small >> integers or short strings are created, there are possibility that they >> might refer to the same objects behind-the-scene. Don't rely on this >> behavior. > > Yes, but why is '-' and 'foo' cached, and not '--'? Do you know what > the basis of the choice is? Shortish Python identifiers and operators, I think. Plus a handful like '\x00'. The source would know for sure, but alas, I am lazy. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From goldnery at gmail.com Sun Jun 8 06:01:00 2008 From: goldnery at gmail.com (Gandalf) Date: Sun, 8 Jun 2008 03:01:00 -0700 (PDT) Subject: SQlite none english char References: <6b1ld5F3a4hsvU1@mid.uni-berlin.de> Message-ID: On Jun 8, 11:00?am, Gerhard H?ring wrote: > Gandalf wrote: > > I works with python 2.5 on windows, ?And I use sqlite3 > > > Now, I have problem searching string in Hebrew in my database > > > I have table called "test" with field num and test > > firs row i insert ?"1" and "?????" ?(that is "Hebrew" in Hebrew) > > second row i insert "2" and "English" [...] > > I recommend you use Unicode strings for all your Python strings in the > application. You can then be that things will just work with the sqlite3 > module. > > The problem is that the sqlite3 module doesn't currently check if what > you insert into the database is in UTF-8 encoding. But if it isn't, > you're likely to run into problems later on. > > So, let's assume that you've written your Python using a UTF-8 editor, > you can then use something like: > > # coding: utf-8 > > as the first line in the script. Among others, this will allow you to > write Unicode literals in UTF-8, i. e. do something like: > > data = u"?????". > > then you can insert this into the database: > > cur.execute("insert into test(test) values (?)", (data,)) > > Note that I use the parametrized form of execute() with ? as > placeholders. *Always* use this when the SQL statement is not constant, > but has parameters of some sort. > > > [...] > > cur.execute("select * ?from `test` where text like '%"+i+"%' ?") > > for row in cur: > > ? ? print row[1] > > > but this one print me nothing > > instead of ????? > > This could be two problems. Either (likely) it simply isn't found > because you inserted garbage (non-UTF-8 data) or you got a decoding > error to UTF-8 executing the select, which the sqlite3 module will > currently unfortunately ignore and return a None value instead. > > Again, use the parametrized form of the execute() statement with Unicode > Python strings to avoid any problems. > > cur.execute("select * from test where text like '%' || ? || '%'", > (searchstr,)) > > !!! Ok, I just found out that you used the + operator in SQL to > concatenate strings. Don't, as it will not work (except on maybe MySQL). > Use the || operator instead! > > Note that when you use cur.execute(sql, params), then params is actually > a tuple of parameters. In the above examples there was only one > parameter, so it was a one-tuple, which is written as (element,). > Dont'write it as (element), because Python will not recognize it as a > tuple then. > > Don't hesitate to ask if you need further help. > > -- Gerhard I solved the problem by entering data manually but now the problem is that i had to delete this function: con.text_factory = str and now I can't see the data that I entered thought my sqlite manager From __peter__ at web.de Sun Jun 15 12:43:26 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Jun 2008 18:43:26 +0200 Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> Message-ID: ram.rachum at gmail.com wrote: > On Jun 15, 6:58?pm, Christian Meesters wrote: >> > I do need speed. Is there an option? >> >> Mind telling us what you *actually* want to achieve? (What do you want to >> calculate?) >> >> Christian > > Physical simulations of objects with near-lightspeed velocity. How did you determine that standard python floats are not good enough? Everything beyond that is unlikely to be supported by the hardware and will therefore introduce a speed penalty. Did you try gmpy? Peter From lawtonpaul at gmail.com Mon Jun 16 20:48:17 2008 From: lawtonpaul at gmail.com (takayuki) Date: Mon, 16 Jun 2008 17:48:17 -0700 (PDT) Subject: newbie question: for loop within for loop confusion References: <821db59d-c9b6-4aa8-b08a-b8f46d230eb1@p25g2000pri.googlegroups.com> Message-ID: Paul, Thank you for the informative reply. Yes, I created the indent problem when manually copying the original script when I posted. (I'm using an old laptop to study python and posting here using the desktop.) Your examples really helped. Last night I played with using a for loop instead of a while loop and got it working, but your examples really clarified things. This loop was particularly interesting because I didn't know the else could be attached to the for. Attaching it to the for solved a lot of problems. for letter in avoid: if letter in word: break else: print word I've printed out this whole thread and will be playing with your and others' solutions. I love this one for its conciseness, but will have to play with it to get my head around it. if not any(letter in word for letter in avoid): print word Thanks again. takayuki From eliben at gmail.com Fri Jun 20 01:01:02 2008 From: eliben at gmail.com (eliben) Date: Thu, 19 Jun 2008 22:01:02 -0700 (PDT) Subject: An idiom for code generation with exec Message-ID: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> Hello, In a Python program I'm writing I need to dynamically generate functions[*] and store them in a dict. eval() can't work for me because a function definition is a statement and not an expression, so I'm using exec. At the moment I came up with the following to make it work: def build_func(args): code """def foo(...)...""" d = {} exec code in globals(), d return d['foo'] My question is, considering that I really need code generation[*] - "is there a cleaner way to do this ?" Also, what happens if I replace globals() by None ? Additionally, I've found indentation to be a problem in such constructs. Is there a workable way to indent the code at the level of build_func, and not on column 0 ? Thanks in advance Eli [*] I know that each time a code generation question comes up people suggest that there's a better way to achieve this, without using exec, eval, etc. But in my case, for reasons too long to fully lay out, I really need to generate non-trivial functions with a lot of hard-coded actions for performance. And there's no problem of security whatsoever. If someone is very interested in the application, I will elaborate more. From mwilson at the-wire.com Fri Jun 20 07:15:48 2008 From: mwilson at the-wire.com (Mel) Date: Fri, 20 Jun 2008 07:15:48 -0400 Subject: Strange re problem References: <2a0a6f87-f72e-4190-85f8-6e43821e313a@r66g2000hsg.googlegroups.com> Message-ID: TYR wrote: > OK, this ought to be simple. I'm parsing a large text file (originally > a database dump) in order to process the contents back into a SQLite3 > database. The data looks like this: > > 'AAA','PF',-17.416666666667,-145.5,'Anaa, French Polynesia','Pacific/ > Tahiti','Anaa';'AAB','AU',-26.75,141,'Arrabury, Queensland, > Australia','?','?';'AAC','EG',31.133333333333,33.8,'Al Arish, > Egypt','Africa/Cairo','El Arish International';'AAE','DZ', > 36.833333333333,8,'Annaba','Africa/Algiers','Rabah Bitat'; > > which goes on for another 308 lines. As keen and agile minds will no > doubt spot, the rows are separated by a ; so it should be simple to > parse it using a regex. So, I establish a db connection and cursor, > create the table, and open the source file. > > Then we do this: > > f = file.readlines() > biglist = re.split(';', f) > > and then iterate over the output from re.split(), inserting each set > of values into the db, and finally close the file and commit > transactions. But instead, I get this error: > > Traceback (most recent call last): > File "converter.py", line 12, in > biglist = re.split(';', f) > File "/usr/lib/python2.5/re.py", line 157, in split > return _compile(pattern, 0).split(string, maxsplit) > TypeError: expected string or buffer (untested) Try f=file.read() readlines gives you a list of lines. Mel. From duncan.booth at invalid.invalid Thu Jun 12 06:40:34 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jun 2008 10:40:34 GMT Subject: ClassName.attribute vs self.__class__.attribute References: <9af859e9-e6e2-48f2-9fa9-139a5acaae0c@f24g2000prh.googlegroups.com> <4850e95d$0$10444$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > > FWIW, metaclasses do have a class attribute that refers to itself !-) > One metaclass (i.e. type) has a class attribute that refers to itself. Other metaclasses have a class attribute that refers to the metaclass's metaclass. I can't think of any situation where a metaclass would be its own metaclass except for 'type' itself, but then I think I've got a headache trying to think about this so maybe I'm wrong. In fact, thinking about it a bit more, I think that if you did have another metaclass which is its own metaclass then the class cannot subclass 'object'. -- Duncan Booth http://kupuguy.blogspot.com From sjmachin at lexicon.net Tue Jun 24 20:36:10 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 24 Jun 2008 17:36:10 -0700 (PDT) Subject: shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": References: <09b41308-0167-4231-b5e7-5baa1a9aff9d@u6g2000prc.googlegroups.com> <3b12d826-4a10-4ed3-b66e-f28f64910f05@m3g2000hsc.googlegroups.com> Message-ID: On Jun 25, 9:06 am, s0s... at gmail.com wrote: > On Jun 24, 5:36 pm, John Machin wrote: > > > On Jun 25, 4:32 am, cirfu wrote: > > > > if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": > > > > cant i write something like: > > > if char in "[A-Za-z]": > > > You can write that if you want to, but it's equivalent to > > if char in "zaZa]-[": > > i.e. it doesn't do what you want. > > > This gives the same reuslt as your original code, unaffected by > > locale: > > > if "A" <= char <= "Z" or "a" <= char <= "z": > > But doesn't that rely on the underlying character set? Unless there is a Python implementation using EBCDIC, different underlying character set that differs from ASCII in A..Z and a..z is *not* a practical concern. > It's like > performing math on C char's (maybe that's what the interpreter does > internally?). If that's the case, using 'char.isalpha()' or 'char in > string.letters' or regex's would be better. You should be asking the OP what he really wants ... precisely those letters? alphabetic, in what locale? From nospam at nospam.com Sun Jun 1 07:59:26 2008 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 01 Jun 2008 13:59:26 +0200 Subject: [Business apps for Windows] Good grid + calendar, etc.? Message-ID: Hello Since Python is such a productive language, I'd really like to be able to use it to write GUI apps for Windows, but business apps require rich widgets like (DB)grids, calendars, etc. The ones available in wxWidgets looked a bit too basic compared to what's available for eg. Delphi or .Net, and don't seem to be under active development (lots of "1.0", "Last updated 2005", etc.) For instance, here's wxGrid and DevExpress' grid for Delphi: http://www.simpol.com/guiimages/wxgrid.jpg http://community.devexpress.com/blogs/thinking/PrintingXtraPivotGridForm.png Is it hopeless, or did I overlook things? Are there other solutions I should look at (FLTK, etc.)? For those of you writing business apps in Python for Windows, how do things go as far as GUI widgets are concerned? Thank you. From arslanburney at gmail.com Fri Jun 20 03:15:25 2008 From: arslanburney at gmail.com (J-Burns) Date: Fri, 20 Jun 2008 00:15:25 -0700 (PDT) Subject: Wierd Test Failure Message-ID: <6d84b388-f72a-4ccc-8b5b-b1fb7cc7f602@26g2000hsk.googlegroups.com> Hello. Im using doctests to check the functions that ive made. Wat i dnt understand is that it gives me a fialure even though the expected and got values are the same. Check this out: ********************************************************************** File "C:\Python25\Lib\idlelib\idle.pyw", line ?, in __main__.Test.test8 Failed example: Test.test8() Expected: True Got: True ********************************************************************** If both the values are returning True how is it possible for the test to fail? :S From celoserpa at gmail.com Tue Jun 24 12:24:46 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Tue, 24 Jun 2008 13:24:46 -0300 Subject: Accounting and financial system Message-ID: <1e5bcefd0806240924t74c7b4ax48d1267e508e516b@mail.gmail.com> Hello list, In a next project of mine, I will need to implement some accounting and financial control. It is not a full ERP, only the basic functions for finances and accounting control. However, I have little to no experience in this business domain (accounting and finances) but I really do need to understand the basic machinery behind it, even if it will take a significant amount of time. What I would like to know is where I could look (besides getting a degree :P) for sample code and documentation for these subjects? Do you think I would need to read some books before I get into code? If so, which ones? For sample code, I was thinking about OpenERP, since I've heard it is a complete ERP solution and it is written in python ;) Really, I'm committed to understand the basiscs of the said business domains, I really need this project to succeed :) Thanks in advance! Marceo. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mccredie at gmail.com Fri Jun 27 12:03:05 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 27 Jun 2008 09:03:05 -0700 (PDT) Subject: embedding and extending python C API registering callback handler objects References: Message-ID: On Jun 27, 8:22?am, Tim Spens wrote: > Hello all, > > I've been trying to get an example found herehttp://codeidol.com/python/python3/Embedding-Python/Registering-Callb... > to work. ?Every thing works fine except when I try to trigger an event from c that will call a python function. ?Here is my test code: > > //-----------------------python code--------------------------// > #! /usr/bin/env python > import time > import callback > > def callback1(label,count): > ? ? ? ? print 'callback1 successfully triggered from python via callback.so' > ? ? ? ? return 'callback1 => %s number %i' % (label, count) > > def callback2(label,count): > ? ? ? ? return 'callback2 => ' + ?label * count > > print '\nTest1:' > callback.setHandler(callback1) > callback.triggerEvent() ? ? ? ? # simulate events caught by C layer > > print '\nTest2:' > callback.setHandler(callback2) > > print 'Waiting for callback2 to be called from c:' > while 1: > ? ? ? ? time.sleep(.001) > > //-----------------------c code-------------------------------// > #include > #include > > /* keep Python object in C */ > static PyObject *Handler = NULL; > > void Route_Event(char *label, int count){ > ? ? char *cres; > ? ? PyObject *args, *pres; > ? ? /* call Python handler */ > ? ? args = Py_BuildValue("(si)", label, count); > ? ? pres = PyEval_CallObject(Handler, args); > ? ? Py_DECREF(args); > ? ? if (pres != NULL){ > ? ? ? ? /* use and decref handler result */ > ? ? ? ? PyArg_Parse(pres, "s", &cres); > ? ? ? ? printf("%s\n", cres); > ? ? ? ? Py_DECREF(pres); > > }} > > // the actual python callback call > static PyObject * > make_call(PyObject *function, PyObject *args){ > ? ? if (function == NULL) return NULL; > ? ? PyObject * val = PyObject_CallObject(function, args); > ? ? Py_XDECREF(args); > ? ? return val; > > } > > static PyObject * > Register_Handler(PyObject *self, PyObject *args){ > ? ? /* save Python callable object */ > ? ? Py_XDECREF(Handler); > ? ? PyArg_Parse(args, "O", &Handler); > ? ? Py_XINCREF(Handler); > ? ? Py_INCREF(Py_None); > ? ? return Py_None; > > } > > static PyObject * > Trigger_Event(PyObject *self, PyObject *args){ > ? ? /* let Python simulate event caught by C */ > ? ? static int count = 0; > ? ? Route_Event("spam", count++); > ? ? Py_INCREF(Py_None); > ? ? return Py_None; > > } > > static struct PyMethodDef callback_methods[] = { > ? ? {"setHandler", ? ?Register_Handler}, ? ? ? /* name, address */ > ? ? {"triggerEvent", ?Trigger_Event}, > ? ? {NULL, NULL}}; > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? /* on first "import callback" */ > void initcallback(){ ? ? ? ? ? ? ? ? ?/* this is called by Python ?*/ > ? ? (void) Py_InitModule("callback", callback_methods); > > } > > int main(){ > ? ? ? ? while (1){ > ? ? ? ? ? ? ? ? printf("1\n"); > ? ? ? ? ? ? ? ? //attempting to call callback2 which is registered to Handler > ? ? ? ? ? ? ? ? //i've also tried args = Py_BuildValue("(si)", label, count); here but I get a segfault. > ? ? ? ? ? ? ? ? PyObject *args = Py_BuildValue("s","c code"); > ? ? ? ? ? ? ? ? printf("2\n"); > ? ? ? ? ? ? ? ? PyObject* val = make_call(Handler,args); > ? ? ? ? ? ? ? ? printf("3\n"); > ? ? ? ? ? ? Py_XDECREF (val); > ? ? ? ? ? ? printf("4\n"); > ? ? ? ? ? ? ? ? sleep(1); > > }} > > //------------------------compiler stuff----------------------// > gcc callback.c -c -g -Wall -fpic -I /usr/include/python2.5 -o callback.o > gcc callback.c -g -Wall -I /usr/include/python2.5 -L /usr/local/lib -lpython2.5 -o callback > gcc -shared -Wall callback.o -o callback.so > > //------------------------test code results-------------------// > ../callback.py > Test1: > callback1 successfully triggered from python via callback.so > callback1 => spam number 0 > > Test2: > Waiting for callback2 to be called from c: > #NOTHING EVER GETS PRINTED HERE CALLBACK NEVER GETS CALLED? > > ../callback > 1 > 2 > 3 > 4 > .... > > Thanks, > Tim Maybe you just need to flush the stdout buffer in python. `sys.stdout.flush()` Matt From someone at somewhere.net Tue Jun 3 11:26:04 2008 From: someone at somewhere.net (Dino Dragovic) Date: Tue, 03 Jun 2008 17:26:04 +0200 Subject: trinity school defender Message-ID: u gorenavedenom flajeru u 8. redu: "postoji vi?e od 60.000 virusa i drugih ?tetnih programa " samo virusa ima nekoliko stotina tisuca, zajedno sa potencijalno stetim aplikacijama i ostalim malicioznim kodom brojka ide preko milion.... From russblau at hotmail.com Mon Jun 9 11:33:43 2008 From: russblau at hotmail.com (Russell Blau) Date: Mon, 9 Jun 2008 11:33:43 -0400 Subject: How to find the first space? References: <7a91cc8f-2e93-46e9-8360-a01da9170187@m44g2000hsc.googlegroups.com> Message-ID: "Johny" wrote in message news:7a91cc8f-2e93-46e9-8360-a01da9170187 at m44g2000hsc.googlegroups.com... > How can I find the first space using regex? > > For example I have text > Text=' This is a sample ' Why do you need to use a regex? text = text.replace(" ", "") Russ From andrei.avk at gmail.com Mon Jun 9 16:38:17 2008 From: andrei.avk at gmail.com (Rainy) Date: Mon, 9 Jun 2008 13:38:17 -0700 (PDT) Subject: Separators inside a var name References: Message-ID: On Jun 9, 2:05?pm, "Sebastian \"lunar\" Wiesner" wrote: > ?Rainy at Montag 09 Juni 2008 19:29: > > > I have a stylistic question. In most languages words in var. name are > > separated by underscores or cap letters, resulting in var names like > > var_name, VarName and varName. I don't like that very much because all > > 3 ways of naming look bad and/or hard to type. > > Then you better get used to such names, as they are common for many widely > spread languages including C, C++, C#, Java, Python, Ruby, Perl and many > more ;) ?You may like these or dislike these names, but you won't come > around them ;) Well, I was thinking of using some obscure language for personal projects that may not need good libs, etc. But of course I agree that there are no mainstream widely used languages that allow this. > > > From what I understand, scheme can have variables like var-name. I'm > > curious about reasons that python chose to disallow this. > > "-" is an operator in Python. ?How should the parser know, > whether "var-name" means "the object bound to var_dash_name" or "subtract > the object bound to name from the object bound to var"? As I mentioned in another post, differentiate between var1 - var2 and var-name. > > Scheme can allows such names, because its a functional programming language. > Subtracting in this language is not done through operators, but through > functions. ?Therefore there is a clear difference between referencing a > name or subtracting two ones: var-name vs (- var name). > > > Another question I have is what other languages allow this naming scheme? > > Other lisp dialects do, due to the same reasons as scheme. ? > > > Were there any languages that allowed space as a separator? > > None that I know of. ?Probably one could use unicode characters, that look > like a space in languages, which allow unicode characters in identifiers > (as Java or C#, iirc), but I doubt this. ?Anyway, even if allowed, this > would be silly, since it obscures code to the eyes of the reader. Yes, that's of course out. I meant using real space. > > > What would be a practical way to separate variables from keywords in that > > case? "some long variable name", 'just a string', or maybe using 2 spaces: > > one var ?+ ?other var ?+ ?third var ? > > I can't image a practical way to allow a space as character in names, while > still maintaining it syntactic element for separation of names. ?Quotes are > normally used for string or characters literals and a double space is hard > to distinguish from a single space, and things like ${a name with spaces} > is a lot nastier than names with underscores (which aren't bad at all, > imho). I agree about ${name with spaces}. I would be interested in the approach of using something else for strings and using quotes for var names. Not perfect either but might be better than underscores... > > > I think being able to easy have very long names for vars that are easy to > > type would be a fairly significant advantage. > > Names shouldn't be long, they should be expressive. ?If you can't give an > object a _short_, but _expressive_ name, your object is too complicated ;) I'm not sure, I often find myself needing to use 4 words for var name, and then underscores I think don't look too good, I would say that underscores are kind of ok for 2 words, not very good for 3 words and bad for 4+ words. I think if spaces were allowed, I would sometimes use 5 word variables. > > Btw, I don't really understand your refusal of underscores. ?In my opinion > such names are harder to read than underscores, which look more like a real > space, because the leave a space in the middle of a line, that you look at. > If they are too hard for you to type, whats the point in swapping the dash > and the underscore in your keyboard layout? To me, underscores_look_very_ugly. What_if_I_typed part_of_every_sentence with_an_underscore? Ugly! Swapping the dash and underscore are not a bad idea, it doesn't fix uglyness, though, and it adds a problem if you have to work on another system, because you will always type dash by mistake (which will look nice but won't work ;-) ). From tjreedy at udel.edu Thu Jun 19 21:29:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 19 Jun 2008 21:29:53 -0400 Subject: advanced listcomprehenions? In-Reply-To: References: <717129b5-d92f-4be2-ae6a-037870bfa407@2g2000hsn.googlegroups.com> Message-ID: Duncan Booth wrote: > Mark Wooding wrote: > >> This is still inelegant, though. We can glue the results mod 3 and 5 >> together using the Chinese Remainder Theorem and working mod 15 >> instead. For example, >> >> [['Fizz', 'FizzBuzz', False, None, 'Buzz'][(pow(i, 4, 15) + 1)%7] or >> str(i) for i in xrange(1, 101)] The lookup table is a constant. If made a tuple, it will be compiled as a constant (as least in 2.6, maybe 2.5). In any case, it could (and to me should) be lifted out of the string comp. >> >> (A less mathematical approach would just use i%15 to index a table. But >> that's not interesting. ;-) ) >> > > Ooh. Doesn't having 5 elements make you shudder? (Even though you did > change one to avoid a repeated value.) You have 4 options for output, so > for elegance that list should also have 4 elements: > > [[str(i), 'FizzBuzz', 'Fizz', 'Buzz'][25/(pow(i, 4, 15) + 1)%4] for i in > xrange(1, 101)] > > I feel it is even more elegant with the lookup table in its natural order: > > [['Fizz', 'Buzz', 'FizzBuzz', str(i)][62/(pow(i, 4, 15) + 1)%4] for i in > xrange(1, 101)] These make the lookup table variable, so it has to be recalculated for each i. tjr From Lie.1296 at gmail.com Tue Jun 3 09:04:57 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 3 Jun 2008 06:04:57 -0700 (PDT) Subject: Generating event from event References: <37f8a6a1-dc98-4985-a84d-f74ead1ec2b7@z72g2000hsb.googlegroups.com> <6aanqgF36mnldU1@mid.uni-berlin.de> <2980f056-a68f-4d8e-9104-642ef5911fcf@k37g2000hsf.googlegroups.com> <82471cd7-55bb-4376-bcae-3a601ed8f75a@c65g2000hsa.googlegroups.com> Message-ID: On May 31, 1:27?am, Mike Driscoll wrote: > On May 30, 12:11?pm, Gandalf wrote: > > > Hi Diez, I can't see how it ?matter which GUI-Toolkit i uses because I > > can combine libraries. > > I think all that matter is that i work with windows XP. > > > if you ever done something like that or you familiar with article > > which can show me how to implement what I asked it would help me > > > Thank you very much > > It matters because each Python GUI toolkit works differently. Tkinter > does it via Tk/tcl calls, wxPython uses the wx library and pyGTK does > it in yet another way. The basic ideas are the same, but the > implementations are quite different. > > In wx, for example, there are mouse events called wx.MouseEvent: > > http://www.wxpython.org/docs/api/wx.MouseEvent-class.html > > In Tkinter, they do the same thing, but the calls are almost > completely different. See the following for examples: > > http://www.pythonware.com/library/tkinter/introduction/events-and-bin... > > You probably either want the MouseEvents or to create an > AcceleratorTable. > > Mike I'd get frustated enough to *plonk* someone like him if he keeps refusing to answer an information that is already requested and already mentioned of the significance. From gagsl-py2 at yahoo.com.ar Tue Jun 3 22:12:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 03 Jun 2008 23:12:00 -0300 Subject: Handling some isolated iso-8859-1 characters References: Message-ID: En Tue, 03 Jun 2008 15:38:09 -0300, Daniel Mahoney escribi?: > I'm working on an app that's processing Usenet messages. I'm making a > connection to my NNTP feed and grabbing the headers for the groups I'm > interested in, saving the info to disk, and doing some post-processing. > I'm finding a few bizarre characters and I'm not sure how to handle them > pythonically. > > One of the lines I'm finding this problem with contains: > 137050 Cleo and I have an anouncement! "Mlle. > =?iso-8859-1?Q?Ana=EFs?=" > Sun, 21 Nov 2004 16:21:50 -0500 > 4478 69 Xref: > sn-us rec.pets.cats.community:137050 > > The interesting patch is the string that reads > "=?iso-8859-1?Q?Ana=EFs?=". > An HTML rendering of what this string should look would be "Anaïs". > > What I'm doing now is a brute-force substitution from the version in the > file to the HTML version. That's ugly. What's a better way to translate > that string? Or is my problem that I'm grabbing the headers from the NNTP > server incorrectly? No, it's not you, those headers are formatted following RFC 2047 Python already has support for that format, use the email.header class, see -- Gabriel Genellina From mccredie at gmail.com Thu Jun 26 11:19:29 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 26 Jun 2008 08:19:29 -0700 (PDT) Subject: ConfigParser: Can I read(ConfigParser.get()) a configuration file and use it to call a funciton? References: <34b51593-d787-4f12-9cc2-473d3832ff0d@k37g2000hsf.googlegroups.com> Message-ID: <7fd37b8c-b96d-480c-94c4-e53f8598830e@d45g2000hsc.googlegroups.com> On Jun 26, 7:41?am, jamitwi... at gmail.com wrote: > Hello. I am a novice programmer and have a question > > I have a configuration file(configuration.cfg) > I read this from reading.py using ConfigParser > When I use ConfigParser.get() function, it returns a string. > I want to call a function that has the same name as the string from > the configuration file. > > configuration.cfg > --------------------------------------- > [1234] > title: abcd > function: efgh > --------------------------------------- > > reading.py > -------------------------------------------------------- > import ConfigParser > > def efgh(): > ? ?print 'blah' > > config = ConfigParser.ConfigParser() > config.read('configuration.cfg') > > fcn = config.get('1234','function') > type(fcn) > print fcn > -------------------------------------------------------- > > > efgh > > Is there any way to call efgh() ? > One way I know is using if statement > if fcn == 'efgh': > ? ?efgh() > > But I am going to have many functions to call, so I want to avoid > this. > > Thank you for your help Something like this: globals()[fcn]() From bignose+hates-spam at benfinney.id.au Tue Jun 3 09:31:34 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 03 Jun 2008 23:31:34 +1000 Subject: Code correctness, and testing strategies References: Message-ID: <87d4mymyq1.fsf@benfinney.id.au> Duncan Booth writes: > I made the mistake at one point when I was trying to sell the > concept of TDD telling the people I was trying to persuade that by > writing the tests up front it influences the design of the code. I > felt the room go cold: they said the customer has to sign off the > design before we start coding, and once they've signed it off we > can't change anything. It's for misunderstandings like you describe here that I prefer (these days) to use the term "behaviour driven development". The coding is driven by desired new and/or altered behaviour of the application; everything else follows from that statement of direction. People, such as customers, who don't care about the term "unit test" can easily relate to the term "behaviour". They are happy to talk about how they want the application to behave, and are usually easy to convince that such descriptions of behaviour are what should be the driving force behind the implementation. -- \ "Truth would quickly cease to become stranger than fiction, | `\ once we got as used to it." -- Henry L. Mencken | _o__) | Ben Finney From jason at tishler.net Mon Jun 9 09:15:29 2008 From: jason at tishler.net (Jason Tishler) Date: Mon, 09 Jun 2008 09:15:29 -0400 Subject: Invalid Version Number (Distutils from Cygwin) In-Reply-To: <17714617.post@talk.nabble.com> References: <17714617.post@talk.nabble.com> Message-ID: <20080609131529.GA3324@tishler.net> On Sat, Jun 07, 2008 at 05:34:21PM -0700, newbie73 wrote: > [snip] > I'm attempting to build a project (FANN libraries) using cygwin (to > avoid installing MSVC 2003) and am receiving this error: > > Traceback (most recent call last): > [snip] > ValueError: invalid version number '2.18.50.20080523' The above is a known issue: http://bugs.python.org/issue2234 Unfortunately, resolution of this issue has stalled. Additionally, someone posted a different regular expression to the Cygwin list that is suppose to handle more cases of ld version strings: http://cygwin.com/ml/cygwin/2008-05/msg00622.html Can we reach consensus on what is the best ld version string regular expression to use? If so, then I will work to get this change committed to the Python code base and release a patched Cygwin Python 2.5.2 with this fix included. Thanks, Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From t_spens at yahoo.com Thu Jun 26 15:15:13 2008 From: t_spens at yahoo.com (Tim Spens) Date: Thu, 26 Jun 2008 12:15:13 -0700 (PDT) Subject: simplest c python api callback example Message-ID: <274270.13633.qm@web45105.mail.sp1.yahoo.com> The following is a simple complete example using the c python api to generate callbacks from c to python. But when I run the c code I get a segfault in PyInt_FromLong () (see below). Most of this example code was taken from pg 1478 of the 3rd edition python o'reilly book. I cannot see what I'm doing wrong here to get this segfault? Please help. //-------------------python-code-------------------------// #! /usr/bin/env python ####################################################### # register for and handle event callbacks from C; # compile C code, and run with 'python register.py' ####################################################### import time # # C calls these Python functions; # handle an event, return a result # def callback1(label, count): return 'callback1 called with args: label-%s and count-%i' % (label, count) # # Python calls a C extension module # to register handlers, trigger events # import cregister cregister.setpythonHandler(callback1) print '\nwaiting for callback pythonHandler to be called:' while 1: time.sleep(1) //-------------------compiler commands--------------// gcc -Wall -fno-strict-aliasing -g -I /usr/include/python2.5 -c cregister.c;gcc -g -Wall -I /usr/include/python2.5 -L /usr/local/lib -lpython2.5 cregister.c -o cregister;gcc -shared -fPIC -g -Wall -I /usr/include/python2.5 -L /usr/lib -lpython2.5 -o cregister.so cregister.o //-------------------c-code-------------------------// #include #include /***********************************************/ /* 1) code to route events to Python object */ /* note that we could run strings here instead */ /***********************************************/ //python handlers //keep Python object in C static PyObject *pythonHandler = NULL; void Route_Event(){ PyObject *args; // call Python handler args = Py_BuildValue("(si)", "c code", 5); PyEval_CallObject(pythonHandler, args); } /*****************************************************/ /* 2) python extension module to register handlers */ /* python imports this module to set handler objects */ /*****************************************************/ static PyObject * Register_pythonHandler(PyObject *self, PyObject *args){ // save Python callable object Py_XDECREF(pythonHandler); //called before? PyArg_Parse(args, "O", &pythonHandler); //one argument? Py_XINCREF(pythonHandler); //add a reference Py_INCREF(Py_None); //return 'None': success return Py_None; } //makes these functions available by importing cregister in python static struct PyMethodDef cregister_methods[] = { {"setpythonHandler", Register_pythonHandler}, {NULL, NULL} }; // this is called by Python on first "import cregister" void initcregister(){ (void) Py_InitModule("cregister", cregister_methods); } int main(){ while (1){ PyObject *arglist; arglist = Py_BuildValue("(si)", "c code", 5); Py_XINCREF(pythonHandler); Py_XINCREF(arglist); PyEval_CallObject(pythonHandler, arglist); Py_XDECREF(pythonHandler); Py_XDECREF(arglist); sleep(1); } } Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 0xb7c1c6b0 (LWP 13699)] 0xb7e0bcfb in PyInt_FromLong () from /usr/lib/libpython2.5.so.1.0 (gdb) bt #0 0xb7e0bcfb in PyInt_FromLong () from /usr/lib/libpython2.5.so.1.0 #1 0xb7e8cae6 in ?? () from /usr/lib/libpython2.5.so.1.0 #2 0x00000005 in ?? () #3 0x00000006 in ?? () #4 0xbf89a378 in ?? () #5 0xb7e9d095 in _PyObject_GC_Malloc () from /usr/lib/libpython2.5.so.1.0 #6 0xb7e8d1dd in ?? () from /usr/lib/libpython2.5.so.1.0 #7 0x00000002 in ?? () #8 0x08048320 in ?? () #9 0x72d6dafa in ?? () #10 0x00000029 in ?? () #11 0xbf89a474 in ?? () #12 0xbf89a478 in ?? () #13 0x00000000 in ?? () From patrickstinson.lists at gmail.com Wed Jun 4 18:33:18 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Wed, 4 Jun 2008 14:33:18 -0800 Subject: python, dlls, and multiple instances In-Reply-To: <4842ed97$0$25496$9b622d9e@news.freenet.de> References: <4842ed97$0$25496$9b622d9e@news.freenet.de> Message-ID: <6214d7a20806041533p75e4a621w262ae36b0cf0cc48@mail.gmail.com> ahh, ok. Looks like my fundamental understanding of how dlls work was a little messed up. Thanks! On Sun, Jun 1, 2008 at 10:42 AM, "Martin v. L?wis" wrote: >> Is it a correct to assume that you can use multiple instances of >> python altogether if each is loaded from a separate dll? For instance, >> if I write a couple of dll/so libs, and each has python statically >> linked in, is it safe to assume that since dlls use their own address >> space > > DLLs don't use their own address space. All DLLs of a single operating > system process use the same address space. > > Different DLLs do use different portions of that address space. > >> then each dll would have it's own GIL, and will therefore >> coexist safely within the same app? This is correct across all >> platforms, yes? > > No; it rather depends on the way the operating system resolves symbols. > On some systems (e.g. many Unix systems), there is only a single global > symbol table for the entire process. So when a shared library is loaded, > and needs to resolve its symbols (even the ones that it also defines > itself), it may end up finding the GIL in a different copy of the Python > interpreter, so they all share the GIL (even though there would have > been space for multiple GILs). > > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list > From bruno.desthuilliers at gmail.com Fri Jun 20 17:06:04 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 20 Jun 2008 14:06:04 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> <485bd4f8$0$30999$426a74cc@news.free.fr> Message-ID: On 20 juin, 21:41, eliben wrote: > > [1] except using compile to build a code object with the function's > > body, then instanciate a function object using this code, but I'm not > > sure whether it will buy you much more performance-wise. I'd personnaly > > prefer this because I find it more explicit and readable, but YMMV. > > How is compiling more readable than exec - Using compile and function(), you explicitely instanciate a new function object, while using exec you're relying on a side effect. > doesn't it require an extra > step ? Well... Your way: d = {} exec code in globals(), d return d['foo'] My way: return function(compile(code, '', 'exec'), globals()) As far as I'm concern, it's two steps less - but YMMV, of course !-) > You generate code dynamically anyway. Yes, indeed. Which may or not be the right thing to do here, but this is a different question (and one I can't actually answer). From google at mrabarnett.plus.com Wed Jun 18 19:29:50 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 18 Jun 2008 16:29:50 -0700 (PDT) Subject: advanced listcomprehenions? References: <717129b5-d92f-4be2-ae6a-037870bfa407@2g2000hsn.googlegroups.com> Message-ID: <1fd4a490-cb70-4659-8912-d5b6febe2705@d1g2000hsg.googlegroups.com> On Jun 18, 10:42?pm, cirfu wrote: > I am wondering if it is possible to write advanced listcomprehensions. > > For example: > """Write a program that prints the numbers from 1 to 100. But for > multiples of three print "Fizz" instead of the number and for the > multiples of five print "Buzz". For numbers which are multiples of > both three and five print "FizzBuzz".""" > Obv it doesnt have to be a list according tot hat definition but > suppose i want to generate that list. > > >>> [["Fizzbuzz",x] for x in xrange(1,101) if x%3 == 0 and x%5 == 0] > > [['Fizzbuzz', 15], ['Fizzbuzz', 30], ['Fizzbuzz', 45], ['Fizzbuzz', > 60], ['Fizzbuzz', 75], ['Fizzbuzz', 90]] > > is not what i want. the following does the trick but is ldo not a > listcomprehension: > > for i in xrange(1,101): > ? ? s = "" > ? ? if i%3 == 0: > ? ? ? ? s += "Fizz" > ? ? if i%5 == 0: > ? ? ? ? s += "Buzz" > ? ? if s: > ? ? ? ? print "%d : %s" % (i,s) > ? ? else: > ? ? ? ? print i > > or to generate a lisrt but not by listcomprehsnion: > map(lambda x: (not x%3 and not x%5 and "FizzBuzz") or (not x%3 and > "Fizz") > or (not x%5 and "Buzz") or x, xrange(1,101)) [("FizzBuzz" if n % 15 == 0 else "Fizz" if n % 3 == 0 else "Buzz" if n % 5 == 0 else str(n)) for n in range(1, 101)] From saluk64007 at gmail.com Tue Jun 10 14:56:05 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Tue, 10 Jun 2008 11:56:05 -0700 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <18c8cd3f-b050-4ddb-8b03-d24754b2b075@u12g2000prd.googlegroups.com> <48495693$0$26543$426a74cc@news.free.fr> <87f889f2-6365-4274-a978-5199d21b7998@w5g2000prd.googlegroups.com> <484cf5f6$0$15495$426a74cc@news.free.fr> <127975a3-b3d9-4799-9673-b292ec8d37e3@x19g2000prg.googlegroups.com> <11b37cfd-d94e-411d-99fc-405da9fc8e4d@m73g2000hsh.googlegroups.com> <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> <484e3526$0$30894$426a74cc@news.free.fr> <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> Message-ID: Hi Russ, Here are just some pragmatic considerations. Personally I am against data hiding, but I obviously won't convince you in that regard. There are some pros and cons as with anything, and I feel the cons outweight the pros (namely that users of code should be able to use how they want, even if it means shooting themselves in the foot; and the fact that priv somewhat breaks the dynamics of python) Even if your proposal were to go through, you are looking at probably 2 years before it can even be used. Python3 is basically in freeze mode, and it contains the biggest change in python syntax for a long time. I know it doesn't seem like a big change to you to add a priv keyword, but python very rarely adds keywords, so it's a long shot merely for that reason. This is something that potentially would be under consideration for something like 3.2 or higher I think, so if you want to get the job done now, this topic or trying to convince other long time python users isn't going to accomplish your goals. Leading underscore takes two keystrokes to type (shift, _) while priv, private, etc takes many more. If you are too lazy to type "_var" then how come you aren't too lazy to type "priv var"? Too me it seems like more typing. If the primary objection to leading underscores is looks, it seems like you unnecesarily avoid them for a pointless reason. There are ugly aspects to every language, and there isn't really a better convention to use that I can see. Without of course implementing keywords, which are conceptually difficult to think about in terms of python object model - although you might be able to come up with a way. But if you have a better naming convention or strategy that you want to try on your code, nothing is stopping you. You can use one of the hacks found in this thread, or come up with your own hack, to more or less accomplish what you want. It should take 30 minutes or less to set up, and you are done with it. The internals of python make it difficult to do more than that, but you are welcome to create your own python fork if you think you are up to it. Although I think that would be more than 30 minutes of work. And feel free to try other languages. No one claimed python is the best for every circumstance. Well, if someone claimed that they are just fooling themselves. Python is a good hacker language that scales pretty well into enterprise and web services; and can be used for other things as well. I don't believe that data prevention (we aren't really talking about just hiding here) is necessary for 99% of tasks, but other people think differently, so there are plenty of languages that implement these features. Good luck finding a solution to fit your project. However I don't think trying to get a "priv" keyword into official python is feasable unless you want to wait a very long time and go hoarse from shouting :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at divmod.com Sun Jun 29 10:11:15 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 29 Jun 2008 10:11:15 -0400 Subject: Why is recursion so slow? In-Reply-To: <5504f9ac0806290703h1bf44639jbfe5331c4a2d1369@mail.gmail.com> Message-ID: <20080629141115.4714.638077829.divmod.quotient.14914@ohm> On Sun, 29 Jun 2008 10:03:46 -0400, Dan Upton wrote: >On Sun, Jun 29, 2008 at 1:27 AM, Terry Reedy wrote: >> >> >> slix wrote: >>> >>> Recursion is awesome for writing some functions, like searching trees >>> etc but wow how can it be THAT much slower for computing fibonacci- >>> numbers? >> >> The comparison below has nothing to do with recursion versus iteration. (It >> is a common myth.) You (as have others) are comparing an exponential, >> O(1.6**n), algorithm with a linear, O(n), algorithm. >> > >FWIW, though, it's entirely possible for a recursive algorithm with >the same asymptotic runtime to be wall-clock slower, just because of >all the extra work involved in setting up and tearing down stack >frames and executing call/return instructions. (If the function is >tail-recursive you can get around this, though I don't know exactly >how CPython is implemented and whether it optimizes that case.) CPython doesn't do tail call elimination. And indeed, function calls in Python have a much higher fixed overhead than iteration. Jean-Paul From mathieu.malaterre at gmail.com Wed Jun 4 09:59:27 2008 From: mathieu.malaterre at gmail.com (mathieu) Date: Wed, 4 Jun 2008 06:59:27 -0700 (PDT) Subject: Distributing 2 python modules with incompatible API Message-ID: hi there, As far as I understand python is not using the usual UNIX system of soname when two libraries provide incompatible API. So let say I have a _foo.so version 1.2 and 2.0, all I can (should do) is move them underneath a subdirectory in site-package: pythonX.Y/site-package/foo1.2/_foo.so pythonX.Y/site-package/foo1.2/foo.py and pythonX.Y/site-package/foo2.0/_foo.so pythonX.Y/site-package/foo2.0/foo.py Then a central foo.pth would (sytem-wide) define which one is the default version: pythonX.Y/site-package/foo.pth If this is correct ? Is there any documentation that I missed ? Thanks -Mathieu From JKPeck at gmail.com Wed Jun 25 09:29:28 2008 From: JKPeck at gmail.com (JKPeck) Date: Wed, 25 Jun 2008 06:29:28 -0700 (PDT) Subject: Using the backing store with mmap Message-ID: <402eaad5-6fb7-4b61-80dc-bb64840b94cb@m44g2000hsc.googlegroups.com> According to the mmap.mmap 2.5 documentation, "Changed in version 2.5: To map anonymous memory, -1 should be passed as the fileno along with the length." I would like to use shared memory to communicate between two processes that otherwise have no way to communicate, but I couldn't find a way to share anonymous memory. (I can use file names agreed on by convention, but the file is really irrelevant, and I'd prefer to eliminate it.) Is this possible? What is the lifetime of this shared memory? Is it in fact private to the creating process, or is it shared among all (Python) processes? Does it need to be flushed by a writing process? How do the access flags relate to this? If I create two such items, are they independent, or is it all one pool? TIA, Jon Peck From duncan.booth at invalid.invalid Tue Jun 17 04:20:42 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Jun 2008 08:20:42 GMT Subject: Does '!=' equivelent to 'is not' References: Message-ID: "Leo Jay" wrote: > same objects are equal, but equal don't have to be the same object. same objects are often equal, but not always: >>> inf = 2e200*2e200 >>> ind = inf/inf >>> ind==ind False >>> ind is ind True -- Duncan Booth http://kupuguy.blogspot.com From mccredie at gmail.com Fri Jun 13 12:55:04 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 13 Jun 2008 09:55:04 -0700 (PDT) Subject: weird iteration/assignment problem References: <61936860-de3f-4bb1-8806-08f9f21ad113@m36g2000hse.googlegroups.com> <6bfgpoF3bpl84U1@mid.uni-berlin.de> Message-ID: On Jun 13, 8:07 am, "Diez B. Roggisch" wrote: > cirfu schrieb: > > > for i in xrange(0, len(texts)): > > texts[i] = "yes" > > > for i in texts: > > i = "no" > > > why is the first one working but not the second. i mean i see why the > > firts one works but i dont udnerstand why the second doesnt. > > Because in the second you only bind the contents of texts to a name i. > > But that doesn't mean that i magically became an "alias" for > texts[index] - it just happens to point at the same object. > > To accomplish what you want, the pythonic idiom is to use enumerate: > > for i, text in enumerate(texts): > text[i] = "yes" > > Diez That should be: for i, text in enumerate(texts): texts[i] = "yes" From larry.bates at websafe.com` Sun Jun 1 07:41:14 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 01 Jun 2008 06:41:14 -0500 Subject: Need Tutorial For the following lib In-Reply-To: <0bdd04b8-23b6-4a68-bda2-6984428ce7bd@b1g2000hsg.googlegroups.com> References: <9950cf3f-e58a-413a-bdff-a40cc1c6cf6d@8g2000hse.googlegroups.com> <0bdd04b8-23b6-4a68-bda2-6984428ce7bd@b1g2000hsg.googlegroups.com> Message-ID: <4KCdnQj2nvh7F9_VnZ2dnUVZ_uidnZ2d@comcast.com> Gandalf wrote: > Hi scott, you couldn't be more wrong about my laziness. I straggle > with my poor English for hours to fined what I'm looking for. > I found a very simple and not comprehensive tutorial for the pyWinAuto > lib in this address http://pywinauto.openqa.org/ > but it only show how to do the basic, and my knowledge at this point > is not enough to figure the rest I need to know by myself > I found another simple lib for the watsup that based on winGuiAuto > lib in this address > http://www.tizmoi.net/watsup/intro.html > But for some risen I couldn't manage to ran it in my computer > > I'm trying to generate auto mouse double click or auto selecting text > (the selecting text part is the one I interest in. mouse double click > just do the same effect if the mouse cursor is on text) > > I'm sorry you feel I'm lazy. The truth is that event writing this > message takes me an enormous power. > weather you choose to help me or not I still going to keep trying , > But you have the opportunity to save me lots of trouble, So maybe one > day I could help others. > > so if you familiar with any good tutorial for this library please let > me know and if not then thank you anyway for wonting to help > > Y.G > > > What you want is an easy solution to what isn't an easy problem, but (as with your other post) you refuse to provide enough information to allow us to help you. If I were you, I would download wxPython and go through the demos that it includes. comp.python.wxpython list is excellent (at least as good as this one) for any follow-up questions. Windows events and mouse clicks are going to take a concerted effort (on your part) to learn (especially if you haven't accomplished such a task in another language). -Larry From Pratip.Mukherjee at FMR.COM Tue Jun 17 08:57:41 2008 From: Pratip.Mukherjee at FMR.COM (Mukherjee, Pratip) Date: Tue, 17 Jun 2008 08:57:41 -0400 Subject: How do I avoid using HTTPRedirectHandler with urllib2? Message-ID: Hi, I am new to Python, trying it as an alternative to Perl. I am having problem with python HTTP handling library, urllib2. How do I avoid using the HTTPRedirectHandler while making a HTTP request? For those familiar to Perl-LWP, this is done by using simple_request() on the UserAgent object. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From socyl at 987jk.com.invalid Mon Jun 9 11:54:28 2008 From: socyl at 987jk.com.invalid (kj) Date: Mon, 9 Jun 2008 15:54:28 +0000 (UTC) Subject: Q re documentation Python style References: Message-ID: Wow. That was a great bunch of advice. Thank you all very much! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From asdf at asdf.com Tue Jun 10 21:05:45 2008 From: asdf at asdf.com (asdf) Date: 11 Jun 2008 01:05:45 GMT Subject: Dynamic HTML from Python Script References: <484f151c$0$5009$607ed4bc@cv.net> <484f21aa$1@dnews.tpgi.com.au> Message-ID: <484f24e9$0$5020$607ed4bc@cv.net> > Well, there's a few ways you could approach it. > > You could create a cgi program from your script - this is probably the > solution you're looking for. > Output from the script does come up very often. There is a new output every 10 secs and it's possible that the script might be run indefinitely. Basically I want all that output displayed in a web browser > You could have the script run periodically and create a static html file > in the webroot... this would be acceptable, maybe preferable, if the > output from your script doesn't change frequently. > From kurdayon at yahoo.com Fri Jun 27 17:41:01 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Fri, 27 Jun 2008 14:41:01 -0700 (PDT) Subject: "method involving two objects" is that possible in Python? Message-ID: <8c8aec73-bd5b-4dfc-b91a-b100f3b9ddfa@m73g2000hsh.googlegroups.com> Hi, I just started to learn Python. I understood how one can create a class and define a method related with that class. According to my understanding every call of a methods is related with a specific object. For example, we have a method "length", than we call this method as the following "x.length()" or "y.length()" or "z.length()", where z, y, and z are objects of the class. I am wandering if it is possible to create a method which is related not with a single object (as in the previous example) but with a pare of objects. For example, I want to have a class for vectors, and I want to have a methods which calculate a dot product of two vectors. One of the possibilities is to use __mul__ and that I calculated dot product of "x" and "y" just as "x * y". However, I am wandering if I can declare a method in a way that allows me to calculate dot product as "dot(x,y)". Thank you in advance. From healey.rich at gmail.com Mon Jun 23 21:09:21 2008 From: healey.rich at gmail.com (Rich Healey) Date: Tue, 24 Jun 2008 11:09:21 +1000 Subject: IDE on the level of Eclipse or DEVc++? In-Reply-To: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> Message-ID: <48604941.6030707@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 cirfu wrote: > is there an IDE for python of the same quality as Eclipse or DEVC++? > > I am currently using the editor that coems iwth python and it is all > fine but for bigger projects it would be nice to have some way to > easier browse the projectfiles for example. I don't want to start a flamewar. But I like vim. - -- Rich Healey - healey.rich at gmail.com Developer / Systems Admin - OpenPGP: 0x8C8147807 MSN: bitchohealey at hotmail.com AIM: richohealey33 irc.psych0tik.net -> #hbh #admins richohealey irc.freenode.org -> #hbh #debian PythonNinja -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFIYElBLeTfO4yBSAcRAvjqAJ9DIbb5qxLTh+s2k0AsUkmxoC0TtACdFj3x hxVamWJkbDsslu8F+QhG2xA= =G4vQ -----END PGP SIGNATURE----- From rhamph at gmail.com Wed Jun 11 13:55:14 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Wed, 11 Jun 2008 10:55:14 -0700 (PDT) Subject: Producer-consumer threading problem References: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> <9482cbb7-297e-4429-b7a1-6d7c1dcc9070@t12g2000prg.googlegroups.com> <3d0a1204-526b-4447-a2cf-7f40860bb299@d1g2000hsg.googlegroups.com> Message-ID: <35245867-5534-4d3b-a86d-f469d44a4dda@q27g2000prf.googlegroups.com> On Jun 11, 6:00 am, George Sakkis wrote: > On Jun 11, 1:59 am, Rhamphoryncus wrote: > > > Why not use a normal Queue, put a dummy value (such as None) in when > > you're producer has finished, and have the main thread use the normal > > Thread.join() method on all your child threads? > > I just gave two reasons: > - Concurrency / interactivity. The main thread shouldn't wait for all > one million items to be produced to get to see even one of them. Then don't wait. The main thread can easily do other work while the producer and consumer threads go about their business. > - Limiting resources. Just like iterating over the lines of a file is > more memory efficient than reading the whole file in memory, getting > each consumed item as it becomes available is more memory efficient > than waiting for all of them to finish. That's why you give Queue a maxsize. Put it at maybe 5 or 10. Enough that the producer can operate in a burst (usually more efficient that switching threads after each item), then the consumer can grab them all in a burst. Then again, you may find it easier to use an event-driven architecture (like Twisted, as others have suggested.) From asdf at asdf.com Mon Jun 16 21:16:54 2008 From: asdf at asdf.com (asdf) Date: 17 Jun 2008 01:16:54 GMT Subject: 2Q's: How to autocreate instance of class;How to check for membership in a class Message-ID: <48571086$0$5010$607ed4bc@cv.net> So I'm writing a script which will create several instances of User() class. I want each instance to be named after the login name of a user. I don't know beforehand how many users the script will have to create or how they are named. Right now I've created a dictionary of usernames as keys and objects themselves as values. It works, but is very unwieldy, because every time I need to access a value from within an object I have to do something like dict-user[x].value. Is there a way of automatically naming objects from variable names. So for example if I know that var1=jsmith. Can I somehow do var1=User(). This obviously won't work because I tried this. It'll just create var1 of type User. My second question is how can I check if object is a member of a class. so let's say I create a=User(), b=User()... Can I do something similar to if x.Users()==TRUE: print "user already created" Right now I'm doing this using try-except which works but I'm looking for something cleaner. thanks for all the replies. From jgardner at jonathangardner.net Mon Jun 30 16:21:54 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 30 Jun 2008 13:21:54 -0700 (PDT) Subject: ask for a RE pattern to match TABLE in html References: <6a4f17690806260653i136681bdsabe0f6bb1dfab67b@mail.gmail.com> <62f752f3-d840-42de-a414-0d56d15d7c5a@w4g2000prd.googlegroups.com> Message-ID: <87bb8346-6498-4e51-b065-88d915dcff0d@p39g2000prm.googlegroups.com> On Jun 27, 10:32?am, "David C. Ullrich" wrote: > (ii) The regexes in languages like Python and Perl include > features that are not part of the formal CS notion of > "regular expression". Do they include something that > does allow parsing nested delimiters properly? > In perl, there are some pretty wild extensions to the regex syntax, features that make it much more than a regular expression engine. Yes, it is possible to match parentheses and other nested structures (such as HTML), and the regex to do so isn't incredibly difficult. Note that Python doesn't support this extension. See http://www.perl.com/pub/a/2003/08/21/perlcookbook.html From metallourlante at gmail.com Mon Jun 23 10:55:07 2008 From: metallourlante at gmail.com (Alex) Date: Mon, 23 Jun 2008 07:55:07 -0700 (PDT) Subject: learning unit testing in python Message-ID: Hi all. I'd like learn some basic unit testing with python. I red some articles about different testing framework like unittest or nose, but I'm a bit confused: what is the best choice? I'm not a professional developer (I'm a SEO) but I belive that unit testing is a good and pragmatic way to produce working software, so I'd like to find something really simple ad straightforward because I don't have to manage big programming projects. Thanks in advance, Alex From noagbodjivictor at gmail.com Sat Jun 28 23:22:51 2008 From: noagbodjivictor at gmail.com (Victor Noagbodji) Date: Sat, 28 Jun 2008 23:22:51 -0400 Subject: HTML Parsing Message-ID: > Hi everyone Hello > I am trying to build my own web crawler for an experiement and I don't > know how to access HTTP protocol with python. urllib2: http://docs.python.org/lib/module-urllib2.html > Also, Are there any Opensource Parsing engine for HTML documents > available in Python too? That would be great. BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/ http://www.crummy.com/software/BeautifulSoup/documentation.html All the best -- NOAGBODJI Paul Victor From badmuthahubbard at gmail.com Thu Jun 5 04:52:33 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Thu, 5 Jun 2008 11:52:33 +0300 Subject: Interesting Math Problem In-Reply-To: <748f2d520806040103q48689a01i310ee07df20a5e73@mail.gmail.com> References: <748f2d520806040103q48689a01i310ee07df20a5e73@mail.gmail.com> Message-ID: <8200bab70806050152u68aecf48hb2caffdf58c9aa5d@mail.gmail.com> On Wed, Jun 4, 2008 at 11:03 AM, BEES INC wrote: > My Solution (in Python): > > # round to one decimal place and > # separate into whole and fractional parts > parts = str(round(star_sum/num_raters, 1)).split('.') > whole = int(parts[0]) > frac = int(parts[1]) > if frac < 3: > ___frac = 0 > elif frac > 7: > ___frac = 0 > ___whole += 1 > else: > ___frac = 5 > # recombine for a star rating rounded to the half > stars = float(str(whole)+'.'+str(frac)) def roundstars(invalue): inv *= 2 inv += .5 return float(int(inv))/2 seems to work for me. > Mmmm? In-N-Out Burgers? Please reply if you've got a better solution. I've never had the pleasure, but I've heard they're a wonderful experience. -Chuckk -- http://www.badmuthahubbard.com From george.sakkis at gmail.com Thu Jun 12 00:41:21 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 11 Jun 2008 21:41:21 -0700 (PDT) Subject: Confusion with weakref, __del__ and threading References: <113f383e-9027-461b-88db-7e5331e7d361@59g2000hsb.googlegroups.com> <7ed2109d-3b88-484c-9d19-67706747c95f@v26g2000prm.googlegroups.com> <5da23b98-9434-41d4-9dd1-0a423fd387b1@26g2000hsk.googlegroups.com> <2a3ae0a4-144b-44ce-8e30-53b5586ccb7e@w4g2000prd.googlegroups.com> Message-ID: <68a9447a-799e-4143-8724-2ff55fc24b0c@w7g2000hsa.googlegroups.com> On Jun 11, 8:37?pm, Rhamphoryncus wrote: > On Jun 11, 2:15 pm, George Sakkis wrote: > > > > > On Jun 11, 2:01 pm, Rhamphoryncus wrote: > > > > On Jun 11, 10:43 am, George Sakkis wrote: > > > > > On Jun 11, 1:40 am, Rhamphoryncus wrote: > > > > > The trick here is that calling proxy.sleep(0.01) first gets a strong > > > > > reference to the Mystery instance, then holds that strong reference > > > > > until it returns. > > > > > Ah, that was the missing part; I thought that anything accessed > > > > through a proxy didn't create a strong reference. The good thing is > > > > that it seems you can get a proxy to a bounded method and then call it > > > > without creating a strong reference to 'self': > > > > That's not right. ?Of course a bound method has a strong reference to > > > self, otherwise you'd never be able to call it. ?There must be > > > something else going on here. ?Try using sys.setcheckinterval(1) to > > > make threads switch more often. > > > I tried that and it still works; all objects die at the main thread. > > Any other idea to break it ? > > Nothing comes to mind. > > However, none of this is guaranteed anyway, so you can't rely on it. > __del__ might be called by any thread at any point (even when you're > holding a lock, updating a datastructure.) Ok, you scared me enough to cut the link to the thread altogether, avoiding the cyclic reference and the weakref proxy. The original intent for keeping a reference to the thread was to be able to join() it later before some cleanup takes place. I have since found a less spooky way to synchronize them but regardless, I'd be interested for an explanation of what's really going on in the posted snippets. George From gagsl-py2 at yahoo.com.ar Tue Jun 24 05:23:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 24 Jun 2008 06:23:57 -0300 Subject: string.Template.delimiter cannot be overriden? References: <4rH5k.2032$to3.1384@newsfe15.phx> <35e212be-e85b-41fd-90c2-f90959053232@l28g2000prd.googlegroups.com> Message-ID: En Tue, 17 Jun 2008 02:20:23 -0300, Raymond Hettinger escribi?: > On Jun 16, 9:53?pm, kretik wrote: >> I've been trying to coax this class to use something other than the >> default '$' but it seems setting it to something else has no discernible >> effect. Is it necessary to inherit from the class to do this? > > Yes, subclassing is the intended way to produce variants of Template > with a different delimiter. Just out of curiosity, why was it done that way? I'd say the "obvious" way to change the default delimiter would be to set an instance attribute - so I guess this was a deliberate decision, but I can't figure out why it is better this way... -- Gabriel Genellina From tjreedy at udel.edu Wed Jun 11 15:22:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Jun 2008 15:22:49 -0400 Subject: Alternative to Decimal type References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: "Frank Millman" wrote in message news:f7cc4f0f-3e37-43e7-927a-0ed14a063930 at 25g2000hsx.googlegroups.com... | Thanks to all for the various replies. They have all helped me to | refine my ideas on the subject. These are my latest thoughts. | | Firstly, the Decimal type exists, it clearly works well, it is written | by people much cleverer than me, so I would need a good reason not to | use it. Speed could be a good reason, provided I am sure that any | alternative is 100% accurate for my purposes. The Decimal module is a Python (now C coded in 2.6/3.0, I believe) implementation of a particular IBM-sponsored standard. The standard is mostly good, but it is somewhat large with lots of options (such as rounding modes) and a bit of garbage (the new 'logical' operations, for instance) added by IBM for proprietary purposes. Fortunately, one can ignore the latter once you recognize them for what they are. As Nick indicated, it is not the first in its general category. And I believe the Decimal implementation could have been done differently. By writing you own class, you get just what you need with the behavior you want. I think just as important is the understanding of many of the issues involved, even if you eventually switch to something else. That is a pretty good reason in itself. tjr From bignose+hates-spam at benfinney.id.au Sat Jun 7 00:52:46 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 07 Jun 2008 14:52:46 +1000 Subject: Dynamically naming objects. References: <8a99c3fa-1eeb-49b3-a714-b6063ec1daab@d19g2000prm.googlegroups.com> <3d2a85b2-255d-4e93-8cfb-e2772f57b69a@u6g2000prc.googlegroups.com> Message-ID: <87tzg5kfs1.fsf@benfinney.id.au> Kalibr writes: > what I want to do is have, say 5 users in a game, so I'd have to > spawn 5 objects. I can't do that because I have'nt hardcoded any > object names for them. Python's built-in mapping type 'dict' is a good fit for this. Given: * a 'User' class that is initialised with the user's name * some way of getting a sequence of names (that you haven't told us yet), that I'll bind here to the name 'sequence_of_names' You can then write:: game_users = {} for name in sequence_of_names: game_users[name] = User(name) This will result in 'game_users' bound to a dict with names mapping to separate instances of the 'User' type. These instances can each be addressed by name from the 'game_users' mapping as 'game_users["Fred"]', etc. -- \ "Pinky, are you pondering what I'm pondering?" "Well, I think | `\ so, Brain, but do I really need two tongues?" -- _Pinky and | _o__) The Brain_ | Ben Finney From healey.rich at gmail.com Tue Jun 17 03:10:41 2008 From: healey.rich at gmail.com (Rich Healey) Date: Tue, 17 Jun 2008 17:10:41 +1000 Subject: print problem In-Reply-To: References: <2MWdnYXqCY3yy8rVnZ2dnUVZ_sbinZ2d@posted.internode> Message-ID: <48576371.7000209@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Gabriel Genellina wrote: > En Tue, 17 Jun 2008 03:15:11 -0300, pirata escribi?: > >> I was trying to print a dot on console every second to indicates >> running process, so I wrote, for example: >> >> for i in xrange(10): >> print ".", >> time.sleep(1) >> >> Idealy, a dot will be printed out each second. But there is nothing >> print out until after 10 seconds, all 10 dots come out together. >> >> I've tried lose the comma in the print statement, and it works. >> >> Is that because of the print statement buffer the characters until >> there is a new line character? > > Very probably, altough I can't reproduce it on Windows. Try invoking the script with python -u (unbuffered input/output): > > python -u your_script.py > Or just write to sys.stdout without the print wrapper.. - -- Rich Healey - healey.rich at gmail.com Developer / Systems Admin - OpenPGP: 0x8C8147807 MSN: bitchohealey at hotmail.com AIM: richohealey33 irc.psych0tik.net -> #hbh #admins richohealey irc.freenode.org -> #hbh #debian PythonNinja -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFIV2NxLeTfO4yBSAcRAkunAJ9w5lavHK4TIUbexX+pSYmPla9oOQCfT8tM tzOhQgcpO7dEG7WhE6FNZ4w= =IqJ1 -----END PGP SIGNATURE----- From pavlovevidence at gmail.com Mon Jun 2 09:41:48 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 2 Jun 2008 06:41:48 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> Message-ID: <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> On Jun 2, 9:07 am, Antoon Pardon wrote: > On 2008-06-02, Carl Banks wrote: > > > > > On Jun 2, 6:40 am, Antoon Pardon wrote: > >> On 2008-06-02, Carl Banks wrote: > > >> > On Jun 2, 5:38 am, Antoon Pardon wrote: > >> >> If you really need it, you can do data hiding in python. It just > >> >> requires a bit more work. > > >> >> ----------------------------- Hide.py --------------------------------- > >> >> class Rec(object): > >> >> def __init__(__, **kwargs): > >> >> for key,value in kwargs.items(): > >> >> setattr(__, key, value) > > >> >> def __getitem__(self, key): > >> >> return getattr(self, key) > > >> >> def __setitem__ (self, key, val): > >> >> setattr(self, key, val) > > >> >> class Foo(object): > > >> >> def __init__(self): > > >> >> hidden = Rec(x=0, y=0) > > >> >> def SetX(val): > >> >> hidden.x = val > > >> >> def SetY(val): > >> >> hidden.y = val > > >> >> def GetX(): > >> >> return hidden.x > > >> >> def GetY(): > >> >> return hidden.y > > >> >> self.SetX = SetX > >> >> self.SetY = SetY > >> >> self.GetX = GetX > >> >> self.GetY = GetY > > >> > In other words, it's a useless no-op. > > >> > In fact, I'd say this is even worse than useless. Creating accessor > >> > functions is a sort of blessing for external use. Knowing that there > >> > are accessor functions is likely to cause a user to show even less > >> > restraint. > > >> I think you completed missed the point. > > > I'm not sure I missed the point so much as I failed to read your mind. > > Fine with me, it is just the other side of the coin. > > >> This is just a proof of concept thing. In a real example there would > >> of course no Set en Get methods but just methods that in the course > >> of their execution would access or update the hidden attributes > > > Fair enough, but I don't see anything in your example that suggests a > > way to discriminate between access from within the class and access > > from outside the class, which is the crucial aspect of data hiding. > > The fact is that hidden and its attributes are not accessible from > outside the instance. They are only accessible to the local functions > of __init__. By binding those local functions as atributes to the > instance, hidden can be modified by what for all practical purposes > looks like a method call, but really is a closure call. You haven't hidden the data at all, all you've done is to change the means of accessing it. What difference does it make whether I write foo.getX() or foo.x? Everyone in the world still has full access to the data. You are not realizing that only useful(**) thing about data hiding is that some code has access to the data, other code does not. If you "hide" data equally from everyone it's just a useless spelling change. ** - Usefulness is questionable in most cases, but we assume it is here for the sake of argument. Carl Banks From cournape at gmail.com Wed Jun 4 09:47:45 2008 From: cournape at gmail.com (David Cournapeau) Date: Wed, 4 Jun 2008 22:47:45 +0900 Subject: How to make py2.5 distutil to use VC2005? In-Reply-To: References: Message-ID: <5b8d13220806040647o1148bf90x6b2b546e9cb339b5@mail.gmail.com> On Wed, Jun 4, 2008 at 11:38 AM, ?? wrote: > Well, IMO, the format of binary files generated by VC2003 and > VC2005 is compatible in most cases. Problem arise with the C runtime, not with object file format. In particular, python uses the C api for file handling, and the standard C is definitely not ABI compatible within VS versions. I strongly advise you against using VS 2005 (with the binary python; if you build python by yourself, then no problem; I don't know if it is possible to build python with VS 2005). You *will* get crashes in many cases. David From wuwei23 at gmail.com Tue Jun 3 01:23:52 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 2 Jun 2008 22:23:52 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> Message-ID: <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> On Jun 3, 2:11 pm, "Russ P." wrote: > Yes, that looks interesting, but I think it has a couple of drawbacks. > First, it requires another completely separate class for the > "implementation" (although perhaps that could be a nested class). That's hardly an enormous overhead, and it does clearly separate the interface you want your "users" to have from the implementation. Even better, since you seem so concerned with others meddling with your implementation directly, they could provide their own quite easily if they so choose. > Secondly, I think it essentially just adds a sort of inner namespace > through which the "private" data is accessed. That might be a good > idea, but I don't think it's quite the same as encapsulation. It's a clear separation of concerns, check. It removes the underscored methods you find so aesthetically offensive, check. I have absolutely no idea what _you_ mean by "encapsulation". Then again, I have no issue with the current convention and personally find the idea of adding a "private" keyword makes as much sense as being able to syntactically define "model", "view" and "controller" methods. From benjamin.kaplan at case.edu Sun Jun 29 11:42:33 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 29 Jun 2008 11:42:33 -0400 Subject: gelato - nvidia and python In-Reply-To: <65fcd6a4-131e-4d7c-96b3-402296bf2a18@y21g2000hsf.googlegroups.com> References: <65fcd6a4-131e-4d7c-96b3-402296bf2a18@y21g2000hsf.googlegroups.com> Message-ID: On Sun, Jun 29, 2008 at 11:34 AM, catalinfest at gmail.com < catalinfest at gmail.com> wrote: > Did somebody worked with gelato from nvidia and python? > I have some C cod from books nvidia . > This is : > " > GelatoAPI *r = GelatoAPI::CreateRenderer(); > r->Camera ("main"); > ... API calls through r ... > r->Render ("main"); > delete r; // Finished with this renderer > " > the code for python i create is only this : > " > python > Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) > [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import gelato > >>> from gelato import * > >>> r=gelato.CreateRenderer > >>> print r > > >>> dir(r) > ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', > '__getattribute__', '__hash__', '__init__', '__module__', '__name__', > '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', > '__setattr__', '__str__'] > " > And I blocked here... > Thank you . > -- You are looking at the function CreateRenderer, not the Renderer object. Try doing this: >>> import gelato >>> r = gelato.CreateRenderer*()* >>> dir(r) > > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eckhardt at satorlaser.com Tue Jun 24 12:01:42 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 24 Jun 2008 18:01:42 +0200 Subject: percent string replacement with index Message-ID: <7ci7j5-uu7.ln1@satorlaser.homedns.org> Hi! I'm still mostly learning Python and there is one thing that puzzles me about string formatting. Typical string formatting has these syntaxes: "%s is %s" % ("GNU", "not Unix") "%(1)s %(2)s" % ("1":"one", "2":"two") What I'm surprised is that this isn't supported: "%(1)s %(2)s" % ("zero", "one", "two") i.e. specifying the index in a sequence instead of the key into a map (maybe I would use [1] instead of (1) though). Further, the key can't be a simple number it seems, which makes this even more inconvenient to me. Can anyone explain this to me? Also, why isn't the 's' conversion (i.e. to a string) the default? I personally would like to just write something like this: "%1 is not %2" % ("zero", "one", "two") or maybe "%[1] is not %[2]" % ("zero", "one", "two") greetings! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From ethan at stoneleaf.us Wed Jun 11 10:39:43 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 11 Jun 2008 06:39:43 -0800 Subject: Alternative to Decimal type In-Reply-To: References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: <484FE3AF.5020504@stoneleaf.us> Frank Millman wrote: > Thanks to all for the various replies. They have all helped me to > refine my ideas on the subject. These are my latest thoughts. > > Firstly, the Decimal type exists, it clearly works well, it is written > by people much cleverer than me, so I would need a good reason not to > use it. Speed could be a good reason, provided I am sure that any > alternative is 100% accurate for my purposes. [snip] > For addition, subtraction, multiplication and division, the 'other' > number can be any of 2, 3, or 4 above. The result is a new Number > instance. The scale of the new instance is based on the following rule > > For addition and subtraction . . . > For multiplication . . . > For division . . . Out of curiosity, what is the purpose of these numbers? Do they represent money, measurements, or something else? The reason I ask is way back in physics class (or maybe chemistry... it was way back :) I was introduced to the idea of significant digits -- that idea being that a measured number is only accurate to a certain degree, and calculations using that number therefore could not be more accurate. Sort of like a built-in error range. I'm thinking of developing the class in the direction of maintaining the significant digits through calculations... mostly as I think it would be fun, and it also seems like a good test case to get me in the habit of unit testing. I'll call it something besides Number, though. :) Is anybody aware of such a class already in existence? -- Ethan From david at boddie.org.uk Fri Jun 20 18:21:39 2008 From: david at boddie.org.uk (David Boddie) Date: Sat, 21 Jun 2008 00:21:39 +0200 Subject: py2exe, PyQT, QtWebKit and jpeg problem References: Message-ID: On Friday 20 June 2008 17:24, Phil Thompson wrote: > On Fri, 20 Jun 2008 08:04:57 -0700 (PDT), Carbonimax > wrote: >> I have a problem with py2exe and QtWebKit : >> I make a program with a QtWebKit view. >> If I launch the .py directly, all images (jpg, png) are displayed but >> if I compile it with py2exe I have only png images. No jpg ! >> No error message, nothing. >> >> Have you a solution ? Thank you. > > At a guess, the JPEG support is implemented as a Qt plugin which you are > not including. Yes, that would appear to the be most obvious cause. See here for another report about this: http://lists.trolltech.com/qt4-preview-feedback/2008-03/msg00064.html David From goldnery at gmail.com Tue Jun 17 12:43:01 2008 From: goldnery at gmail.com (Gandalf) Date: Tue, 17 Jun 2008 09:43:01 -0700 (PDT) Subject: text alignment Message-ID: <39d1c620-9923-46e7-999d-ed86c8b465ff@34g2000hsh.googlegroups.com> Hi every one. What is the similar python WX style property for CSS text-align? I need this item text to start from the right direction: aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60)) aaa.LoadPage('../../aa.html') Thanks! From gabriel.rossetti at arimaz.com Wed Jun 11 03:21:03 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Wed, 11 Jun 2008 09:21:03 +0200 Subject: h2py.py bug? In-Reply-To: References: <484E771D.1050404@arimaz.com> Message-ID: <484F7CDE.9000300@arimaz.com> Gabriel Genellina wrote: > En Tue, 10 Jun 2008 09:44:13 -0300, Gabriel Rossetti > escribi?: > >> I wanted to use the h2py.py script (Tools/scripts/h2py.py) and it >> didn't like char litterals : >> >> Skipping: PC_ERROR = ord() >> >> where my *.h file contained : >> >> #define PC_ERROR '0' >> >> I searched the web and found a post with the same error : >> >> http://mail.python.org/pipermail/python-list/2005-September/340608.html >> >> but it got no replies, I tried the fix and it works. I have the >> following questions: >> >> 1) Why did it not get any attention, is something wrong with it? >> 2) If nothing is wrong, did the fix not get applied because a bug >> report wasn't filed? > > Very probably - bug reports outside the tracker are likely to go > unnoticed or forgotten. > Ok, I'll file one then. >> 3) Isn't turning a char literal into the ordinal value not contrary >> to what a C programmer had in mind when he/she defined it? I mean if >> you define a char literal then in python you would have used a string >> value : >> >> #define PC_ERROR '0' >> >> would become : >> >> PC_ERROR = '0' >> >> in python, and if you intended to use the char type for an 8 bit >> numerical value you would have done : >> >> #define PC_ERROR 0x30 >> >> where 0x30 is the '0' ascii hex value, so shouldn'it the line in the >> diff (see the post) be : >> >> body = p_char.sub("'\\1'", body) >> >> instead of : >> >> body = p_char.sub("ord('\\1')", body) > > It's not so clear what's the intended usage - chars are also integers > in C. (I prefer the current behavior, but certainly it may be wrong in > several places). > Yes, true, but if you intend to use it as an integer, wouldn't you use a numeric value instead of a character literal? From asmodai at in-nomine.org Thu Jun 19 10:39:42 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 19 Jun 2008 16:39:42 +0200 Subject: Extending Python with C: Cannot find MPI library In-Reply-To: <9100a146-a0bb-4958-a7c6-f23c9b518e89@a1g2000hsb.googlegroups.com> References: <9100a146-a0bb-4958-a7c6-f23c9b518e89@a1g2000hsb.googlegroups.com> Message-ID: <20080619143942.GL97799@nexus.in-nomine.org> -On [20080619 16:21], Spectrum (spectrumdt at gmail.com) wrote: > libmpi.so.0 => /usr/lib/openmpi/1.2.4-gcc/libmpi.so.0 >(0x0042f000) > libopen-rte.so.0 => /usr/lib/openmpi/1.2.4-gcc/libopen- >rte.so.0 (0x003d4000) > libopen-pal.so.0 => /usr/lib/openmpi/1.2.4-gcc/libopen- >pal.so.0 (0x00344000) These libraries are what your binaries (.so and such) needs to link against as well. I am not sure if you have to add a flag (-mpi) to your compiler or if you need to add a -L/usr/lib/openmpi/1.2.4-gcc -lmpi -lopen-rte -lopen-pal to the incantations. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B The distance to here is infinite... From eliben at gmail.com Fri Jun 20 15:37:09 2008 From: eliben at gmail.com (eliben) Date: Fri, 20 Jun 2008 12:37:09 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> Message-ID: <8d9283f0-2618-408b-9b75-bf6841dea44e@k37g2000hsf.googlegroups.com> > FWIW, when I had a similar challenge for dynamic coding, I just > generated a py file and then imported it. This technique was nice > because can also work with Pyrex or Psyco. > I guess this is not much different than using exec, at the conceptual level. exec is perhaps more suitable when you really need just one function at a time and not a whole file of related functions. > Also, the code above can be simplified to: get_counter = lambda > packet: packet[5:1:-1] > OK, but that was just a demonstration. The actual functions are complex enough to not fit into a single expression. Eli From johnjsal at NOSPAMgmail.com Mon Jun 16 09:14:38 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 16 Jun 2008 09:14:38 -0400 Subject: newbie question: for loop within for loop confusion References: Message-ID: <02a1b83d$0$25034$c3e8da3@news.astraweb.com> "takayuki" wrote in message news:ba3ce6db-6d2b-4de4-b1d2-00b95fefa8a8 at g16g2000pri.googlegroups.com... > John: There were two "inchworms" because "c" is in "inchworm" so it > shouldn't print. Thanks for your detailed description of the for > loop. lol, I even sat there looking at the word and said to myself "ok, it doesn't contain any of the four letters" :) From marc.wyburn at googlemail.com Fri Jun 13 05:41:30 2008 From: marc.wyburn at googlemail.com (marc wyburn) Date: Fri, 13 Jun 2008 02:41:30 -0700 (PDT) Subject: boolian logic References: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> Message-ID: On 13 Jun, 10:34, Aidan wrote: > marc wyburn wrote: > > HI all, I'm a bit stuck with how to work outboolianlogic. > > > I'd like to say if A is not equal to B, C or D: > > ? ?do something. > > > I've tried > > > if not var == A or B or C: > > and various permutations but can't seem to get my head around it. ?I'm > > pretty sure I need to know what is calulated first i.e the not or the > > 'OR/AND's > > > thanks, Marc. > > You mean like a ternary operation? > > ?>>> True and 1 or 0 > 1 > ?>>> False and 1 or 0 > 0 > > This of course depends on the 'true' result also being true.. it fails > if it is false... > > if that's not what you mean, then maybe this is what you want > > if not var==A or not var==B or not var==C: > ? ? ?# do something the not var==A or not var==B or not var==C was what I was after. I was being too literal with my script and trying not (A or B or C) which doesn't work. Thanks for the help. From grante at visi.com Tue Jun 10 22:43:54 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 10 Jun 2008 21:43:54 -0500 Subject: problems with opening files due to file's path References: <17759531.post@talk.nabble.com> <17761338.post@talk.nabble.com> <902d753e-4eb8-4eb9-b907-3bd1c735af9d@j22g2000hsf.googlegroups.com> Message-ID: <_7ydnVc3Q5Z3ptLVnZ2dnUVZ_jqdnZ2d@posted.visi> On 2008-06-11, Alexnb wrote: >>>> path = "C:\Documents and Settings\Alex\My Documents\My >>>> Music\Rhapsody\Bryanbros\Jason Mraz\I'm Yours (Single)\01 - I'm >>>> Yours.wma" Your string doesn't contain what you think it does. Do a "print path". Hint: the string "\01" consists of a single byte who's value is 001 base 8. >>>> os.startfile(path) > Traceback (most recent call last): > File "", line 1, in > os.startfile(path) > WindowsError: [Error 2] The system cannot find the file specified: > "C:\\Documents and Settings\\Alex\\My Documents\\My > Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\x01 - I'm > Yours.wma" Notice that the string in the error message contains \x01? That's the byte that got changed. > Here's another way: > >>>> os.startfile(r"%s"%path) > Traceback (most recent call last): > File "", line 1, in > os.startfile(r"%s"%path) > WindowsError: [Error 2] The system cannot find the file specified: > "C:\\Documents and Settings\\Alex\\My Documents\\My > Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\x01 - I'm > Yours.wma" > > Same output, however if I personally input it like so: > >>>> os.startfile("C:\\Documents and Settings\\Alex\\My Documents\\My >>>> Music\\Rhapsody\\Bryanbros\\Jason Mraz\\I'm Yours (Single)\\01 - I'm >>>> Yours.wma") > > It works out fine because I can make each backslash doubles so it doesn't > mess stuff up. Right. > So if I could take the path varible and make ever "\" into a > "\\" then it would also work. I don't understand the part about the path variable. The backslash character is used in both C and Python as an escape character so that you can encode special values in string literals. For example: '\r' is a carriage return '\n' is a linefeed, \0nnn is a single byte with the octal value nnn, and so on. Microsoft's choice of '\' as a path separator was a terribly bad one (one of many made by Microsoft over the years). Most Windows system calls will accept forward slashes, so the easiest thing to do is usually just type the strings with forward slashes. -- Grant Edwards grante Yow! NOW do I get to blow at out the CANLDES?? visi.com From ananth99899 at gmail.com Sat Jun 21 01:40:51 2008 From: ananth99899 at gmail.com (www.hollywoodpopstars.blogspot.com) Date: Fri, 20 Jun 2008 22:40:51 -0700 (PDT) Subject: Kerala Couples Enjoying SEX At NET CAFE CENTER Message-ID: <59924f7f-2981-4551-8aab-cce4737ef135@i36g2000prf.googlegroups.com> Hi....Friends, watch and enjoy SECRET WEB-CAMS at LADIES HOSTELS and INTERNET CAFE SEX SCANDALS VIDEOS... http://www.hollywoodpopstars.blogspot.com http://www.googlemobilesphones.blogspot.com From nagle at animats.com Sun Jun 8 00:33:02 2008 From: nagle at animats.com (John Nagle) Date: Sat, 07 Jun 2008 21:33:02 -0700 Subject: multiprocessing module (PEP 371) In-Reply-To: <1c867dff-a909-4b9e-99ec-b096ddfbd83d@c58g2000hsc.googlegroups.com> References: <877a5774-d3cc-49d3-bb64-5cab8505a419@m3g2000hsc.googlegroups.com> <1c867dff-a909-4b9e-99ec-b096ddfbd83d@c58g2000hsc.googlegroups.com> Message-ID: <484b5d74$0$17208$742ec2ed@news.sonic.net> sturlamolden wrote: > On Jun 5, 11:02 am, pataphor wrote: > >> This is probably not very central to the main intention of your post, >> but I see a terminology problem coming up here. It is possible for >> python objects to share a reference to some other object. This has >> nothing to do with threads or processes, although it can be used as a >> *mechanism* for threads and processes to share data. > > It is complicated in the case of processes, because the object must be > kept in shared memory. The complicating factor is that the base > address of the memory mapping, which is not guaranteed to be the same > in the virtual address space of different processes. Introducing shared memory in Python would be a terrible idea, for many reasons, including the need for interprocess garbage collection and locking. Don't go there. Use message passing instead. John Nagle From exarkun at divmod.com Mon Jun 16 06:59:34 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 16 Jun 2008 06:59:34 -0400 Subject: Python GC does not work as it should be In-Reply-To: Message-ID: <20080616105934.4714.1605358387.divmod.quotient.9670@ohm> On Mon, 16 Jun 2008 17:51:00 +0700, Jaimy Azle wrote: >See this piece of code: > >/* API to invoke gc.collect() from C */ >Py_ssize_t >PyGC_Collect(void) >{ > Py_ssize_t n; > > if (collecting) > n = 0; /* already collecting, don't do anything */ > else { > collecting = 1; > n = collect(NUM_GENERATIONS - 1); > collecting = 0; > } > return n; >} > >If a system exception raised when executing collect(xxx), collecting state >variable would never be reset and python GC will not works forever until the >application restarted. A system exception? What's that? C doesn't have exceptions. Jean-Paul From dullrich at sprynet.com Thu Jun 12 13:39:29 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 12 Jun 2008 12:39:29 -0500 Subject: Making wxPython a standard module? References: Message-ID: In article , "Andrea Gavana" wrote: > Hi Diez & All, > > > And on a personal note: I find it *buttugly*. > > Do you mind explaining "why" you find it *buttugly*? My guess would be that "buttugly" is a colloquialism meaning "exquisitely lovely". >I am asking just > out of curiosity, obviously. I am so biased towards wxPython that I > won't make any comment on this thread in particular, but I am curious > to know why some people find it "ugly" or "bad" or whatever. It has > its own bugs and missing features, of course, but it is one of the > major GUI player in the arena, together with PyQt and PyGTK. > > Andrea. > > "Imagination Is The Only Weapon In The War Against Reality." > http://xoomer.alice.it/infinity77/ -- David C. Ullrich From aspersieman at gmail.com Fri Jun 20 03:42:23 2008 From: aspersieman at gmail.com (Aspersieman) Date: Fri, 20 Jun 2008 09:42:23 +0200 Subject: don't make it worse! - was Re: SPAM In-Reply-To: <485AE162.8050407@gmail.com> References: <88f0c3ba-46e1-4b30-a61d-482e5ecf339a@t12g2000prg.googlegroups.com> <485A0E77.2050009@gmail.com> <485AE162.8050407@gmail.com> Message-ID: <485B5F5F.8070207@gmail.com> An HTML attachment was scrubbed... URL: From s0suk3 at gmail.com Tue Jun 24 19:06:43 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Tue, 24 Jun 2008 16:06:43 -0700 (PDT) Subject: shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": References: <09b41308-0167-4231-b5e7-5baa1a9aff9d@u6g2000prc.googlegroups.com> Message-ID: <3b12d826-4a10-4ed3-b66e-f28f64910f05@m3g2000hsc.googlegroups.com> On Jun 24, 5:36 pm, John Machin wrote: > On Jun 25, 4:32 am, cirfu wrote: > > > if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": > > > cant i write something like: > > if char in "[A-Za-z]": > > You can write that if you want to, but it's equivalent to > if char in "zaZa]-[": > i.e. it doesn't do what you want. > > This gives the same reuslt as your original code, unaffected by > locale: > > if "A" <= char <= "Z" or "a" <= char <= "z": But doesn't that rely on the underlying character set? It's like performing math on C char's (maybe that's what the interpreter does internally?). If that's the case, using 'char.isalpha()' or 'char in string.letters' or regex's would be better. From dgetsman at amirehab.net Fri Jun 27 12:36:04 2008 From: dgetsman at amirehab.net (Damon Getsman) Date: Fri, 27 Jun 2008 09:36:04 -0700 (PDT) Subject: what is meaning of "@" in pyhon program. References: <88990b3d-1916-413f-83b9-796aabf43623@l28g2000prd.googlegroups.com> <19aa4978-242b-4732-b072-aa5ff16975b0@27g2000hsf.googlegroups.com> <486502bf$0$6426$426a74cc@news.free.fr> <4bfb891d-7a7b-45bc-b126-1d485c9206ee@m44g2000hsc.googlegroups.com> <48650adb$0$7975$426a74cc@news.free.fr> Message-ID: I didn't think that it was. I just spent about 10 minutes trying to google for the page that I found that on, but I wasn't able to turn it up. My google-fu sucks. I know that I was researching a particular part of the os module and that the snippets of script on the page had an example containing '@if' and '@for'. I don't remember what exactly I used to turn it up before, though, and the link isn't in my history, it was probably a month ago that I saw it. Sorry, I tried. On Jun 27, 10:44?am, Bruno Desthuilliers wrote: > Damon Getsman a ?crit : > > ie: > > @if os.exists(foo): > > ? ?etc > > ? ?etc > > > and > > > @for blah: > > ? ?etc > > ? ?etc > > This is not valid Python. period. From http Wed Jun 4 07:24:19 2008 From: http (Paul Rubin) Date: 04 Jun 2008 04:24:19 -0700 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> Message-ID: <7xk5h5tpcs.fsf@ruckus.brouhaha.com> NickC writes: > if/else was added solely because people kept coming up with ways of > embedding a pseudo conditional inside expressions and writing buggy > code in the process. All it really saves you in practice is a bit of > vertical whitespace, so, no, you still don't need it - but if you > insist on doing it, at least there's now an easy way to do it > correctly. Come on, it's more than vertical whitespace, it's extraneous variables and sometimes even extraneous functions and function call overhead. And Python is supposed to be unbureaucratic. People kept looking for ways to write conditional expressions instead of spewing the logic across multiple statements for a reason: the code is often cleaner that way. From bruno.42.desthuilliers at websiteburo.invalid Tue Jun 10 05:12:15 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 10 Jun 2008 11:12:15 +0200 Subject: Question by someone coming from C... In-Reply-To: References: Message-ID: <484e451b$0$10973$426a74cc@news.free.fr> Skye a ?crit : > Writing this app in Python, not sure what the "best practice" would > be. > > I want a bitfield global logging level that allows me to turn specific > debugging modules on and off. If I was doing this in C, I'd just use > some globals like: > > unsigned int debug_level = 0; > #define DEBUG_GENERAL 0x0001 > #define DEBUG_CONFIG 0x0002 > #define DEBUG_OPTIONS 0x0004 > etc etc > > So I guess my questions are: > > 1. there doesn't seem to be a way to define global constants like in > other languages? > 2. any special voodoo to use bitfields in Python? Others already gave you the best advises (namely: using the logging module). But let's answer your questions anyway: 1/ by convention, anything named ALL_UPPER is considered a constant. Anyone breaking your code by messing with a PSEUDO_CONSTANT is on it's own and has no right to complain. Consider it as a "warranty void if unsealed" warning. 2/ just use plain integers and bitwise operators. But we're usually more concerned about readability than about saving bits, and I've rarely (maybe twice ?) seen bitfields used that way in Python. From george.sakkis at gmail.com Fri Jun 13 19:02:26 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 13 Jun 2008 16:02:26 -0700 (PDT) Subject: importing part of a module without executing the rest References: Message-ID: On Jun 13, 5:52 pm, krishna.00... at gmail.com wrote: > file1.py > ---------- > a = 20 > from abc import * > print "Should this be printed when 'a' is alone imported from this > module" > > file2.py > ---------- > from file1 import a > print a > > (snipped) > > Of course, the option of using if __name__ == '__main__' in file1.py > for statements following 'a = 20' is not useful in my case as I need > all statements in file1 to be exectued when imported by someone else > (say file3.py) That's a bad code smell. In general, modules intended to be imported should not have any side effects at global scope before the "if __name__ == '__main__':" part. Put the "print ..." and all other statements with side effects in one or more functions and let the importing module call them explicitly if necessary. George From niklas.norrthon at hotmail.com Wed Jun 11 02:07:16 2008 From: niklas.norrthon at hotmail.com (Niklas Norrthon) Date: Tue, 10 Jun 2008 23:07:16 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> <4847d203$0$32733$426a74cc@news.free.fr> <87lk1jzgri.fsf@mulj.homelinux.net> <39a7805f-6590-4505-bfa2-0735090d553b@t12g2000prg.googlegroups.com> Message-ID: On 6 Juni, 03:09, "Russ P." wrote: > On Jun 5, 2:57 pm, Hrvoje Niksic wrote: > > > "Russ P." writes: > > > By the way, my recollection is that in C++ access defaults to private > > > if nothing is declared explicity. So normally the "private" > > > declaration is unnecessary. If it is left out, your little trick won't > > > work. > > > How about #define class struct > > I never thought of that one. I wonder what the C++ gurus would say > about that. > > Let me guess. They'd probably say that the access restrictions are for > your own good, and bypassing them is bound to do you more harm than > good in the long run. And they'd probably be right. Just because you > can break into a box labeled "DANGER HIGH VOLTAGE," that doesn't make > it a good idea. > > This just goes to show that the whole idea of using header files as > simple text insertions is flaky to start with, and adding the > preprocessor just compounds the flakiness. Needless to say, I'mnota > big fan of C and C++. From i.i at i.i Thu Jun 26 12:21:39 2008 From: i.i at i.i (Josip) Date: Thu, 26 Jun 2008 18:21:39 +0200 Subject: Storing value with limits in object References: <6tednUvC9-jDxMPVnZ2dnUVZ_hGdnZ2d@comcast.com> Message-ID: Thanks alot. I'm going to use this with few modifications to tailor it to my needs. Thumbs up! > #!/usr/bin/env python > > ## VERSION 2 > ## > ## changelog: > ## - Uses inheritance from _Limited > ## - Added _LimitedLong and llong > ## - limit choose between int, long, and float > > class _Limited(object): > def setlimits(self, lim): > ''' Set the limits and if value is not within limit, > raise ValueError > > The lim argument accepts: > - An instance of _Limited, from which to copy the limits > - A two-tuple, which specifies the limits i.e. (min, max) > > If lim isn't those or lim[0] > lim[1], raise > InvalidLimitsError > > Accepting _Limited instance is just for convenience > ''' > > if isinstance(lim, _Limited): > self.min, self.max = lim.limits > else: > try: > self.min, self.max = lim > if self.min > self.max: raise ValueError > except (ValueError, TypeError): > raise self.InvalidLimitsError, ('limit = %s' % > str(lim)) > > if not (self.min < self < self.max): > raise ValueError, \ > ('val = %s, min = %s, max = %s' % \ > (self, self.min, self.max)) > > def getlimits(self): > return (self.min, self.max) > > limits = property(getlimits, setlimits) > > class _LimitedInt(int, _Limited): > def __init__(self, value, base = 10): > int.__init__(value, base) > > class _LimitedLong(long, _Limited): > def __init__(self, value, base = 10): > long.__init__(value, base) > > class _LimitedFloat(float, _Limited): > def __init__(self, value): > float.__init__(value) > > > def lint(value, limits, base = None): > ''' Always Creates _LimitedInt instance, allows the use of base > ''' > if base: > ret = _LimitedInt(value, base) > else: > ret = _LimitedInt(value) > > ret.limits = limits > return ret > > def llong(value, limits, base = None): > ''' Always Creates _LimitedLong instance, allows the use of base > ''' > if base: > ret = _LimitedLong(value, base) > else: > ret = _LimitedLong(value) > > ret.limits = limits > return ret > > def lfloat(value, limits): > ''' Always Creates _LimitedFloat instance > ''' > ret = _LimitedFloat(value) > > ret.limits = limits > return ret > > def limit(value, limits): > ''' Automatically choose between _LimitedInt, _LimitedLong, > or _LimitedFloat. Cannot use _LimitedInt's/Long's base > ''' > if isinstance(value, (int, long)): > try: > ret = _LimitedInt(value) > except OverflowError: > ret = _LimitedLong(value) > elif isinstance(value, float): > ret = _LimitedFloat(value) > > ret.limits = limits > return ret From geonomica at gmail.com Fri Jun 6 13:04:18 2008 From: geonomica at gmail.com (gianluca) Date: Fri, 6 Jun 2008 10:04:18 -0700 (PDT) Subject: ctypes help Message-ID: hy, I've a huge problem with ctypes. I've compiled my C library and I'd like use it in python with ctype. One function need to pass a pointer to typed ( like this: typedef int value_type). In python I can access to that funtion but arise an exception because python don't know my value_type typedef. Please I need help, could anybody help me? Gianluca From thor__00 at yahoo.com Wed Jun 11 07:23:05 2008 From: thor__00 at yahoo.com (Thor) Date: Wed, 11 Jun 2008 13:23:05 +0200 Subject: Parallel python + ?? Message-ID: Hi, I am running a program using Parallel Python and I wonder if there is a way/module to know in which CPU/core the process is running in. Is that possible? ?ngel From socyl at 987jk.com.invalid Fri Jun 20 08:37:25 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 20 Jun 2008 12:37:25 +0000 (UTC) Subject: ISO dict => xml converter Message-ID: Hi. Does anyone know of a module that will take a suitable Python dictionary and return the corresponding XML structure? In Perl I use XML::Simple's handy XMLout function: use XML::Simple 'XMLout'; my %h = ( 'Foo' => +{ 'Bar' => +{ 'Baz' => [ { 'meenie' => 3 }, { 'meenie' => 7 } ], 'eenie' => 4, }, 'minie' => 1, 'moe' => 2, } ); print XMLout( \%h, KeepRoot => 1, KeyAttr => undef ); __END__ Is there a Python module that can do a similar conversion from a Python dict to an XML string? (FWIW, I'm familiar with xml.marshal.generic.dumps, but it does not produce an output anywhere similar to the one illustrated above.) TIA! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From bob at mellowood.ca Thu Jun 12 15:06:15 2008 From: bob at mellowood.ca (bvdp) Date: Thu, 12 Jun 2008 12:06:15 -0700 Subject: howto split string with both comma and semicolon delimiters References: <3e2540ab-1d2a-45a5-a5b6-3f7ae7a4efac@x35g2000hsb.googlegroups.com> Message-ID: dmitrey wrote: > hi all, > howto split string with both comma and semicolon delimiters? > > i.e. (for example) get ['a','b','c'] from string "a,b;c" > > I have tried s.split(',;') but it don't work > Thx, D. Howabout: s = s.replace(";", ",") s = s.split(",") From lew at lewscanon.com Mon Jun 30 07:51:21 2008 From: lew at lewscanon.com (Lew) Date: Mon, 30 Jun 2008 07:51:21 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: Message-ID: Robert Maas wrote: > /----------------------------------------------------------------------------\ > | ,-.-. | | > | | | |, . ,---.,---.,---. ,---.,---.,---.,---|,---. | > | | | || | `---.| || | | ||---'|---'| |`---. | > | ` ' '`---| `---'`---'` ' ` '`---'`---'`---'`---' | > | `---' | > | | | o | | | > | |---.,---.| ,---. .,---. ,---.| ,---.,---. |---.,---.,---. | > | | ||---'| | | || | ,---|| | ||---'---| || ,---| | > | ` '`---'`---'|---' `` ' `---^`---'`---|`---' `---'` `---^ | | > | | `---' ' | > | | | | | > | ,---.,---.|--- . . .,---.,---.,---|,---.,---. |---.,---.,---. | > | | || || | | || || || ||---'| ---| || ,---| | > | ` '`---'`---' `-'-'`---'` '`---'`---'` `---'` `---^o | > \--------(Rendered by means of )--------/ > (You don't need JavaScript or images to see that ASCII-text image!! > You just need to view this in a fixed-pitch font such as Monaco.) > > Then enter your best guess of the text (40-50 chars) into this TextField: > +--------------------------------------------------+ > | Your son totally needs a Wonder-Bra(r), double-D | > +--------------------------------------------------+ -- Lew From celoserpa at gmail.com Wed Jun 11 02:22:05 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Wed, 11 Jun 2008 03:22:05 -0300 Subject: Using ElementTree as backend for a chat web application issues In-Reply-To: References: <1e5bcefd0806091132p78f42109t1edb5e5acfaadb43@mail.gmail.com> Message-ID: <1e5bcefd0806102322k3e069cfanba6ba9ee01332e54@mail.gmail.com> Well folks, I appreciate your help, but I've got the problem solved by re-implementing the chat backend (server) in Rails. It is working great now (persisting the data in a mysql database, instead of XML files). At least this has led me to search more about concurrent issues and programming. I'm still confused on why this doesn't happen with my Rails backend, but I will eventually find out. Living and learning. Thanks for the attention, Marcelo. On Wed, Jun 11, 2008 at 12:47 AM, Gabriel Genellina wrote: > En Mon, 09 Jun 2008 15:32:00 -0300, Marcelo de Moraes Serpa < > celoserpa at gmail.com> escribi?: > > I've built a chat with a front-end Ajax client and backend usign >> ElementTree >> to persist the data. >> >> In some circunstances I could not yet discover (it seems random) when I >> edit/save the structure, the structure gets corrupted, elementree seems to >> get lost in its internal "cursor", usually something like this happens: >> >> >> >> >> >> >> id="3"/> >> >> Pretty strange, and it drives the whole application unusable. >> >> I don't know if the concurrent nature of the application (multiple users >> using the client at almost the same time and sending data to the server >> which in turn must save the data to the same global.xml file) has >> something >> to do with it - I don't know if ElementTree is suitable for this kind of >> thing. How to hanlde this concurrent issue? >> > > I don't think it's a problem with ElementTree. Perhaps you are writing the > same (global) configuration file from several threads at the same time? You > may need some locking mechanism in that case. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Thu Jun 26 20:44:44 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 26 Jun 2008 17:44:44 -0700 (PDT) Subject: list previous or following list elements References: Message-ID: <0d455050-45f1-4f39-b237-db06a4d43212@x35g2000hsb.googlegroups.com> Terry Reedy: > I believe > wordlist = open('words.txt','r').read().split('\n') > should give you the list in Python. This looks better (but it keeps the newlines too. Untested. Python 2.x): words = open("words.txt").readlines() for i, word in enumerate(words): if word.startswith("b"): print words[i+1] break Another possibility (untested, lazy, uses less memory, probably better): fin = open("words.txt") last_word = fin.next() for word in fin: if last_word.startswith("b"): print word break else: last_word = word fin.close() A note for the original poster: I suggest you to try to learn string methods (not the string module), they are designed to avoid you to use regular expressions most of the times, and they are faster and more readable too. I have seen that people that learn Python coming from Perl are often 'blind' to their existence. Bye, bearophile From __peter__ at web.de Wed Jun 18 08:08:10 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 18 Jun 2008 14:08:10 +0200 Subject: dict order References: Message-ID: Robert Bossy wrote: > I wish to know how two dict objects are compared. By browsing the > archives I gathered that the number of items are first compared, but if > the two dict objects have the same number of items, then the comparison > algorithm was not mentioned. If I interpret the comments in http://svn.python.org/view/python/trunk/Objects/dictobject.c?rev=64048&view=markup correctly it's roughly def characterize(d, e): return min(((k, v) for k, v in d.iteritems() if k not in e or e[k] != v), key=lambda (k, v): k) def dict_compare(d, e): result = cmp(len(d), len(e)) if result: return result try: ka, va = characterize(d, e) except ValueError: return 0 kb, vb = characterize(e, d) return cmp(ka, kb) or cmp(va, vb) Peter From fuzzyman at gmail.com Mon Jun 23 15:39:23 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 23 Jun 2008 12:39:23 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <79a1c500-1844-4405-8f52-21e845a85f9b@z66g2000hsc.googlegroups.com> Message-ID: <2e56b463-ccde-45ca-8c8f-de8debf9c3ad@2g2000hsn.googlegroups.com> On Jun 21, 7:52?am, Peter Otten <__pete... at web.de> wrote: > eliben wrote: > > On Jun 20, 2:44 pm, Peter Otten <__pete... at web.de> wrote: > >> eliben wrote: > >> > Additionally, I've found indentation to be a problem in such > >> > constructs. Is there a workable way to indent the code at the level of > >> > build_func, and not on column 0 ? > > >> exec"if 1:" + code.rstrip() > > >> Peter > > > Why is the 'if' needed here ? I had .strip work for me: > > A simple .strip() doesn't work if the code comprises multiple lines: > > >>> def f(): > > ... ? ? return """ > ... ? ? x = 42 > ... ? ? if x > 0: > ... ? ? ? ? ? ? print x > ... ? ? """ > ...>>> exec "if 1:\n" + f().rstrip() > 42 > >>> exec f().strip() > > Traceback (most recent call last): > ? File "", line 1, in > ? File "", line 2 > ? ? if x > 0: > ? ? ^ > IndentationError: unexpected indent > > You can of course split the code into lines, calculate the indentation of > the first non-white line, remove that indentation from all lines and then > rejoin. > textwrap.dedent will do all that for you... Michael Foord http://www.ironpythoninaction.com/ > Peter From brian_vanderburg2 at yahoo.com Thu Jun 26 11:18:08 2008 From: brian_vanderburg2 at yahoo.com (Allen) Date: Thu, 26 Jun 2008 11:18:08 -0400 Subject: Adding functions to an existing instance Message-ID: <27adnS2SrIrOLv7VnZ2dnUVZ_rjinZ2d@earthlink.com> I need a way to add a method to an existing instance, but be as close as possible to normal instance methods. Using 'new' module or such code as 'def addfunc(...): def helper(...) .. setattr(...)' causes a cyclic reference which requires using 'gc.collect' to release the object. Also 'new' is deprecated. I also made a helper that uses weakref, but the problem is when the object is gone, existing instance method object would not work: f = myobject.function myobject = None f() <--- would not work if it holds weak ref to myobject The best I can come up with is to create a parent class and try to simulate as best as possible. The code below works with no cyclic references that would be cause by 'new.instancemethod' etc, and without the weakref as well. Is there a simpler way of achieving the same without cyclic references? I know this is 'monkey patching' but for a small project I'm working on it is useful to be able to add functions dynamically to one instance without adding it to another instance of the same class, etc. class InstanceFunctionHelper(object): class FunctionCaller(object): def __init__(self, instance, func): self.__instance = instance self.__func = func def __call__(self, *args, **kwargs): return self.__func(self.__instance, *args, **kwargs) def add_instance_function(self, func, name = None): if name is None: name = func.__name__ if hasattr(self, name): delattr(self, name) try: self._instance_funcs[name] = func except AttributeError: self._instance_funcs = {name: func} def __setattr__(self, name, value): funcs = getattr(self, '_instance_funcs', None) if funcs and name in funcs: del funcs[name] object.__setattr__(self, name, value) def __delattr__(self, name): funcs = getattr(self, '_instance_funcs', None) if funcs and name in funcs: del funcs[name] else: object.__delattr__(self, name) def __getattr__(self, name): if name == '_instance_funcs': raise AttributeError funcs = object.__getattribute__(self, '_instance_funcs') if name in funcs: return InstanceFunctionHelper.FunctionCaller(self, funcs[name]) raise AttributeError x = 0 class Blah(InstanceFunctionHelper): def __init__(self): global x x += 1 def __del__(self): global x x -= 1 def Action(self, value): print self print value a = Blah() a.add_instance_function(Action) a.Action(5) a = None print x From ram.rachum at gmail.com Sun Jun 15 12:01:32 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Sun, 15 Jun 2008 09:01:32 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> Message-ID: On Jun 15, 6:58?pm, Christian Meesters wrote: > > I do need speed. Is there an option? > > Mind telling us what you *actually* want to achieve? (What do you want to > calculate?) > > Christian Physical simulations of objects with near-lightspeed velocity. From gabriel.rossetti at arimaz.com Sat Jun 28 14:03:31 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Sat, 28 Jun 2008 20:03:31 +0200 Subject: Do I need "self" and "other"? In-Reply-To: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> Message-ID: <48667CF3.1030402@arimaz.com> Kurda Yon wrote: > Hi, > > I found one example which defines the addition of two vectors as a > method of a class. It looks like that: > > class Vector: > def __add__(self, other): > data = [] > for j in range(len(self.data)): > data.append(self.data[j] + other.data[j]) > return Vector(data) > > In this example one uses "self" and "other". Does one really need to > use this words? And, if yes, why? I have replaced "self" by "x" and > "other" by "y" and everything looks OK. Is it really OK or I can have > some problem in some cases? > > Thank you! > -- > http://mail.python.org/mailman/listinfo/python-list > > > The first param "self" in an instance method is a convention, I would recommend not changing it. The "self" param is pass automatically when you call the method, like so : self.method(param) and this would have been defines as : def method(self, param): # do something here Self is like "this" in java, except it is explicitly added to the parameter list as the first parameter. You could name it whatever you want, but python programmers will throw tomatoes at you for naming it something else :-), since it mean "myself" in if the instance's perspective. Sometimes you have to pass it explicitly, like when calling your parent's method, be you'll see this when you study inheritance. I hope that helps, the "self" param had mixed me up some the first time I had seen it. Gabriel From rowland at river2sea.org Tue Jun 10 12:18:39 2008 From: rowland at river2sea.org (Rowland Smith) Date: Tue, 10 Jun 2008 12:18:39 -0400 Subject: chained exceptions Message-ID: Is anyone aware of a module or recipe for defining a composite/chained exception superclass? I've seen the PEP on chained exceptions wrt Python-3K, but I'm looking for something that is 2.5 compatible. -Rowland --------------------------- "The Dude abides." - The Dude, The Big Lebowski --------------------------- From exarkun at divmod.com Sat Jun 21 18:18:45 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 21 Jun 2008 18:18:45 -0400 Subject: Way to unblock sys.stdin.readline() call In-Reply-To: <37bbded6-af1c-4cd0-95fd-2b5536ec34cf@s50g2000hsb.googlegroups.com> Message-ID: <20080621221845.4714.468104778.divmod.quotient.11684@ohm> On Sat, 21 Jun 2008 12:35:02 -0700 (PDT), joamag wrote: >On Jun 21, 4:46 pm, C?dric Lucantis wrote: >> Le Saturday 21 June 2008 15:26:53 joamag, vous avez ?crit : >> >> > HI, >> >> > Is there any possible way to unblock the sys.stdin.readline() call >> > from a different thread. >> > Something like sys.stdin.write() but that would actually work ... >> > something to put characters in the stdin... >> >> Do you mean setting stdin in non-blocking mode ? On unix you can do it with >> the fcntl module (you'll find more infos in the libc docs) : >> >> fcntl.fcntl(sys.stdin, fcntl.F_SETFL, os.O_NONBLOCK) >> >> and catch IOErrors with errno = EAGAIN. But I don't know how to do it in a >> portable way, suggestions welcome :) >> >> -- >> C?dric Lucantis > >Thanks for the advice that's a way of solving my problem, but I really >need a portable way of doing it... > >The application I?m build is meant to be run in more platforms than >Unix ... so I really need a portable way of doing that or something >else that unblocks the read call in the stdin Twisted supports asynchronous handling of stdin on both POSIX and Windows. See stdiodemo.py and stdin.py under the Miscellaenous section at http://twistedmatrix.com/projects/core/documentation/examples/ Jean-Paul From tdahsu at gmail.com Fri Jun 13 12:16:19 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Fri, 13 Jun 2008 09:16:19 -0700 (PDT) Subject: Iterate creating variables? References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> <6bfhj5F3b47fmU1@mid.uni-berlin.de> <6bfj7bF3c3npoU1@mid.uni-berlin.de> <6bfk3fF3btpk3U1@mid.uni-berlin.de> Message-ID: <34d4366d-1aaa-4c65-99e7-cef8d6741dc1@e39g2000hsf.googlegroups.com> On Jun 13, 12:03?pm, "Diez B. Roggisch" wrote: > > Thank you, this is much closer to where I need to be... > > > The issue is (and this is the part that you don't know, because I > > didn't tell you!) is that I later need to call methods on > > "self.checkbox1", for instance: > > > self.checkbox1.GetValue() > > > to determine if the box is checked or not. > > > I should have included that piece in the initial problem description; > > my apologies. > > Then translate the above to > > self.checkboxes[1].GetValue() > > The point of all this is the following: If you have a variable (even if > not changing often, or being globally configured) number of objects, > it's a good idea to keep them around in a list. > > Even if you need specific parameters for the checkboxes, it would most > probably be better to do it like this > > checkbox_args = [ > ? ?("name", parameter, ...), > ? ?("other_name", other_parameter, ...), > ] > > for parameters in checkbox_args: > ? ? checkboxes.append(Checbbox(*parameters)) > > If you know on the other hand that you will have 10 checkboxes which > have all a defined meaning, it might be better to use a meaningful name > for them, like: > > self.create_backup = Checkbox(...) > self.perform_authorization = Checkbox(...) Trying self.checkboxes[1].GetValue(), gives me: 'NoneType' object has no attribute "GetValue" Thanks. From tdahsu at gmail.com Sat Jun 14 18:18:20 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Sat, 14 Jun 2008 15:18:20 -0700 (PDT) Subject: Avoiding redirects with urllib References: Message-ID: On Jun 14, 5:22?pm, Fernando Rodriguez wrote: > Hi, > > I'musing urllib to download pages from a site. How can I detect if a given > url is being redirected somewhere else? I want to avoid this, is it possible? > > Thanks in advance! Try this: import urllib url_opener = urllib.URLopener() # create URLopener #You could also work with urllib.FancyURLopener try: data = url_opener.open("http://www.somedomain.com/index.html") # open index.html except IOError, error_code: if error_code[0] == "http error": if error_code[1] == 301: #do something here if error_code[2] == 302: #do something here I hope that's of some help! I think you may want to delve deeper into FancyURLopener... From ethan at stoneleaf.us Tue Jun 10 10:06:11 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 10 Jun 2008 06:06:11 -0800 Subject: Alternative to Decimal type In-Reply-To: References: <32247672-cf3a-43c1-ba0a-635a5eff6e04@c58g2000hsc.googlegroups.com> Message-ID: <484E8A53.7010904@stoneleaf.us> Mel wrote: > Frank Millman wrote: > >> Hi all >> >> I have a standard requirement for a 'decimal' type, to instantiate and >> manipulate numeric data that is stored in a database. I came up with a >> solution long before the introduction of the Decimal type, which has >> been working well for me. I know the 'scale' (number of decimal >> places) of the number in advance. When I read the number in from the >> database I scale it up to an integer. When I write it back I scale it >> down again. All arithmetic is done using integers, so I do not lose >> accuracy. [snip] >> -------------------- >> from __future__ import division >> >> class Number(object): >> def __init__(self,value,scale): >> self.factor = 10.0**scale >> if isinstance(value,Number): >> value = value.value / value.factor > > I think this could lead to trouble. One complaint against binary floating > point is that it messes up low-order decimal digits, and this ensures that > all calculations are effectively done in binary floating point. Better, I > think would be > > if isinstance (value, Number): > self.value = value.value > self.scale = scale + value.scale > > and be done with it. Of course, this means self.scale no longer gives the > preferred number of fractional digits. My bias: I did a DecimalFloat class > way back when, when Decimal was being discussed, and separated the exponent > for calculations from the rounding precision for display. What about a little rewrite so the current implementation is like the original, and all calculations are done as integers? Or is this just getting closer and closer to what Decimal does? [only lightly tested] from __future__ import division class Number(object): def __init__(self, value, scale): if isinstance(value, Number): delta = value.scale - scale if delta > 0: self.value = value.value // 10**delta elif delta < 0: self.value = value.value * 10**abs(delta) else: self.value = value.value else: if not scale: scale += 1 self.scale = scale self.factor = 10**self.scale self.value = long(round(value * self.factor)) def __add__(self, other): answer = Number(other, self.scale) answer.value += self.value return answer def __sub__(self, rhs): answer = Number(rhs, self.scale) answer.value = self.value - answer.value return answer def __mul__(self, other): answer = Number(other, self.scale) answer.value *= self.value answer.value //= answer.factor return answer def __truediv__(self, rhs): answer = Number(rhs, self.scale) quotient = 0 divisor = answer.value dividend = self.value for i in range(self.scale+1): quotient = (quotient * 10) + (dividend // divisor) dividend = (dividend % divisor) * 10 answer.value = quotient return answer def __radd__(self, lhs): return self.__add__(lhs) def __rsub__(self, lhs): answer = Number(lhs, self.scale) answer.value = answer.value - self.value return answer def __rmul__(self, lhs): return self.__mul__(lhs) def __rtruediv__(self, lhs): answer = Number(lhs, self.scale) quotient = 0 divisor = self.value dividend = answer.value for i in range(self.scale+1): quotient = (quotient * 10) + (dividend // divisor) dividend = (dividend % divisor) * 10 answer.value = quotient return answer def __cmp__(self, rhs): other = Number(rhs, self.scale) if self.value < other.value: return -1 elif self.value > other.value: return 1 else: return 0 def __str__(self): s = str(self.value) if s[0] == '-': minus = '-' s = s[1:].zfill(self.scale+1) else: minus = '' s = s.zfill(self.scale+1) return '%s%s.%s' % (minus, s[:-self.scale], s[-self.scale:]) -- Ethan From three3q at arcor.de Sat Jun 28 08:11:45 2008 From: three3q at arcor.de (three3q) Date: Sat, 28 Jun 2008 14:11:45 +0200 Subject: matplotlib pylab plot() BadWindow error In-Reply-To: <16f10cf9-a966-4492-891b-d6aedb9ad428@p25g2000hsf.googlegroups.com> References: <16f10cf9-a966-4492-891b-d6aedb9ad428@p25g2000hsf.googlegroups.com> Message-ID: <48662a82$0$6558$9b4e6d93@newsspool3.arcor-online.net> Hi, > I have been warned not to use the show() command in interactive mode. I can't find the error but had better luck with interactivePython ipython which shippes with a pylab-friendly option. dan From Lie.1296 at gmail.com Tue Jun 17 01:36:07 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 16 Jun 2008 22:36:07 -0700 (PDT) Subject: How to catch StopIteration? References: <5f27181e-f558-4760-b6a8-4fb7ef4c5848@a9g2000prl.googlegroups.com> Message-ID: <7840d2fd-f176-40d7-bab0-095549d37f40@l28g2000prd.googlegroups.com> On Jun 17, 10:50?am, ccy56... at gmail.com wrote: > I'm writing to see calcuration process. > And so, I can't catch StopIteration... > > What is mistake? > > def collatz(n): > ? r=[] > ? while n>1: > ? ? r.append(n) > ? ? n = 3*n+1 if n%2 else n/2 > ? ? yield r > > for i, x in enumerate(collatz(13)): > ? try: > ? ? last = x[:i+1] > ? ? print x[:i+1] > ? except StopIteration: > ? ? print last.appnd(1) > > Output: > [13] > [13, 40] > [13, 40, 20] > [13, 40, 20, 10] > [13, 40, 20, 10, 5] > [13, 40, 20, 10, 5, 16] > [13, 40, 20, 10, 5, 16, 8] > [13, 40, 20, 10, 5, 16, 8, 4] > [13, 40, 20, 10, 5, 16, 8, 4, 2] > last.appnd(1) <= [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] ?# i want this > list In a for-loop, StopIteration is caught by the for-loop for your convenience (so you don't need to set up try-except of your own) def collatz(n): r=[] while n>1: r.append(n) n = 3*n+1 if n%2 else n/2 yield r for i, x in enumerate(collatz(13)): last = x[:i+1] print x[:i+1] last.append(1) print last PS: btw, you can't write 'print last.append(1)' because list operations like append doesn't return itself. From sniipe at gmail.com Tue Jun 24 09:18:14 2008 From: sniipe at gmail.com (sniipe at gmail.com) Date: Tue, 24 Jun 2008 06:18:14 -0700 (PDT) Subject: Difference between two dates References: Message-ID: <3355ac93-ed7f-4548-b674-224fbd5270b3@p25g2000hsf.googlegroups.com> Thank you for answers. I used C?dric Lucantis's way to resolve this problem and it works :D From bob at mellowood.ca Sun Jun 29 21:45:32 2008 From: bob at mellowood.ca (bvdp) Date: Sun, 29 Jun 2008 18:45:32 -0700 Subject: Function to import module to namespace In-Reply-To: <4cea42f2-b896-43a8-b8dd-ead2a1add327@z16g2000prn.googlegroups.com> References: <4cea42f2-b896-43a8-b8dd-ead2a1add327@z16g2000prn.googlegroups.com> Message-ID: John Machin wrote: Good questions. Short answer ... probably 'cause I've not thought the problem though completely :) > You are updating with *everything* in the 'more' module, not just the > functions. This includes such things as __name__, __doc__, __file__. > Could have interesting side-effects. > > One quick silly question: why do you want to do this anyway? > I'm writing a "simple" macro expander. I've got some mainline code which reads an input file, parses out macros, and expands them. So, in my input file I might have something like: a fjas j kj sdklj sdkl jfsdkl [ link somewhere sometext ] So, I need a function link() to evaluate and return "http://...." Instead of putting funcs like link() in my mainline I've stuck them in a module of their own. In the mainline I import funcs and then when I need to expand I have the following code: if not cmd in vars(funcs): error("Unknown function/variable '%s'" % cmd) if type(vars(funcs)[cmd]) == type(parse): txt = eval("""funcs.%s("%s")""" % (cmd, arg)) else: # not a func, just expand the variable if arg: error("Argument to variable '%s' not permitted." % cmd) txt = str(eval("funcs.%s" % cmd )) Of course, the question comes up ... what if a user (probably me) wants to add more functions? Easy enough to just edit funcs.py I suppose, but I thought it'd be nice to use more modules. So, I suppose that rather than adding the 2ndary module stuff to the default 'funcs.py' I could just as well have a look and check for the needed function in all the modules I've imported. > Sorry, *two* quick silly questions: are the add-on modules under your > control, or do you want to be able to do this with arbitrary modules? > [If under your control, you could insist that such modules had an > __all__ attribute with appropriate contents] Why would I want to do that ... and how? > A third: why do you want to import into an existing namespace? Now > that you know about __import__, why just not call the functions where > they are? Yeah, that would probably be cleaner (safer). Thanks. From grante at visi.com Sat Jun 14 15:17:56 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 14 Jun 2008 14:17:56 -0500 Subject: Creating a TCP/IP connection on already-networked computers References: <4853f269$0$11615$607ed4bc@cv.net> <4854123f$0$5017$607ed4bc@cv.net> Message-ID: On 2008-06-14, John Salerno wrote: > John Salerno wrote: >> if the program I write actually works and allows the two >> computers to speak to each other, will that be a result purely of the >> program, or will it have anything to do with the fact that they are >> already on a home network together? > > Here are the two programs. Server first, then client. They work, which > in itself amazes me that it's so simple to create a network connection > like this! But my basic question is this: would this connection work if > the two computers (each running one of these scripts) were completely > unrelated to one another? That depends on your definition of "unrelated." > My two are on a home network, but if I were to run the server > program and have a friend of mine (who lives somewhere else) > run the client program, would it still work? Yes, if the routers/firewalls/PCs were set up properly and if you changed the IP addresses in the programs appropriately. -- Grant Edwards grante Yow! I want the presidency at so bad I can already taste visi.com the hors d'oeuvres. From maehhheeyy at gmail.com Tue Jun 10 17:30:20 2008 From: maehhheeyy at gmail.com (maehhheeyy) Date: Tue, 10 Jun 2008 14:30:20 -0700 (PDT) Subject: can't assign to literal References: <9cf693ae-298a-41ba-8e18-ca63c037329e@j1g2000prb.googlegroups.com> Message-ID: On Jun 10, 1:21?pm, Matimus wrote: > On Jun 10, 12:53?pm, maehhheeyy wrote: > > > this is stopping my program from running properly. is there something > > wrong in my code when that happens? > > yes > > Post your code, or at least the full error message if you want more > details. > > Matt for 1 in oids, vals head_oids: SyntaxError: can't assign to literal From eliben at gmail.com Sat Jun 21 02:10:16 2008 From: eliben at gmail.com (eliben) Date: Fri, 20 Jun 2008 23:10:16 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> <485bd4f8$0$30999$426a74cc@news.free.fr> Message-ID: > d = {} > execcode in globals(), d > return d['foo'] > > My way: > > return function(compile(code, '', 'exec'), globals()) > With some help from the guys at IRC I came to realize your way doesn't do the same. It creates a function that, when called, creates 'foo' on globals(). This is not exactly what I need. Eli From casey.mcginty at gmail.com Mon Jun 30 04:52:24 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Sun, 29 Jun 2008 22:52:24 -1000 Subject: Help with Borg design Pattern In-Reply-To: <200806280525.54549.maric@aristote.info> References: <200806280525.54549.maric@aristote.info> Message-ID: On Fri, Jun 27, 2008 at 5:25 PM, Maric Michaud wrote: > Yes it is, but it's rather unneeded in Python, we prefer simply create a > module level dictionnary, these tricks are used in language like C++ or > Java. > > In python : > > mymodule.py : > > ModuleOptions = {} > > othermodule.py : > > import mymodule > > mymodule.ModuleOptions['Verbose'] = True > > or if you think encapsulation is important : > > mymodule.py : > > _ModuleOptions = {} > > def get_option(opt) : > return _ModuleOptions[opt] > .... > > And you're done. > > Using a module level instance seems the right way to go. I'm trying something like this. mymodule.py: class MyDict( dict): ... ... MyDict = MyDict() othermodule.py: import mymodule print mymodule.MyDict I'm running into a slight problem however that my run-time defined logging level is not correctly set until after the module has initialized, preventing any log messages from showing up. Is there a pythonic way to get around this? I'm thinking of adding a module init routine, but I don't feel like this is clean solution. - Casey -------------- next part -------------- An HTML attachment was scrubbed... URL: From stdenton at sbcglobal.net Sat Jun 7 17:11:29 2008 From: stdenton at sbcglobal.net (Sam Denton) Date: Sat, 07 Jun 2008 16:11:29 -0500 Subject: Need help porting Perl function In-Reply-To: References: Message-ID: kj wrote: > Hi. I'd like to port a Perl function that does something I don't > know how to do in Python. (In fact, it may even be something that > is distinctly un-Pythonic!) > > The original Perl function takes a reference to an array, removes > from this array all the elements that satisfy a particular criterion, > and returns the list consisting of the removed elements. Hence > this function returns a value *and* has a major side effect, namely > the target array of the original argument will be modified (this > is the part I suspect may be un-Pythonic). The two solutions thus far use the .index() method, which itself runs in O(n) time. This means that the provided functions run in O(n^2) time, which can be a problem if the list is big. I'd go with this: def partition(alist, criteria): list1, list2 = [], [] for item in alist: if criteria(item): list1.append(item) else: list2.append(item) return (list1, list2) def mod(alist, criteria=lambda x: x % 2 == 0): alist[:], blist = partition(alist, criteria) return blist >>> partition(range(10), lambda x: x % 2 == 0) ([0, 2, 4, 6, 8], [1, 3, 5, 7, 9]) >>> l=range(10) >>> mod(l) [1, 3, 5, 7, 9] >>> l [0, 2, 4, 6, 8] From tjreedy at udel.edu Fri Jun 13 16:00:14 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 13 Jun 2008 16:00:14 -0400 Subject: Mapping None. Why? References: Message-ID: "David C. Ullrich" wrote in message news:dullrich-571EC3.12043113062008 at text.giganews.com... | In article | , | Paddy wrote: | | > True, but None is not a function. It's a sentinel value to turn on the | > functionality. | | Uh, thanks. I think I knew that - I was just suggesting why | the way map works makes sense. filter(None, iterable) works the same way: None-> identity function, The immediate reason is the Python has no builtin id(). But apparently there is also historical precedent in the functional community for this convention. From lists at cheimes.de Sun Jun 8 06:20:32 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 08 Jun 2008 12:20:32 +0200 Subject: How to get System.Timers.Timer In-Reply-To: References: <2KSdncr7xeVoztbVnZ2dnUVZ_qninZ2d@comcast.com> Message-ID: John Machin wrote: > One grabs one's googler and goes a-huntin' ... > ==>> http://msdn.microsoft.com/en-us/library/system.timers.aspx > Looks like part of .NET so one might expect that one already have it. > However one would need to use IronPython to access it ... Or the PythonDotNET extension for CPython. Christian From sexxxy at autograf.pl Wed Jun 18 12:20:57 2008 From: sexxxy at autograf.pl (sexxxyy) Date: Wed, 18 Jun 2008 09:20:57 -0700 (PDT) Subject: The best FREE porn on the Net Message-ID: <2585e0da-ce84-4035-8487-9982d8b4ab67@f36g2000hsa.googlegroups.com> http://rozrywka.yeba.pl/show.php?id=2737 From maric at aristote.info Wed Jun 11 04:36:56 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 11 Jun 2008 10:36:56 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <783c55ec-a294-4600-91d9-4a0d78632c49@t12g2000prg.googlegroups.com> <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> Message-ID: <200806111036.58055.maric@aristote.info> Le Wednesday 11 June 2008 08:11:02 Russ P., vous avez ?crit?: > http://www.sofcheck.com > > Here is an excerpt from their website: > > "SofCheck?s advanced static error detection solutions find bugs in > programs before programs are run. By mathematically analyzing every > line of software, considering every possible input, and every path > through the program, SofCheck?s solutions find any and all errors that > cause a program to crash or produce an undefined result." Don't mix commercial discourse with technical, it desserves your point. Theoretically, wether a program has bugs or not is not computable. Static analysis as they imply is just nonsense. AFAIK, the efforts needed to make good static analysis are proven, by experience, to be at least as time consuming than the efforts needed to make good unit and dynamic testing. -- _____________ Maric Michaud From koski at emile.com Wed Jun 25 16:52:36 2008 From: koski at emile.com (Ilkka Koski) Date: Wed, 25 Jun 2008 15:52:36 -0500 Subject: Router debug References: Message-ID: <1214427156_6921@news-in1.superfeed.net> T.S.10.05.2008."Lis?ydinvoimaloiden rakentamisella ei ole tulevissa Euroopan ilmastotalkoissamme MIT??N merkityst?!"... .. Anteeksi nyt varmaan on sattunut maamme kivimmanluokan ydinlobbareillemme kirjoitusvirhe..Vaan eik? mit?, "ei mit??n merkityst?!" Turun-Sanoman p??kirjoituksesta vihon viimeiseksi luulisi l?ytyv?n tuollaista sanomaa. Vasta parisen kuukautta sitten kun TVO/Posiva YVA-kokouksissa kun olimme saaneet suut silm?t t?yteen vakuutuksia, ett? maahamme on saatava hyviss? ajoin ennen vuoden vaihdetta k?yntiin v?hint??n kolme, ellei per?ti enemm?n ydinvoimalahankkeita, nimenomaan ilmaston talkoitamme varten! Huikeaa muutosta ilmassa, vallan vallatonta muuten. Vain muutama p?iv? sitten maatamme suorastaan j?risytt?nyt YLE:n gallub kun esitteli maassamme olevan v?hint??n 2/3 ydinvastarinnan. Jo sen julkaisu enteili muutosten jykevyytt? aiemmista 80% ydinmy?nn?ist? olevan vailla vertaa. Huikein viesti oli siin?, ett? tuskin 4% suomalaisista oli edell? kerrotun TVO/Posivan triplavoimalan takana! On sanomatta selv??, ett? t?t? taustatuin masinoitua ydinalasajomenttaliteettia on osattu odotella jo vapun Heiniluoman NATO-vastakommentista asti. Koska NATO-j?senyyden viiv?stymisest? seuraa Pertti Simolan TVO:n YVA 4 kokouslausunnon alasajoennakointeja. Suomen ydinaikeiten tielle oli jo kasaantunut rajua vastustusta. My?s EU:n vaatimat 38<50% vuoden 2050 uudisenergtiatavoitteet osaltaan olivat nakertamassa ydinimpperialismin perussavijalkaa. KTM Pekkarisen jatkoa gallubista ei tarvinnut kauoja odotella. Ei tullut 3 uutta ydinvoimalahanketta t?lle vuodelle, ei edes ensi vuodelle. Hauskasti ydinvisiot sai yks kaks mit??n taustoittamatta 2v aikaviiveet tuosta vaan! Myrtyneiden ydinherraskaisten shokkia, p?lyilevi? ja h?mm?styneit?, suorastaan kauhistuneita kommenttejaan siit?, ett? mites kuitataan vuosittainen per?ti +10% ydins?hk?tarpeemme jatkovuosina saa vain silkkaa torua julkisuuden selkosilta nyt. Tulee eitt?m?tt? mieleen, enemm?n kuin paljon on maailmalta t?ytynyt tulla Suomen megamuutoksen takaamiseksi! Ilmasto kun oli se viimeinen keppihevonen ydinvoiman suomalaisuuden, ty?paikkojen luonnin, halpuusilluusiuoiden ja jopa Cernin viimevuotisen polttoainejatkuvuusennakointien kadottua totaaliseen laserjalostuksen 90% saannin romahdettua 11%. Nyt alkaa selke?sti ydinaavikoitumisen luomat ionosf??rituhot, It?merikuolemat kampamaneetteineen mehil?iskatoineen kaikkineen kasaamaan tulisia hiili? ydinalasajon kansainv?liseen kiihdytt?miseen. Maailman uraanivarojen loppuiminen energiapositiivisen? ei j?t? my?s selittelyille sijaa. Yht? kaikki ydinalan alasajo ALKOI! Joko mukana menee vain se, tai sit? k?ytt?v? ihmiskunta on luonnon selke? ja kiistaton Einsteinin ennakoima FAKTA! From deets at nospam.web.de Mon Jun 9 11:36:25 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 09 Jun 2008 17:36:25 +0200 Subject: How to find the first space? References: <7a91cc8f-2e93-46e9-8360-a01da9170187@m44g2000hsc.googlegroups.com> Message-ID: <6b5110F3a49r4U3@mid.uni-berlin.de> Johny wrote: > How can I find the first space using regex? > > For example I have text > Text=' This is a sample ' > > The last space I can remove by > Text=re.sub(r"\s(?!\w)",'',Text) > > but I do not know how to remove the first space. > Can anyone help? Use the strip-method, as defined on stringlike objects. Diez From ian.g.kelly at gmail.com Sun Jun 1 14:49:17 2008 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 1 Jun 2008 12:49:17 -0600 Subject: SPOJ, Problem Code: sumtrian, Reducing time taken to solve. In-Reply-To: References: Message-ID: <3fc761710806011149u176fcd61nc93e7e35825b5376@mail.gmail.com> On Sun, Jun 1, 2008 at 7:25 AM, Shriphani wrote: > I was trying to solve the sumtrian problem in the SPOJ problem set > ( https://www.spoj.pl/problems/SUMTRIAN/ ) and this is the solution I > submitted: http://pastebin.ca/1035867 > > The result was, "Your solution from 2008-06-01 15:13:06 to problem > SUMTRIAN, written in Python, > has exceeded the allowed time limit." > > I suspect that the first portion of my solution which looks at the > input, figures out the number of triangles and forms a list that > contains lists containing each row of the triangle, is wrong. I am not > too sure how to optimize it. I would appreciate help. Since you asked, I went and tried the problem myself and managed to get a solution accepted with a bit of work. Here are my suggestions with regard to your code: * You absolutely need to use psyco for this problem. The accepted solutions have memory usage of 36M+, which on SPOJ is a sure sign that psyco was used, and they're already just a hair under the time limit. * Instead of guessing "it's probably the input step", why don't you profile your code so that you *know* where the bottlenecks are? * Use xrange instead of range in for loops, and certainly don't use while loops for iteration. * max is quite slow for comparing only two things. It's faster to compare the two things yourself. Since this line may be executed millions of times, the difference could be quite significant. From phillip.oldham at gmail.com Fri Jun 13 04:43:36 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Fri, 13 Jun 2008 01:43:36 -0700 (PDT) Subject: Functionality similar to PHP's SimpleXML? Message-ID: <2cff2ee3-970d-4ba0-97e5-821c65fbf0d6@d1g2000hsg.googlegroups.com> I'm sure I'll soon figure out how to find these things out for myself, but I'd like to get the community's advice on something. I'm going to throw together a quick project over the weekend: a spider. I want to scan a website for certain elements. I come from a PHP background, so normally I'd: - throw together a quick REST script to handle http request/responses - load the pages into a simplexml object and - run an xpath over the dom to find the nodes I need to test One of the benefits of PHP's dom implementation is that you can easily load both XML and HTML4 documents - the HTML gets normalised to XML during the import. So, my questions are: Is there a python module to easily handle http request/responses? Is there a python dom module that works similar to php's when working with older html? What python module would I use to apply an XPath expression over a dom and return the results? From bruno.42.desthuilliers at websiteburo.invalid Fri Jun 27 04:28:06 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 27 Jun 2008 10:28:06 +0200 Subject: Adding functions to an existing instance In-Reply-To: References: <27adnS2SrIrOLv7VnZ2dnUVZ_rjinZ2d@earthlink.com> Message-ID: <4864a48c$0$2671$426a74cc@news.free.fr> Allen a ?crit : > bruno.desthuilliers at gmail.com wrote: >> On 26 juin, 17:18, Allen wrote: >>> I need a way to add a method to an existing instance, but be as close as >>> possible to normal instance methods. >> >> def set_method(obj, func, name=None): >> if not name: >> name = func.__name__ >> setattr(obj, name, func.__get__(obj, type(obj))) >> >> class Toto(object): >> pass >> >> toto = Toto() >> >> def titi(self): >> print self >> >> set_method(toto, titi) >> > > I tried that. func.__get__(obj, type(obj)) creates a bound method Indeed, since this is how bound methods are created anyway. > and > then sets an attribute to that, creating a cyclic reference. toto > contains a reference to the bound method, the bound method contains a > reference to the instance toto. Yes, true. I suppose you have good reasons to worry about cyclic references here, but I fail to imagine what they are. Another solution might be to create new class on the fly from the instance's class, inserting the function in the attribs dict, and then rebind the instance's __class__ to this new class, but that might be a bit overkill. From eliben at gmail.com Fri Jun 20 15:44:52 2008 From: eliben at gmail.com (eliben) Date: Fri, 20 Jun 2008 12:44:52 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> Message-ID: <8711b1fe-8256-4f6f-a3d7-f99f44eb23b0@e53g2000hsa.googlegroups.com> On Jun 20, 3:19 pm, George Sakkis wrote: > On Jun 20, 8:03 am, eliben wrote: > > > > > On Jun 20, 9:17 am, Bruno Desthuilliers > > 42.desthuilli... at websiteburo.invalid> wrote: > > > eliben a ?crit :> Hello, > > > > > In a Python program I'm writing I need to dynamically generate > > > > functions[*] > > > > (snip) > > > > > [*] I know that each time a code generation question comes up people > > > > suggest that there's a better way to achieve this, without using exec, > > > > eval, etc. > > > > Just to make things clear: you do know that you can dynamically build > > > functions without exec, do you ? > > > Yes, but the other options for doing so are significantly less > > flexible than exec. > > > > > But in my case, for reasons too long to fully lay out, I > > > > really need to generate non-trivial functions with a lot of hard-coded > > > > actions for performance. > > > > Just out of curiousity : could you tell a bit more about your use case > > > and what makes a simple closure not an option ? > > > Okay. > > > I work in the field of embedded programming, and one of the main uses > > I have for Python (and previously Perl) is writing GUIs for > > controlling embedded systems. The communication protocols are usually > > ad-hoc messages (headear, footer, data, crc) built on top of serial > > communication (RS232). > > > The packets that arrive have a known format. For example (YAMLish > > syntax): > > > packet_length: 10 > > fields: > > - name: header > > offset: 0 > > length: 1 > > - name: time_tag > > offset: 1 > > length: 1 > > transform: val * 2048 > > units: ms > > - name: counter > > offset: 2 > > length: 4 > > bytes-msb-first: true > > - name: bitmask > > offset: 6 > > length: 1 > > bit_from: 0 > > bit_to: 5 > > ... > > > This is a partial capability display. Fields have defined offsets and > > lengths, can be only several bits long, can have defined > > transformations and units for convenient display. > > > I have a program that should receive such packets from the serial port > > and display their contents in tabular form. I want the user to be able > > to specify the format of his packets in a file similar to above. > > > Now, in previous versions of this code, written in Perl, I found out > > that the procedure of extracting field values from packets is very > > inefficient. I've rewritten it using a dynamically generated procedure > > for each field, that does hard coded access to its data. For example: > > > def get_counter(packet): > > data = packet[2:6] > > data.reverse() > > return data > > > This gave me a huge speedup, because each field now had its specific > > function sitting in a dict that quickly extracted the field's data > > from a given packet. > > It's still not clear why the generic version is so slower, unless you > extract only a few selected fields, not all of them. Can you post a > sample of how you used to write it without exec to clarify where the > inefficiency comes from ? > > George The generic version has to make a lot of decisions at runtime, based on the format specification. Extract the offset from the spec, extract the length. Is it msb- first ? Then reverse. Are specific bits required ? If so, do bit operations. Should bits be reversed ? etc. A dynamically generated function doesn't have to make any decisions - everything is hard coded in it, because these decisions have been done at compile time. This can save a lot of dict accesses and conditions, and results in a speedup. I guess this is not much different from Lisp macros - making decisions at compile time instead of run time and saving performance. Eli From bedouglas at earthlink.net Wed Jun 18 23:33:38 2008 From: bedouglas at earthlink.net (bruce) Date: Wed, 18 Jun 2008 20:33:38 -0700 Subject: python/ruby question.. Message-ID: <049e01c8d1bd$44fcee30$0301a8c0@tmesa.com> hi... can someone point me to where/how i would go about calling a ruby app from a python app, and having the python app being able to get a returned value from the ruby script. something like test.py a = os.exec(testruby.rb) testruby.py foo = 9 return foo i know this doesn't work... but i've been searching for hours on this with no luck.... (and yeah, i'm relatively new to both ruby/python!!) thanks From Lie.1296 at gmail.com Sun Jun 1 14:51:14 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 1 Jun 2008 11:51:14 -0700 (PDT) Subject: How to get all the variables in a python shell References: <61f7681d-5cd3-4093-96f9-82f0e7383217@y38g2000hsy.googlegroups.com> Message-ID: <5d8f08ae-adcc-4eee-a6db-87d684df955f@q24g2000prf.googlegroups.com> On Jun 2, 1:29?am, Lie wrote: > lixinyi... at gmail.com wrote: > > Hi! > > > I'm currently working on a scientific computation software built in > > python. > > What I want to implement is a Matlab style command window <-> > > workspace interaction. > > > For example, you type 'a=1' in the command window, and you see a list > > item named 'a' in the workspace. > > You double click the icon of the item, and you see its value. You can > > modify the value of the list item, > > 1 -> 100 etc, ?after which if you go back to the command window and > > type 'a' ?and press enter, you see that > > varable a's value has been changed to 100. > > > So my question is : if you have two DOS command windows running under > > WINDOWS OS, how can you make them share the same internal variable > > buffer? Or is there any easier way to implement such kind of > > interaction? > > > Maybe I could just build a small database to store all the values and > > access them from both programs, but chances are sometimes I have to > > deal with big arrays, and they will eat extra memory if I keep them in > > a database. Is there anyway to access a shell's local memory buffer? > > I tried to use shell.interp.locals() in wxPython, but there's too many > > variables in the list which I don't actually need. > > > Come on guys, give me some ideas. Thanks in advance! > > In all kinds of code, it's best to seperate the workers code and the > UI code, in your case, you should create a backend (worker), which is > a class that stands on its own, and two foreground class (UI) that is > completely independent of each other but have the same interface. The > backend code would have an event that is raised when it is changed to > notify the UI (esp. The gui one) that it has changed since last time, > possibly passing info on what have been changed. The front ends, would > watch for this event as necessary (I don't think it is necessary for > the command line to watch this event) and react to it as necessary > like refreshing the view. The front-end window may only call functions > on the backend to interact with the data being worked on (in short the > backend class is opaque). > > This obliviate the need to share data between the two (or more) > windows (UI) because all the data are contained in the backend class > that the frontend can't access directly. To clarify what I meant, the front ends should never contain any working data except the ones needed for the UI to illustrate what it wanted to show at the moment, and even then, it is accessed in read only fashion. And actually because of Python's Global Interpreter Lock, which means that your program would all be contained in the same python interpreter instance (unless you do some workarounds), passing objects/ lists around between python program is cheap because they're just a "reference" passing (like pointer passing in C/C++) This approach is a simple "server-client" method (not a true server- client method though, since a true one cannot share unserialized data), and is extremely scalable, it's easy to add a third window for example, there is no need for every front end to be aware that there are other front ends, since it just watches for the "Changed" event from the backend. From kalakouentin at yahoo.com Mon Jun 2 02:08:17 2008 From: kalakouentin at yahoo.com (kalakouentin) Date: Mon, 02 Jun 2008 06:08:17 -0000 Subject: "Faster" I/O in a script Message-ID: I use python in order to analyze my data which are in a text form. The script is fairly simple. It reads a line form the input file, computes what it must compute and then write it it to a buffer/list. When the whole reading file is processed (essential all lines) then the algorithms goes ahead and writes them one by one on the output file. It works fine. But because of the continuous I/O it takes a lot of time to execute. I think that the output phase is more or less optimized. (A loop that reads the solutions list sequentially and puts "/n" in the appropriate intervals). Do you know a way to actually load my data in a more "batch-like" way so I will avoid the constant line by line reading? I guess I could read and store the whole text in a list with each cell being being a line and then process each line one by one again but I don't really think that would offer me a significant time gain. Thanx in advance for the time reading this. Pantelis From omer at no-log.org Thu Jun 26 10:11:36 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Thu, 26 Jun 2008 16:11:36 +0200 Subject: ask for a RE pattern to match TABLE in html In-Reply-To: <6a4f17690806260653i136681bdsabe0f6bb1dfab67b@mail.gmail.com> References: <6a4f17690806260653i136681bdsabe0f6bb1dfab67b@mail.gmail.com> Message-ID: <200806261611.36746.omer@no-log.org> Le Thursday 26 June 2008 15:53:06 oyster, vous avez ?crit?: > that is, there is no TABLE tag between a TABLE, for example >
    1.the curd of milk separated from the whey and prepared ? > in many ways as a food.
    something with out table tag
    > what is the RE pattern? thanks > > the following is not right > [^table]*?
  • The construct [abc] does not match a whole word but only one char, so [^table] means "any char which is not t, a, b, l or e". Anyway the inside table word won't match your pattern, as there are '<' and '>' in it, and these chars have to be escaped when used as simple text. So this should work: re.compile(r'.*') ^ this is to avoid matching a tag name starting with table (like ) -- C?dric Lucantis From stefan_ml at behnel.de Mon Jun 9 17:08:43 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 09 Jun 2008 23:08:43 +0200 Subject: Web Crawler - Python or Perl? In-Reply-To: References: <484D7329.6060107@behnel.de> <1a91e16d-ccfc-487a-80fc-4d9992455eb9@p25g2000hsf.googlegroups.com> Message-ID: <484d9bdc$0$6606$9b4e6d93@newsspool2.arcor-online.net> Ray Cote wrote: > Beautiful Soup is a bit slower, but it will actually parse some of the > bizarre HTML you'll download off the web. [...] > I don't know if some of the quicker parsers discussed require > well-formed HTML since I've not used them. You may want to consider > using one of the quicker HTML parsers and, when they throw a fit on the > downloaded HTML, drop back to Beautiful Soup -- which usually gets > _something_ useful off the page. So does lxml.html. And if you still feel like needing BS once in a while, there's lxml.html.soupparser. http://codespeak.net/lxml/elementsoup.html Stefan From pavlovevidence at gmail.com Mon Jun 9 18:33:40 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 9 Jun 2008 15:33:40 -0700 (PDT) Subject: Question by someone coming from C... References: Message-ID: On Jun 9, 5:00 pm, Skye wrote: > Writing this app in Python, not sure what the "best practice" would > be. > > I want a bitfield global logging level that allows me to turn specific > debugging modules on and off. If I was doing this in C, I'd just use > some globals like: > > unsigned int debug_level = 0; > #define DEBUG_GENERAL 0x0001 > #define DEBUG_CONFIG 0x0002 > #define DEBUG_OPTIONS 0x0004 > etc etc > > So I guess my questions are: > > 1. there doesn't seem to be a way to define global constants like in > other languages? > 2. any special voodoo to use bitfields in Python? Apart from the good advice "use the logging module", here is the Pythonic way you'd do this sort of thing in general. (There's not always a spiffy built-in module for anything you want to do; just usually. :) The lack of globals is a minor issue; you can get globally accessible values by storing them in a module and importing that module. The way I'd do the above is to define a module, say config.py, to hold configuration options. Then I'd define each condition in its own variable: debug_general = False debug_config = False debug_options = False I could then enable debugging by changing the value: import config config.debug_general = True And I could use print debugging output based on the config settings like this: import config if config.debug_general or config.debug_options: print_debugging_info() But again, the logging modules handles all this for you so no point for this particular task. P.S. I'd do it more or less this way in C, too. Carl Banks From bignose+hates-spam at benfinney.id.au Wed Jun 25 06:32:26 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 25 Jun 2008 20:32:26 +1000 Subject: python -regular expression - list element References: <62e21ec1-18f3-4572-b223-1b8a5c40688c@f63g2000hsf.googlegroups.com> Message-ID: <87abh9pzyd.fsf@benfinney.id.au> antar2 writes: > for x in list1: > re.compile(x) > for y in list2: > re.compile(y) > if x in y: > z = re.sub(x, 'u', y) > but this does not work You need to frotz the hymangirator with spangule. That, or show us the actual result you're seeing and how it differs from what you expect to happen. -- \ "I must say that I find television very educational. The minute | `\ somebody turns it on, I go to the library and read a book." -- | _o__) Groucho Marx | Ben Finney From eliben at gmail.com Sat Jun 21 01:28:44 2008 From: eliben at gmail.com (eliben) Date: Fri, 20 Jun 2008 22:28:44 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485b5977$0$9738$426a74cc@news.free.fr> <59711f50-7599-42f4-9e6f-5e09ab080524@z72g2000hsb.googlegroups.com> <8711b1fe-8256-4f6f-a3d7-f99f44eb23b0@e53g2000hsa.googlegroups.com> <195ccfd2-3751-44ac-af5e-22c77f8999b7@k37g2000hsf.googlegroups.com> Message-ID: > So you are saying that for example "if do_reverse: data.reverse()" is > *much* slower than "data.reverse()" ? I would expect that checking the > truthness of a boolean would be negligible compared to the reverse > itself. Did you try converting all checks to identity comparisons with > None ? I mean replacing every "if compile_time_condition:" in a loop > with > > compile_time_condition = compile_time_condition or None > for i in some_loop: > if compile_time_condition is None: > ... > > It's hard to believe that the overhead of identity checks is > comparable (let alone much higher) to the body of the loop for > anything more complex than "pass". > There are also dict accesses (to extract the format parameters, such as length and offsets) to the format, which are absent. Besides, the fields are usually small, so reverse is relatively cheap. Eli From justin.mailinglists at gmail.com Tue Jun 3 22:10:38 2008 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Tue, 3 Jun 2008 19:10:38 -0700 (PDT) Subject: Handling some isolated iso-8859-1 characters References: Message-ID: <16ad09c5-5095-4444-8739-285f8d665fd3@q24g2000prf.googlegroups.com> On Jun 4, 2:38 am, Daniel Mahoney wrote: > I'm working on an app that's processing Usenet messages. I'm making a > connection to my NNTP feed and grabbing the headers for the groups I'm > interested in, saving the info to disk, and doing some post-processing. > I'm finding a few bizarre characters and I'm not sure how to handle them > pythonically. > > One of the lines I'm finding this problem with contains: > 137050 Cleo and I have an anouncement! "Mlle. =?iso-8859-1?Q?Ana=EFs?=" > Sun, 21 Nov 2004 16:21:50 -0500 > 4478 69 Xref: > sn-us rec.pets.cats.community:137050 > > The interesting patch is the string that reads "=?iso-8859-1?Q?Ana=EFs?=". > An HTML rendering of what this string should look would be "Anaïs". > > What I'm doing now is a brute-force substitution from the version in the > file to the HTML version. That's ugly. What's a better way to translate > that string? Or is my problem that I'm grabbing the headers from the NNTP > server incorrectly? >>> from email.Header import decode_header >>> decode_header("=?iso-8859-1?Q?Ana=EFs?=") [('Ana\xefs', 'iso-8859-1')] >>> (s, e), = decode_header("=?iso-8859-1?Q?Ana=EFs?=") >>> s 'Ana\xefs' >>> e 'iso-8859-1' >>> s.decode(e) u'Ana\xefs' >>> import unicodedata >>> import htmlentitydefs >>> for c in s.decode(e): ... print ord(c), unicodedata.name(c) ... 65 LATIN CAPITAL LETTER A 110 LATIN SMALL LETTER N 97 LATIN SMALL LETTER A 239 LATIN SMALL LETTER I WITH DIAERESIS 115 LATIN SMALL LETTER S >>> htmlentitydefs.codepoint2name[239] 'iuml' >>> From Lie.1296 at gmail.com Mon Jun 9 17:45:40 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 9 Jun 2008 14:45:40 -0700 (PDT) Subject: Separators inside a var name References: Message-ID: <2eb6cdc2-cd9e-42d4-9460-d9f9df680365@l17g2000pri.googlegroups.com> On Jun 10, 3:38?am, Rainy wrote: > On Jun 9, 2:05?pm, "Sebastian \"lunar\" Wiesner" > > wrote: > > ?Rainy at Montag 09 Juni 2008 19:29: > > > > I have a stylistic question. In most languages words in var. name are > > > separated by underscores or cap letters, resulting in var names like > > > var_name, VarName and varName. I don't like that very much because all > > > 3 ways of naming look bad and/or hard to type. > > > Then you better get used to such names, as they are common for many widely > > spread languages including C, C++, C#, Java, Python, Ruby, Perl and many > > more ;) ?You may like these or dislike these names, but you won't come > > around them ;) > > Well, I was thinking of using some obscure language for personal > projects > that may not need good libs, etc. But of course I agree that there are > no mainstream widely used languages that allow this. > > > > > > From what I understand, scheme can have variables like var-name. I'm > > > curious about reasons that python chose to disallow this. > > > "-" is an operator in Python. ?How should the parser know, > > whether "var-name" means "the object bound to var_dash_name" or "subtract > > the object bound to name from the object bound to var"? > > As I mentioned in another post, differentiate between var1 - var2 and > var-name. As Sebastian have said, it just can't work like that in python and most languages. var1-var2 is a subtraction, because - is an operator. Operator must allow spaces and lack of spaces, how would you want these to be interpreted then: a+b, a-b, a/b, a*b, a**b? In Lisp/Scheme there is no room for ambiguity since their syntax made it impossible that a-b means subtraction. Translated to python, your idea would mean we have to do this: sub(a, dashed-name) for all subtraction. [1] Lisp/Scheme have syntax like this: (- a b) for subtraction, (+ a b) for addition > > > > > Scheme can allows such names, because its a functional programming language. > > Subtracting in this language is not done through operators, but through > > functions. ?Therefore there is a clear difference between referencing a > > name or subtracting two ones: var-name vs (- var name). > > > > Another question I have is what other languages allow this naming scheme? > > > Other lisp dialects do, due to the same reasons as scheme. ? > > > > Were there any languages that allowed space as a separator? > > > None that I know of. ?Probably one could use unicode characters, that look > > like a space in languages, which allow unicode characters in identifiers > > (as Java or C#, iirc), but I doubt this. ?Anyway, even if allowed, this > > would be silly, since it obscures code to the eyes of the reader. > > Yes, that's of course out. I meant using real space. Real space or space-lookalike, allowing blank characters for variable names is a bad idea. It hurts readability by a factor of twenty. > > > What would be a practical way to separate variables from keywords in that > > > case? "some long variable name", 'just a string', or maybe using 2 spaces: > > > one var ?+ ?other var ?+ ?third var ? > > > I can't image a practical way to allow a space as character in names, while > > still maintaining it syntactic element for separation of names. ?Quotes are > > normally used for string or characters literals and a double space is hard > > to distinguish from a single space, and things like ${a name with spaces} > > is a lot nastier than names with underscores (which aren't bad at all, > > imho). > > I agree about ${name with spaces}. I would be interested in the > approach > of using something else for strings and using quotes for var names. > Not > perfect either but might be better than underscores... Err.. what's actually your problem with underscore? Quoting names is the worse idea ever, I'm sure he only reference it as a joke. Especially since it would be ambiguous whether the thing in the quote is a name or a string > > > > I think being able to easy have very long names for vars that are easy to > > > type would be a fairly significant advantage. > > > Names shouldn't be long, they should be expressive. ?If you can't give an > > object a _short_, but _expressive_ name, your object is too complicated ;) > > I'm not sure, I often find myself needing to use 4 words for var name, > and > then underscores I think don't look too good, I would say that > underscores > are kind of ok for 2 words, not very good for 3 words and bad for 4+ > words. > I think if spaces were allowed, I would sometimes use 5 word > variables. I think you need to think simple. KISS principle. Add documentation then use short, expressive names. Generally a shorter the name is more readable than 5-words names. Which ones is clearer: class Math(object): def add(a, b): return a + b def sub(a, b): return a - b and: class Mathematic(object): def addition(left_hand_side_operand, right_hand_side_operand): return left_hand_side_operand + right_hand_side_operand def subtraction(left_hand_side_operand, right_hand_side_operand): return left_hand_side_operand - right_hand_side_operand and short names also saves some typing. > > Btw, I don't really understand your refusal of underscores. ?In my opinion > > such names are harder to read than underscores, which look more like a real > > space, because the leave a space in the middle of a line, that you look at. > > If they are too hard for you to type, whats the point in swapping the dash > > and the underscore in your keyboard layout? > > To me, underscores_look_very_ugly. What_if_I_typed > part_of_every_sentence > with_an_underscore? Ugly! Swapping the dash and underscore are not a > bad > idea, it doesn't fix uglyness, though, and it adds a problem if you > have > to work on another system, because you will always type dash by > mistake > (which will look nice but won't work ;-) ). From ram.rachum at gmail.com Sun Jun 15 08:02:15 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Sun, 15 Jun 2008 05:02:15 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> Message-ID: On Jun 15, 2:48?pm, Peter Otten <__pete... at web.de> wrote: > ram.rac... at gmail.com wrote: > > Quick question: > > I have python code that does a lot of floating point arithmetic. How > > do I make it do the arithmetic in 64 bit? (I have a 64 bit CPU.) If > > I'll install a 64-bit operating system, will that do the trick? > > The Python float type uses a C double internally which is 64 bit even on 32 > bit CPUs. > > Peter Does it mean that even now it does arithmetic in 64 bit? I'm not getting enough precision. Is there any way to increase it? Ram. From bryancchan at gmail.com Mon Jun 2 18:23:29 2008 From: bryancchan at gmail.com (Chanman) Date: Mon, 2 Jun 2008 15:23:29 -0700 (PDT) Subject: Importing xlrd Message-ID: This is probably a simple question to most of you, but here goes. I've downloaded the xlrd (version 0.6.1) module and placed in in the site-packages folder. Now, when I write a script, I type: import sys import xlrd When I run it, there is an import error saying there is no module named xlrd. However when I type sys.path, the site-packages folder is definitely in the path. Do I somehow need to run the xlrd setup.py first before importing? Any help would be appreciated. From google at mrabarnett.plus.com Wed Jun 18 19:19:54 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 18 Jun 2008 16:19:54 -0700 (PDT) Subject: Does '!=' equivelent to 'is not' References: <8c93628a-c89a-4bd3-b30e-91f83f7d17d0@w4g2000prd.googlegroups.com> <20080617120941.GE7349@dragontoe.org> <0fcecc82-0edd-4f57-865a-b2e558577281@x35g2000hsb.googlegroups.com> <44841b35-468b-447b-a925-1de019e0f63f@f24g2000prh.googlegroups.com> Message-ID: On Jun 18, 9:43?pm, Lie wrote: > On Jun 19, 2:51?am, Paul McGuire wrote: > > > On Jun 18, 2:22?pm, Lie wrote: > > > > I'm not a native English speaker, although I think my parents would > > > have liked me to be more straightforward when talking, cause I tend to > > > say things like "possibly", "maybe", "probably", and other ambiguous > > > expressions to the extent that it has frustrated them now and then. > > > Well, at least you *talk* to your parents! ?Mostly what I get from my > > kids is, "can I borrow 10 dollars?" > > lol, I rarely initiate the talk to my parents unless I have to, they > usually starts talking first which I usually responded with the > ambiguous statements. Well, in fact, I rarely initiate a talk with > anybody, it's my nature to keep myself in the shade until I have to be > in the light. > "'Tis better to remain silent and be thought a fool, than open one's mouth and remove all doubt." - Samuel Johnson. :-) > But I never asked for money up straight like that though. From littlesweetmelon at gmail.com Thu Jun 5 05:01:10 2008 From: littlesweetmelon at gmail.com (=?GB2312?B?zPC5zw==?=) Date: Thu, 5 Jun 2008 17:01:10 +0800 Subject: How to make py2.5 distutil to use VC2005? In-Reply-To: <5b8d13220806050134s3e6ad9dfn15bd4c5924551bdc@mail.gmail.com> References: <5b8d13220806040647o1148bf90x6b2b546e9cb339b5@mail.gmail.com> <5b8d13220806050134s3e6ad9dfn15bd4c5924551bdc@mail.gmail.com> Message-ID: > The problem is not compiler, but runtime. For example, if python is > built with runtime foo, and yours with runtime bar, and you use in bar > a file handle, you're screwed: > > http://msdn.microsoft.com/en-us/library/ms235460(VS.80).aspx > > That's why you cannot build a python extension with VS 2005 for python > 2003, in a reliable way. Thank you for providing this document. Indeed, passing internal pointers of one CRT lib to another is dangerous. But in most cases, the python extension only focus on computational-intensive jobs rather than API-intensive jobs. Therefore it is safe to let VS2003-built python to call VS2005-built extensions with some attentions. When you use distutil to trigger compilation, a special *python script* will check whether the default compiler is VS2003. If there is no VS2003, this script will pop-up the error for incompatible compilers. I really really wonder how to *force* distutil to use my specified compile. eg: (pseudo) python setup.py build -c VC2005 or python setup.py build --compiler=C:\VC8\cc --linker=C:\VC8\ld Regards, --- ShenLei From bruno.42.desthuilliers at websiteburo.invalid Wed Jun 25 03:27:52 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 25 Jun 2008 09:27:52 +0200 Subject: newb question on strings In-Reply-To: <5a29e27d-c1b4-4028-8e20-841c58e3f006@27g2000hsf.googlegroups.com> References: <998616c1-8b96-49a7-b830-f122f5f0ee54@a32g2000prf.googlegroups.com> <5a29e27d-c1b4-4028-8e20-841c58e3f006@27g2000hsf.googlegroups.com> Message-ID: <4861f36c$0$17492$426a74cc@news.free.fr> Dan Bishop a ?crit : > On Jun 24, 4:04 pm, "shand... at gmail.com" wrote: >> Are you trying to escape for a regular expression? >> >> Just do re.escape(). >> >>>>> print re.escape('Happy') >> Happy >>>>> print re.escape("Frank's Diner") >> Frank\'s\ Diner >> >> If you're escaping for URLs, there's urllib2.quote(), for a command >> line, use subprocess.list2cmdline. > > And if you're escaping for string literals in Python (or C and its > descendants), you can do: > >>>> print "Frank's Diner".encode('string-escape') > Frank\'s Diner > And finally, if you're escaping it to use it for a SQL query, any DB-API compliant adapter will automatically escape it's params if used correctly. From tjreedy at udel.edu Thu Jun 5 17:20:05 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 5 Jun 2008 17:20:05 -0400 Subject: Token Error: EOF in multiline statement References: <8d7b532c-9801-4a56-b9fa-ca0e7e152bdf@e39g2000hsf.googlegroups.com> Message-ID: "Matimus" wrote in message news:8d7b532c-9801-4a56-b9fa-ca0e7e152bdf at e39g2000hsf.googlegroups.com... | On Jun 5, 12:58 pm, maehhheeyy wrote: | > I'm not sure what it means but it always highlights the last line with | > nothing on it. My program has 63 lines and it highlights the 64th | > line. This keeps popping up whenever I try to run my program. Can you | > please help me fix this? | | You are going to have to post the code or at least the exception text. | It sounds like the last line of your code is missing a needed | parentheses, but it is impossible to know without more input. or { or [ or ''' or """ or the last line ends with '\' From johnjsal at NOSPAMgmail.com Mon Jun 16 20:21:35 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 16 Jun 2008 20:21:35 -0400 Subject: Buffer size when receiving data through a socket? Message-ID: <20080616202135.41c407de.johnjsal@NOSPAMgmail.com> I wrote some pretty basic socket programming again, but I'm still confused about what's happening with the buffer_size variable. Here are the server and client programs: -------------- from socket import * host = '' port = 51567 address = (host, port) buffer_size = 1024 server_socket = socket(AF_INET, SOCK_STREAM) server_socket.bind(address) server_socket.listen(5) while True: print 'waiting for connection...' client_socket, client_address = server_socket.accept() print '...connected from:', client_address while True: data = client_socket.recv(buffer_size) if not data: break client_socket.send('%s %s' % ('You typed:', data)) client_socket.close() server_socket.close() ------------ from socket import * host = 'localhost' port = 51567 address = (host, port) buffer_size = 1024 client_socket = socket(AF_INET, SOCK_STREAM) client_socket.connect(address) while True: data = raw_input('> ') if not data: break client_socket.send(data) data = client_socket.recv(buffer_size) if not data: break print data client_socket.close() --------------- I tried changing buffer_size to 10 and I got this output: john at john-laptop:~$ python myclient.py > hello You typed: > something hello > this is a long string You typed: > why doesn't this work right something > john at john-laptop:~$ My first question is, isn't buffer_size the number of bytes being sent at one time? If so, why doesn't 'hello' get printed after the server returns the data to the client? Isn't 'hello' just 5 bytes? Secondly, how is it working that once I type in a new string (e.g. 'something') and then the server returns data to the client, it prints the *previous* string, (i.e. 'hello')? Wouldn't the data variable get overwritten with the value, or is the value being stored somewhere else at this point? Thanks! From aweraw at gmail.com Tue Jun 10 00:37:53 2008 From: aweraw at gmail.com (Aidan) Date: Tue, 10 Jun 2008 14:37:53 +1000 Subject: Python, subprocess, dump, gzip and Cron Message-ID: <484e0521$1@dnews.tpgi.com.au> Hi, I'm having a bit of trouble with a python script I wrote, though I'm not sure if it's related directly to python, or one of the other software packages... The situation is that I'm trying to create a system backup script that creates an image of the system, filters the output though gzip, and then uploads the data (via ftp) to a remote site. The problem is that when I run the script from the command line, it works as I expect it, but when it is run by cron I only get a 20 byte file where the compressed image should be... does anyone have any idea as to why this might be happening? Code follows #!/usr/bin/python from subprocess import PIPE, Popen from ftplib import FTP host = 'box' filename = '%s.img.gz' % host ftp_host = '192.168.1.250' ftpuser, ftppass = 'admin', 'admin' dest_dir = '/share/%s' % host dump = Popen('dump 0uaf - /',shell=True,stdout=PIPE) gzip = Popen('gzip',shell=True,stdin=dump.stdout,stdout=PIPE) ftp = FTP(ftp_host) ftp.login(ftpuser,ftppass) ftp.cwd(dest_dir) ftp.storbinary('STOR %s' % filename,gzip.stdout) ftp.quit() print "Image '%s' created" % filename I appreciate all feedback. Thanks in advance. From mallikarjun.melagiri at hcl.in Wed Jun 4 06:38:11 2008 From: mallikarjun.melagiri at hcl.in (Mallikarjun Melagiri) Date: Wed, 04 Jun 2008 16:08:11 +0530 Subject: Problem with PEXPECT in Python References: 1183258018.859050.241980@o11g2000prd.googlegroups.com Message-ID: <48467093.30508@hcl.in> Hi Noah, I am new to python. I'm trying to use pexpect. Following is my problem definition: I should have a script on my machine A, which should 'ssh' to machine B and from there it shud copy a file to machine C thru 'scp'. Please help me. Regards Mallik From Robert.Bossy at jouy.inra.fr Wed Jun 18 05:22:40 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 18 Jun 2008 11:22:40 +0200 Subject: dict order Message-ID: <4858D3E0.7050004@jouy.inra.fr> Hi, I wish to know how two dict objects are compared. By browsing the archives I gathered that the number of items are first compared, but if the two dict objects have the same number of items, then the comparison algorithm was not mentioned. Note that I'm not trying to rely on this order. I'm building a domain-specific language where there's a data structure similar to python dict and I need an source of inspiration for implementing comparisons. Thanks RB From maric at aristote.info Mon Jun 30 05:27:09 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 30 Jun 2008 11:27:09 +0200 Subject: List Performance In-Reply-To: References: <42358e0b-a351-4862-8f6a-1938eedeff6c@s21g2000prm.googlegroups.com> Message-ID: <200806301127.11398.maric@aristote.info> Le Monday 30 June 2008 09:23:46 Peter Otten, vous avez ?crit?: > Ampedesign wrote: > > If I happen to have a list that contains over 50,000 items, will the > > size of the list severely impact the performance of appending to the > > list? > > No. > > $ python -m timeit -n20000 -s"items = []" "items.append(42)" > 20000 loops, best of 3: 0.554 usec per loop > $ python -m timeit -n20000 -s"items = [42]*10**6" "items.append(42)" > 20000 loops, best of 3: 0.529 usec per loop But it surely could, if the box happens to be out of memory and begin to swap, while it's not, of course, an issue with python lists... -- _____________ Maric Michaud From fernandoREMOVE_THIS at easyjob.net Sun Jun 15 04:39:31 2008 From: fernandoREMOVE_THIS at easyjob.net (Fernando Rodriguez) Date: Sun, 15 Jun 2008 08:39:31 +0000 (UTC) Subject: Avoiding redirects with urllib References: Message-ID: Hello Fernando, >> I hope that's of some help! I think you may want to delve deeper >> into >> FancyURLopener... > The problem is that I'm using a subclass of FancyOpener and it doesn't > raise those exceptions. > Ok, forget it, I should have read the "fine" manual. O:-) From mike at ipglobal.net Mon Jun 30 10:53:54 2008 From: mike at ipglobal.net (Support Desk) Date: Mon, 30 Jun 2008 09:53:54 -0500 Subject: regex help Message-ID: <12af01c8dac1$1dc54530$a501a8c0@office.ipglobal.net> Hello, I am working on a web-app, that querys long distance numbers from a database of call logs. I am trying to put together a regex that matches any number that does not start with the following. Basically any number that does'nt start with: 281 713 832 or 1281 1713 1832 is long distance any, help would be appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alia_khouri at yahoo.com Sun Jun 1 04:47:55 2008 From: alia_khouri at yahoo.com (Alia Khouri) Date: Sun, 1 Jun 2008 01:47:55 -0700 (PDT) Subject: python's setuptools (eggs) vs ruby's gems survey/discussion Message-ID: <71ff8ebc-96e6-40f8-bcf2-43a0a2bd4135@w7g2000hsa.googlegroups.com> Can we open up the discussion here about how to improve setuptools which has become the de facto standard for distributing / installing python software. I've been playing around with ruby's gems which seems to be more more mature and usable. >From my perspective, the relative immaturity of setuptools and its simultaneous widespread use is a clear python weakness and can make python less easy to absorb than it should be. A few questions (please add more) so far are: (1) Should setuptools be standard? (2) What bugs you most about the current featureset? (3) Which features do you need the most (list in order of need)? (4) Shouldn't we just port gems to python? (5) What's the best community process to improve setuptools? (6) What's your ideal conception of the 'standard python package manager? To give this discussion some ammunition, I will post the output of the different '--help' for either tool: ================================================== SETUPTOOLS ================================================== C:\TMP>easy_install --help Global options: --verbose (-v) run verbosely (default) --quiet (-q) run quietly (turns verbosity off) --dry-run (-n) don't actually do anything --help (-h) show detailed help message Options for 'easy_install' command: --prefix installation prefix --zip-ok (-z) install package as a zipfile --multi-version (-m) make apps have to require() a version --upgrade (-U) force upgrade (searches PyPI for latest versions) --install-dir (-d) install package to DIR --script-dir (-s) install scripts to DIR --exclude-scripts (-x) Don't install scripts --always-copy (-a) Copy all needed packages to install dir --index-url (-i) base URL of Python Package Index --find-links (-f) additional URL(s) to search for packages --delete-conflicting (-D) no longer needed; don't use this --ignore-conflicts-at-my-risk no longer needed; don't use this --build-directory (-b) download/extract/build in DIR; keep the results --optimize (-O) also compile with optimization: -O1 for "python -O", -O2 for "python -OO", and -O0 to disable [default: -O0] --record filename in which to record list of installed files --always-unzip (-Z) don't install as a zipfile, no matter what --site-dirs (-S) list of directories where .pth files work --editable (-e) Install specified packages in editable form --no-deps (-N) don't install dependencies --allow-hosts (-H) pattern(s) that hostnames must match --local-snapshots-ok (-l) allow building eggs from local checkouts usage: easy_install-script.py [options] requirement_or_url ... or: easy_install-script.py --help ================================================== GEMS ================================================== C:\TMP>gem --help RubyGems is a sophisticated package manager for Ruby. This is a basic help message containing pointers to more information. Usage: gem -h/--help gem -v/--version gem command [arguments...] [options...] Examples: gem install rake gem list --local gem build package.gemspec gem help install Further help: gem help commands list all 'gem' commands gem help examples show some examples of usage gem help platforms show information about platforms gem help show help on COMMAND (e.g. 'gem help install') Further information: http://rubygems.rubyforge.org C:\TMP>gem help commands GEM commands are: build Build a gem from a gemspec cert Manage RubyGems certificates and signing settings check Check installed gems cleanup Clean up old versions of installed gems in the local repository contents Display the contents of the installed gems dependency Show the dependencies of an installed gem environment Display information about the RubyGems environment fetch Download a gem and place it in the current directory generate_index Generates the index files for a gem server directory help Provide help on the 'gem' command install Install a gem into the local repository list Display gems whose name starts with STRING lock Generate a lockdown list of gems mirror Mirror a gem repository outdated Display all gems that need updates pristine Restores installed gems to pristine condition from files located in the gem cache query Query gem information in local or remote repositories rdoc Generates RDoc for pre-installed gems search Display all gems whose name contains STRING server Documentation and gem repository HTTP server sources Manage the sources and cache file RubyGems uses to search for gems specification Display gem specification (in yaml) uninstall Uninstall gems from the local repository unpack Unpack an installed gem to the current directory update Update the named gems (or all installed gems) in the local repository which Find the location of a library For help on a particular command, use 'gem help COMMAND'. Commands may be abbreviated, so long as they are unambiguous. e.g. 'gem i rake' is short for 'gem install rake'. ======================================================= Hope this discussion can be constructive. In any case, I do appreciate the effort that went into creating setuptools (Thanks Phillip J. Eby :-). It's existence is clearly better than otherwise. Best, AK From eliben at gmail.com Tue Jun 24 01:18:47 2008 From: eliben at gmail.com (eliben) Date: Mon, 23 Jun 2008 22:18:47 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> <485f4f35$0$28417$426a74cc@news.free.fr> Message-ID: <0967da3a-1fea-401e-896d-9c099b3054ce@c58g2000hsc.googlegroups.com> > If code generation is not the best, and I fail to see any performance issue > that could explain such a choice, except a misunderstanding of > what "compilation" means in python, just don't use it, use closures or > callable instances, there are many way to achieve this. And while we're on the topic of what compilation means in Python, I'm not sure I fully understand the difference between compiled (.pyc) code and exec-ed code. Is the exec-ed code turned to bytecode too, i.e. it will be as efficient as compile-d code ? Eli From asdf at asdf.com Wed Jun 11 21:19:28 2008 From: asdf at asdf.com (asdf) Date: 12 Jun 2008 01:19:28 GMT Subject: matplotlib question Message-ID: <485079a0$0$11641$607ed4bc@cv.net> basically I need to plot a graph of data vs time. However when i use matplotlib the hr:min tick marks come out very close together and appear jumbled. So 12:00 comes out very close to 12:30 for example. There are two things I would like to do. First, is to increase the horizontal dimension of the graph. So basically increase the horizontal number of pixels. The data will always be from midnight to midnight it's just that i want it stretched out more horizontally. Also, how do i specify that i only want hourly tickmarks. So under the x-axis i only want to see 12:00 1:00 etc. thanks From pchilds at gmail.com Tue Jun 3 15:18:18 2008 From: pchilds at gmail.com (Paul Childs) Date: Tue, 3 Jun 2008 12:18:18 -0700 (PDT) Subject: Creating object in function doesn't seem to create a new object. Message-ID: <0d321eb1-8bc3-4ae4-893f-9ad137d9eca4@25g2000hsx.googlegroups.com> Hi folks, I'll start off with the code I wrote... (ActivePython 2.4 on Windows XP SP2) ------------------------------- class FlightCondition(object): lsf = [0,'Low Speed Flare'] vto = [0,'Vertical Take-Off'] def get_flight_condition(flight_data): fc1 = FlightCondition() for row in flight_data: fc1.lsf[0] += 1 fc1.vto[0] += 1 print 'in function get_flight_condition' print fc1.lsf print fc1.vto return fc1 for count in range(3): fc = get_flight_condition([1,2,3]) print 'returned fc' print fc.lsf print fc.vto --------------------------------- When I run it I get... in function get_flight_condition [3, 'Low Speed Flare'] [3, 'Vertical Take-Off'] returned fc [3, 'Low Speed Flare'] [3, 'Vertical Take-Off'] in function get_flight_condition [6, 'Low Speed Flare'] [6, 'Vertical Take-Off'] returned fc [6, 'Low Speed Flare'] [6, 'Vertical Take-Off'] in function get_flight_condition [9, 'Low Speed Flare'] [9, 'Vertical Take-Off'] returned fc [9, 'Low Speed Flare'] [9, 'Vertical Take-Off'] --------------------------------- I thought that when I wrote fc1 = FlightCondition() in the function it would create a new FlightCondition object which would be passed back every time. Instead it seems to re-reference the old version and continue to add to it. --------------------------------- What I expected was... in function get_flight_condition [3, 'Low Speed Flare'] [3, 'Vertical Take-Off'] returned fc [3, 'Low Speed Flare'] [3, 'Vertical Take-Off'] in function get_flight_condition [3, 'Low Speed Flare'] [3, 'Vertical Take-Off'] returned fc [3, 'Low Speed Flare'] [3, 'Vertical Take-Off'] in function get_flight_condition [3, 'Low Speed Flare'] [3, 'Vertical Take-Off'] returned fc [3, 'Low Speed Flare'] [3, 'Vertical Take-Off'] --------------------------------- Could someone please explain to me why I get the output I did instead of what I expected. How do I code my function so I get a new fc1 every time and my desired output? Thanks in advance. /Paul From davidj411 at gmail.com Fri Jun 20 16:34:59 2008 From: davidj411 at gmail.com (davidj411) Date: Fri, 20 Jun 2008 13:34:59 -0700 (PDT) Subject: sublassing as a verb Message-ID: docs on urllib module say this about the FancyUrlOpener: "class FancyURLopener( ...) FancyURLopener subclasses URLopener providing default handling for ..." does that mean the FancyURLopener is a subclass of URLopener? From 42flicks at gmail.com Tue Jun 10 06:42:39 2008 From: 42flicks at gmail.com (Mike) Date: Tue, 10 Jun 2008 22:42:39 +1200 Subject: TWITTER API and urllib2 Message-ID: <2b54d4370806100342h7a34f5f3p13ba81a6e873f14f@mail.gmail.com> Hello, I've spent the last couple of nights hacking away at a Python wrapper for the Twitter API that I can use for various things. I'm having trouble with one of the methods: user_timeline. ( http://groups.google.com/group/twitter-development-talk/web/api-documentation#HelpMethods ). This is the only method that is returning a HTTP 401. It seems strange and I'm not sure how to debug it further as the other methods requring authentication work. Please keep in mind the code is missing alot of polish :) - Though I'm open to suggestions on improvements. If anyone is familiar with this I'd really appreciate a hint as it has me stumped! (I really need this method for my functionality too!) --- import urllib2, urllib, urlparse class TwitterMethods(object): def __init__(self): pass def url_request(self,uri,authentication=None): auth = urllib2.HTTPBasicAuthHandler() netlock = urlparse.urlparse(uri) if authentication: passwdMgr = urllib2.HTTPPasswordMgrWithDefaultRealm() passwdMgr.add_password(None,netlock[1],authentication.username,authentication.password) auth = urllib2.HTTPBasicAuthHandler(passwdMgr) req = urllib2.Request(uri) o = urllib2.build_opener(auth) try: f = o.open(req) print f.readlines([0]) except o.error: print "error" #except: # print "unknown error" return def UserTimeline(self,authentication): self.url_request("http://twitter.com/statuses/user_timeline.xml ",authentication) class TwitterAuth(object): def __init__(self,username,password): self.username = username self.password = password p = TwitterMethods() auth = TwitterAuth('email at gmail.com','password') p.UserTimeline(auth) -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Thu Jun 12 21:10:49 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 12 Jun 2008 18:10:49 -0700 (PDT) Subject: howto split string with both comma and semicolon delimiters References: <3e2540ab-1d2a-45a5-a5b6-3f7ae7a4efac@x35g2000hsb.googlegroups.com> Message-ID: On Jun 12, 8:06 pm, bvdp wrote: > dmitrey wrote: > > hi all, > > howto split string with both comma and semicolon delimiters? > > > i.e. (for example) get ['a','b','c'] from string "a,b;c" > > > I have tried s.split(',;') but it don't work > > Thx, D. > > Howabout: > > s = s.replace(";", ",") > s = s.split(",") I've wondered in the past whether there would be sufficient need for things like s.split((',', ';')) and s.partition((',', ';')). From ebgssth at gmail.com Tue Jun 17 10:19:47 2008 From: ebgssth at gmail.com (js) Date: Tue, 17 Jun 2008 23:19:47 +0900 Subject: The best way to package a Python module? In-Reply-To: <8763sa9msw.fsf@benfinney.id.au> References: <8763sa9msw.fsf@benfinney.id.au> Message-ID: Thanks everyone for details. I'll try stealing some of the good bits of python-central of debian for my purpose. On Mon, Jun 16, 2008 at 10:43 AM, Ben Finney wrote: > Jean-Paul Calderone writes: > >> >What has changed is that the tools in common use for Debian >> >packaging of Python libraries have taken on the role of generating >> >those per-version copies at install time. >> >> exarkun at boson:~$ ls -l /usr/lib/python2.{4,5}/site-packages/sqlite/main.py >> lrwxrwxrwx 1 root root 63 2007-12-27 15:29 /usr/lib/python2.4/site-packages/sqlite/main.py -> /usr/share/pycentral/python-sqlite/site-packages/sqlite/main.py >> lrwxrwxrwx 1 root root 63 2007-12-27 15:29 /usr/lib/python2.5/site-packages/sqlite/main.py -> /usr/share/pycentral/python-sqlite/site-packages/sqlite/main.py >> exarkun at boson:~$ >> >> That doesn't seem to agree with your statement. Am I missing something? > > You are missing an inspection of the contents of the actual package > file. The package file itself contains only a single copy of the > Python module (at /usr/share/pycentral/site-packages/sqlite/main.py). > > What you see there on your filesystem was created at install time; the > installation tool figures out, at install time, which Python versions > need to be supported on this particular system, and creates those > symlinks. > > Thus, the change that's occurred is that the user doesn't need to > choose between "Python SQLite library for Python 2.4" and "Python > SQLite library for Python 2.5". > > There is no longer a separation at the package level by Python > version, so the user merely needs to choose (given your example) the > single "Python SQLite library", and the install process takes care of > setting it up for all supported versions of Python on the system. > > -- > \ "[Freedom of speech] isn't something somebody else gives you. | > `\ That's something you give to yourself." ?_Hocus Pocus_, | > _o__) Kurt Vonnegut | > Ben Finney > -- > http://mail.python.org/mailman/listinfo/python-list From ivan.illarionov at gmail.com Wed Jun 4 12:54:08 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 4 Jun 2008 16:54:08 +0000 (UTC) Subject: can python do some kernel stuff? References: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> <48366cfa$0$15168$607ed4bc@cv.net> <28c432f0-657c-4272-8cd4-a9081b013279@w5g2000prd.googlegroups.com> <69nigsF3499pqU2@mid.uni-berlin.de> <4836994e$0$11625$607ed4bc@cv.net> <69nls3F344g2cU1@mid.uni-berlin.de> <4836a876$0$11623$607ed4bc@cv.net> Message-ID: On Wed, 04 Jun 2008 11:24:11 -0500, Grant Edwards wrote: >> I can't understand why somebody might want to do kernel stuff in >> Python. > > we choose to put Python in kernel-space and do the other things, not > because they are easy, but because they are hard, because that goal > will serve to organize and measure the best of our energies and > skills... > > ;) tinypy rewritten in assembly probably could do the kernel job. CPython is far too big for the kernel. Another crazy idea. What about initd/launchd replacement in pure Python? Python would be the first PID. Isn't it more practical? Ivan From frank-milton at hotmail.com Tue Jun 3 17:18:10 2008 From: frank-milton at hotmail.com (Milton) Date: Tue, 3 Jun 2008 14:18:10 -0700 (PDT) Subject: How to increase the depth of the python traceback? Message-ID: <8d36d9cf-af00-43e2-8540-b50a2df04bd2@a1g2000hsb.googlegroups.com> How to increase the depth of the python traceback? I have some code that gets an exception deep in the python logging module and the traceback produced does not go back far enough to show my own code. How can the traceback limit be controlled in Python 2.5. The docs indicate that there is an attribute in the sys module ?tracebacklimit? that defaults to 1000 (affectively no limit). I cannot find this attribute in the sys module of Python2.5 From zaikenv at gmail.com Fri Jun 27 10:55:02 2008 From: zaikenv at gmail.com (Joel Corbin) Date: Fri, 27 Jun 2008 10:55:02 -0400 Subject: what is meaning of "@" in pyhon program. In-Reply-To: <88990b3d-1916-413f-83b9-796aabf43623@l28g2000prd.googlegroups.com> References: <88990b3d-1916-413f-83b9-796aabf43623@l28g2000prd.googlegroups.com> Message-ID: Hi Evan, The @ is a "decorator", knowing this should help you search for a better explanation than I could give... Have a look here to start: http://mail.python.org/pipermail/tutor/2006-September/048978.html Joel On Fri, Jun 27, 2008 at 10:48 AM, Evan wrote: > HI, > > When I check example of "cmd2" module (a enhancement of cmd module), I > can not understand all, for example: the character "@", > > +++++++++++++++++++++++++++++++++++++++++++++++++++++ > def options(option_list): > .................. > > class cmd(...): > ............................... > @options([make_option('-p', '--piglatin', action="store_true", > help="atinLay")]) > +++++++++++++++++++++++++++++++++++++++++++++++++++++ > > I do not understand what "@options" does, most time, I know what the > meaning of character "*" and character "**", but I was not use "@" > before. > > Thanks for your help. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nyamatongwe+thunder at gmail.com Sat Jun 28 19:19:56 2008 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sat, 28 Jun 2008 23:19:56 GMT Subject: pxssh submit su commands = very very slow In-Reply-To: <39f89067-8ee6-470a-92ce-77b46a344f37@34g2000hsf.googlegroups.com> References: <39f89067-8ee6-470a-92ce-77b46a344f37@34g2000hsf.googlegroups.com> Message-ID: gert: > This works but after the su command you have to wait like 2 minutes > before each command gets executed ? > s.sendline ('su') > s.expect('Password:') A common idiom seems to be to omit the start of the expected reply since it may not be grabbed quickly enough. Then the prompt has to time out. Try s.expect('assword:') Neil From gherron at islandtraining.com Sat Jun 28 12:04:20 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 28 Jun 2008 09:04:20 -0700 Subject: 2D online multiplayer framework? In-Reply-To: <6dc6195b-b8a0-42a9-a982-3a4b70943c24@r37g2000prm.googlegroups.com> References: <6dc6195b-b8a0-42a9-a982-3a4b70943c24@r37g2000prm.googlegroups.com> Message-ID: <48666104.3010507@islandtraining.com> George Oliver wrote: > I'm looking for a framework to support a 2D online real-time > multiplayer game (rugby league football with a lo-fi pixel look). The > GameProgramming page at the Python wiki had some suggestions but so > far nothing looks that promising, does anyone have some > recommendations? > > It would be ideal to play this through a web browser but I don't know > if that's practical. > > This aspect of programming is pretty new to me so I'm not sure if I > should start with something general like Twisted or if there's a > different path I should take. > > > thanks, George > -- > http://mail.python.org/mailman/listinfo/python-list > Pyglet is my favorite: http://www.pyglet.org/ Twisted might be fine for the "online multiplayer" parts, but really if you want a 2D/3D real-time game, start with a game framework. Gary Herron From jeffnyman at gmail.com Thu Jun 5 02:54:02 2008 From: jeffnyman at gmail.com (Jeff Nyman) Date: Wed, 4 Jun 2008 23:54:02 -0700 (PDT) Subject: os.path.walk -- Can You Limit Directories Returned? Message-ID: <65971e97-09eb-4295-a090-517341a86065@e53g2000hsa.googlegroups.com> Greetings all. I did some searching on this but I can't seem to find a specific solution. I have code like this: ========================================= def walker1(arg, dirname, names): DC_List.append((dirname,'')) os.path.walk('\\\\vcdcflx006\\Flex\\Sites', walker1, 0) ========================================= The Sites\ directory is set up like this: Sites\ Baltimore Birmingham .... And so forth. Each of the city directories has directories under it as well. The problem is that my code grabs every single directory that is under the various city directories when what I really want it to do is just grab the directories that are under Sites\ and that's it. I don't want it to recurse down into the sub-directories of the cities. Is there a way to do this? Or is os.path.walk not by best choice here? Any help and/or advice would be appreciated. - Jeff From toolmaster at 163.com Wed Jun 18 04:09:12 2008 From: toolmaster at 163.com (WaterWalk) Date: Wed, 18 Jun 2008 01:09:12 -0700 (PDT) Subject: Name lookup inside class definition References: <1c1a1181-905c-4401-ae00-36b3fabebab9@v1g2000pra.googlegroups.com> Message-ID: <24ea79d9-3715-43b9-b337-50627f84e69c@w4g2000prd.googlegroups.com> Ah, I see. Thank you all. From ivan.illarionov at gmail.com Wed Jun 4 03:44:38 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 4 Jun 2008 07:44:38 +0000 (UTC) Subject: Best way to modify code without breaking stuff. References: Message-ID: On Wed, 04 Jun 2008 00:25:19 -0700, Jesse Aldridge wrote: > I've got a module that I use regularly. I want to make some extensive > changes to this module but I want all of the programs that depend on the > module to keep working while I'm making my changes. What's the best way > to accomplish this? Version control system. http://en.wikipedia.org/wiki/List_of_revision_control_software Make your module a versioned repository. Make your changes in different place, then commit them. I use SVN and mercurial. Ivan From david at hlacik.eu Wed Jun 4 18:26:25 2008 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Thu, 5 Jun 2008 00:26:25 +0200 Subject: no module named py Message-ID: Hello, what this beautifull mesage which is messing me whole day means : *python: error , ('No module named py',), No module named py* as a result of class pdg.py which is called from nnrpd_auth.py. To be detailed ... news server inn is calling that when doing autentification , it calls nnrpd_auth.py where instance of my class is hooked into inn , when authentification begins it calls method authenticate(arguments) from pdg. I will provide as many information as needed to solve this mistery, becouse i really need to solve it. Thanks! #!/usr/bin/env python import ldap from nnrpd import syslog class news: server = 'ldap://dev01.net.hlacik.eu' user_dn = 'cn=pdg,ou=Operators,o=Polarion' user_pw = 'Pdg1' connectcodes = { 'READPOST':200, 'READ':201, 'AUTHNEEDED':480, 'PERMDENIED':502 } authcodes = { 'ALLOWED':281, 'DENIED':502 } def newsauth(self,match_username,match_password): base_dn = 'ou=Users,o=Polarion' filter = "(uid=" + match_username + ")" attrs = ['userPassword'] try : l = ldap.initialize(self.server) l.bind_s(self.user_dn, self.user_pw) raw_res = l.search_s( base_dn, ldap.SCOPE_SUBTREE, filter, attrs ) l.unbind() except ldap.SERVER_DOWN: print "Error, server down" return 2 except ldap.INVALID_CREDENTIALS: print "Error, invalid credentials" return 2 except ldap.LDAPError, e: print "Error, %s" % e for results in raw_res: (cn,search) = results for password in search["userPassword"]: if password == match_password: return 1 return 0 def authenticate(self, attributes): # just for debugging purposes syslog('notice', 'nnrpd_auth authenticate() invoked: hostname %s, ipaddress %s, interface %s, user %s' % (\ attributes['hostname'], \ attributes['ipaddress'], \ attributes['interface'], \ attributes['user'])) try: syslog('notice', "result %s" % self.newsauth('boss','bbbb')) except Exception, msg: syslog('notice', "error %s, %s, %s" % (type(msg),msg.args,msg)) # do username passworld authentication #if self.newsauth(attributes['user'], str(attributes['pass'])): # syslog('notice', 'authentication by username succeeded') # return ( self.authcodes['ALLOWED'], 'No error' ) #else: # syslog('notice', 'authentication by username failed') # return ( self.authcodes['DENIED'], 'Access Denied!') ------------------- nnrpd_auth_py : # # Sample authentication and authorization class. It defines all methods known # to nnrpd. # # Import functions exposed by nnrpd. This import must succeed, or nothing # will work! from nnrpd import * from pdg import * myauth = news() # ...and try to hook up on nnrpd. This would make auth object methods visible # to nnrpd. try: set_auth_hook(myauth) syslog('notice', "authentication module successfully hooked into nnrpd") except Exception, errmsg: syslog('error', "Cannot obtain nnrpd hook for authentication method: %s" % errmsg[0]) -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Sat Jun 7 20:07:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 7 Jun 2008 17:07:51 -0700 (PDT) Subject: Can this be done with list comprehension? References: Message-ID: <45692181-3b90-49c9-a0e5-8af933034a49@z16g2000prn.googlegroups.com> On Jun 8, 8:31 am, Karlo Lozovina <_karlo_ at _mosor.net_> wrote: > This is what I'm trying to do (create a list using list comprehesion, then > insert new element at the beginning of that list): > > result = [someFunction(i) for i in some_list].insert(0, 'something') result = ['something'] + [someFunction(i) for i in some_list] From pfreixes at gmail.com Fri Jun 13 07:55:30 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Fri, 13 Jun 2008 13:55:30 +0200 Subject: GIL cpu multi core usage problem In-Reply-To: References: <207312b70806091126t6d9c3479hfe39368cd06b029e@mail.gmail.com> Message-ID: <207312b70806130455h4db9c6dn91485837b7a4bf1c@mail.gmail.com> Hi, When you say this "C extensions (usually) release the GIL when they don't call into any Python code" do you talk about this macros ? Py_BEGIN_ALLOW_THREADS Py_END_ALLOW_THREADS On Wed, Jun 11, 2008 at 3:52 AM, Gabriel Genellina wrote: > En Mon, 09 Jun 2008 15:26:09 -0300, Pau Freixes > escribi?: > > Surly this is a recurring theme into python dev world, but I need your >> help >> for confirm if the follow image it's really >> >> http://www.milnou.net/~pfreixes/img/cpu_usage_gil_problem.png >> >> >> I'm writing a brief article for my blog and I need to make sure about the >> current problem with GIL and multi core environments, this picture try to >> explain with images the problem for scheduling multiple threads running >> python code of same interpreter into multiple cpu cores. Can anyone >> confirm >> to me this picture ? >> > > Yes, if both threads are executing pure Python code, they can't run > simultaneously. > > Note that: > - C extensions (usually) release the GIL when they don't call into any > Python code > - The interpreter also releases the GIL before any I/O operation > If the process is I/O bound then the GIL is not so important, and if it's > CPU bound you may benefit from reimplementing the critical parts in C (by > example, using NumPy for a number-crunching process). Another alternative is > to use multiple processes with some form of IPC instead of multiple threads. > These are the usual arguments against "fear of GIL". You should consider > your specific application to see if the GIL is actually a problem in your > case or not. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From pythonreptile at gmail.com Tue Jun 3 19:33:20 2008 From: pythonreptile at gmail.com (pythonreptile at gmail.com) Date: Tue, 3 Jun 2008 16:33:20 -0700 (PDT) Subject: Constructor re-initialization issue References: <00d47094-b687-48f2-9dc0-c92994a4f70c@y38g2000hsy.googlegroups.com> Message-ID: <513f9db0-b971-4644-aa1f-d990e335920a@u6g2000prc.googlegroups.com> On Jun 3, 12:59 pm, George Sakkis wrote: > On Jun 3, 6:11 pm, pythonrept... at gmail.com wrote: > > > > > Hello all, > > > I have come across this issue in Python and I cannot quite understand > > what is going on. > > > class Param(): > > def __init__(self, data={}, condition=False): > > if condition: > > data['class']="Advanced" > > print data > > > In the previous example, I expect the variable data to be re- > > initialized every time I construct an object type Param. However, when > > I do the following: > > > Param(condition=True) > > Param(condition=False) > > > The second call still prints {'class': 'Advanced'} > > > Shouldn't data be initialized to {} since it is the default in > > __init__? Why would the state of data be preserved between two > > independent instantiations? > > > Any help would be greatly appreciated. > > > M. > > This must be by far the most FAQ.. unfortunately it seems it will > remain for 3.x as well:http://www.python.org/doc/faq/general/#why-are-default-values-shared-... Thanks for clearing this up for me. M. From a.harrowell at gmail.com Wed Jun 25 14:33:05 2008 From: a.harrowell at gmail.com (TYR) Date: Wed, 25 Jun 2008 11:33:05 -0700 (PDT) Subject: Mobile Devices References: Message-ID: <549d4fcd-7c89-47dc-9a44-8e3e6ac92ed2@d77g2000hsb.googlegroups.com> On Jun 25, 10:38?am, rodmc wrote: > Hi, > > I have been scouting around online for information on how to use > Python and a GUI toolikit to develop mobile devices. At present I am > using wxPython for desktop apps and would like to continue using that > if possible. Anyway, I would like to know what people would recommend > for developing mobile applications which can run on Windows Mobile and > Mac OS X (iPhone etc)? It would also be cool if the same apps could > run where possible (or atleast part of them) on desktop machines as > well. > > Any tips, experiences etc welcome. This is really to stimulate some > general discussion. > > Best, > > rod I know nothing of running Python on WinMob devices, but I see no reason why it shouldn't be possible. However MS doesn't, as far as I know, support it or provide any tools/sdks/ecosystem services. Apple has its own rather closed ecosystem for iPhone support, but as everyone knows there is a vigorous hacker community doing unofficial things with them. However, I'm not aware of any python activity. Most mobile Python activity is in the nokiasphere; there is a Nokia- backed version of Python for S60 devices, which is fully supported, includes Python libs that wrap the devices' native functionality up to and including N95 accelerometers, and has a desktop mobile device emulator for convenience. However, wxPython wouldn't really be relevant as pyS60 includes its own native GUI toolkit, appuifw; no reason why you couldn't install the module and try, though, but using appuifw does ensure that your GUI will look like all the other stuff on the phone. It won't, of course, work on your PC. From shandy.b at gmail.com Tue Jun 24 17:04:04 2008 From: shandy.b at gmail.com (shandy.b at gmail.com) Date: Tue, 24 Jun 2008 14:04:04 -0700 (PDT) Subject: newb question on strings References: Message-ID: <998616c1-8b96-49a7-b830-f122f5f0ee54@a32g2000prf.googlegroups.com> Are you trying to escape for a regular expression? Just do re.escape(). >>> print re.escape('Happy') Happy >>> print re.escape("Frank's Diner") Frank\'s\ Diner If you're escaping for URLs, there's urllib2.quote(), for a command line, use subprocess.list2cmdline. Generally, the module that consumes the string should provide a function like escape(). On Jun 24, 1:27?pm, regex_jedi wrote: > ok, I have looked a lot of places, and can't seem to get a clear > answer... > > I have a string called > ? ?each_theme > > Some values of the string may contain a single quote as in - > ? ?Happy > ? ?Sad > ? ?Nice > ? ?Frank's Laundry > ? ?Explosion > > Notice that the 4th value has a single quote in it. Well, I need to > make sure that the single quote is escaped before handing it off for > further processing to a class I later call for some other processing. > > So I thought, no big deal, I should be able to find a way to escape > the single quote on the string. ?I am a perl and PHP guy, so I do a > lot of regex stuff. ?I did a quick search and found someone had said > to use this re.sub function, so I tried. ?But the following doesn't > work. To be honest, I am a little lost with all the modules and > classes required to do simple math or string functions in Python. > None of it seems built it in.. its all import modules... ?Here is what > I am trying... > > ? ? ? ? # escape single quotes in theme name > ? ? ? ? re.sub('''(['"])''', r'\\\1', each_theme) > > you python masters... show me the way please... > > thanks > regex_jedi From gagsl-py2 at yahoo.com.ar Fri Jun 13 05:47:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Jun 2008 06:47:22 -0300 Subject: boolian logic References: <742d534a-02c3-4228-9b94-2b25c953da85@56g2000hsm.googlegroups.com> Message-ID: En Fri, 13 Jun 2008 06:15:52 -0300, marc wyburn escribi?: > HI all, I'm a bit stuck with how to work out boolian logic. > > I'd like to say if A is not equal to B, C or D: > do something. > > I've tried > > if not var == A or B or C: > and various permutations but can't seem to get my head around it. I'm > pretty sure I need to know what is calulated first i.e the not or the > 'OR/AND's if A not in (B, C, D): ... "or" has less priority than not, and all boolean operators have less priority than comparisons. So your expression above reads as: if (not (var==A)) or B or C and the three or'ed expressions are evaluated from left to right (short-circuit: stop as soon as any true value is found). Evaluation order is defined in the Reference Manual, see in particular, operator precedence is summarized in -- Gabriel Genellina From giles.thomas at resolversystems.com Wed Jun 4 14:17:39 2008 From: giles.thomas at resolversystems.com (Giles Thomas) Date: Wed, 4 Jun 2008 11:17:39 -0700 (PDT) Subject: ANN: Resolver One 1.1 released References: <827962c7-36ad-4e66-bae3-0ca033054501@a1g2000hsb.googlegroups.com> <4846D9BF.90406@behnel.de> Message-ID: <6670b267-c2be-4fe3-9e83-48d3fa77fc70@s50g2000hsb.googlegroups.com> Stefan Behnel wrote: > Giles Thomas wrote: > > We are proud to announce the release of Resolver One, version 1.1 - the > > largest IronPython application in the world, we think, at 38,000 lines > > of production code backed up by 130,000 lines of unit and functional > > tests. > > Is it really IronPython specific code or would it run on standard Python? It's really IronPython-specific, which is both a blessing - there's a suprising amount of really good .NET classes out there and it's great to be able to script them using Python from a grid-based environment - and a curse, because we lose the cross-platform capabilities and the C extensions like numpy. We're working on sorting out the latter with a project called Ironclad () which aims to get C extensions working in IronPython. For the cross-platform stuff, in the longer term we hope to be Mono-compatible and so be able to support Linux and the Mac. All the best, Giles -- Giles Thomas MD & CTO, Resolver Systems Ltd. giles.thomas at resolversystems.com +44 (0) 20 7253 6372 Try out Resolver One! (Free registration required) 17a Clerkenwell Road, London EC1M 5RD, UK VAT No.: GB 893 5643 79 Registered in England and Wales as company number 5467329. Registered address: 843 Finchley Road, London NW11 8NA, UK From dbpokorny at gmail.com Wed Jun 18 17:58:04 2008 From: dbpokorny at gmail.com (dbpokorny at gmail.com) Date: Wed, 18 Jun 2008 14:58:04 -0700 (PDT) Subject: PEP 372 -- Adding an ordered directory to collections References: <5c6cdecc-624f-4e1f-b4d5-88656e182d02@a1g2000hsb.googlegroups.com> Message-ID: Wow, I was completely wrong about sorted dicts and odicts. On Jun 17, 4:21 am, bearophileH... at lycos.com wrote: > mean. I think for this data structure it's important to keep all the > normal dict operations at the same speed. If you use a C Why keep the normal dict operations at the same speed? There is a substantial cost this entails. It seems that some odict solutions take up 4n words per entry in the limit (ignoring the fixed percentage growth space for lists and dicts). This is n words for _keys and 3n words for the underlying dict. What about storing the key:value pairs as a pair of lists (maybe interleaved)? Key lookup then becomes an O(n) operation, but the storage requirements are reduced to 2n from 4n. Here is a hypothetical (somewhat contrived) example: odicts are used to store the attributes of XML elements in a medium-sized XML document (say 250K). If the required munging does some surgery on elements 3-4 layers deep in a few places, then the number of key lookups may be relatively small. (Assuming that very few odicts will have more than 30 entries, each individual lookup will be fairly quick as well). The document has to be loaded into memory anyway, so the extra cost of key lookups is more than compensated for by the substantial reduction in the number of cache line misses. The main concern is that doubling the size of the data structure in order to turn key lookup into an O(1) operation may give worse performance in the common case (this is a personal impression from reading the use case list in the rationale), and a data structure like this seems to be way off by itself in the time-space complexity landscape. In this case the odict no longer inherits from the dict. Cheers, David From __peter__ at web.de Sun Jun 15 14:43:55 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Jun 2008 20:43:55 +0200 Subject: randrange loops References: <6e424f2a-872d-4dd1-b28d-cf2a985895c9@j22g2000hsf.googlegroups.com> Message-ID: luislupe at gmail.com wrote: > I've created a method where the script defines twenty variables and > several of them should be random having a maximum and a minimum value. > > What I did was this: > > from random import randrange as rr, random > > self.tr2_vezes = self.rr(self.d_tr2_vezes[0],self.d_tr2_vezes[-1], > 1) # just an example, others are similar > > The minimum and maximum limits are never lower than -50 and higher > than 250 and are integer. > > Many times, not always, the problem is that the script just loops > forever and no value is chosen for the variable. > > What's happening here? What am I doing wrong? You don't provide enough information. Please show as a small script that demonstrates the behaviour you describe. Peter From george.sakkis at gmail.com Thu Jun 5 13:22:44 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 5 Jun 2008 10:22:44 -0700 (PDT) Subject: Tuples part 2 References: <6d3e6d40-63a6-40d1-8ea4-5ddf40238d8d@m44g2000hsc.googlegroups.com> <99bc30fb-532a-4c4f-9f5e-e7a18c28d2a5@z72g2000hsb.googlegroups.com> <0ecaaa47-3ad4-4f67-9d48-94d5d1951bc6@y21g2000hsf.googlegroups.com> Message-ID: On Jun 5, 11:48 am, Ivan Illarionov wrote: > On 5 ???, 19:38, George Sakkis wrote: > > > > > On Jun 5, 11:21 am, Ivan Illarionov wrote: > > > > On 5 ???, 18:56, Ivan Illarionov wrote: > > > > > On 5 ???, 18:19, "victor.hera... at gmail.com" > > > > wrote: > > > > > > On Jun 5, 3:49 pm, Ivan Illarionov wrote: > > > > > > > On 5 ???, 01:57, "victor.hera... at gmail.com" > > > > > > wrote: > > > > > > > > Hi Everyone, > > > > > > > > i have another question. What if i wanted to make n tuples, each with > > > > > > > a list of coordinates. For example : > > > > > > > > coords = list() > > > > > > > for h in xrange(1,11,1): > > > > > > > for i in xrange(1, 5, 1) : > > > > > > > for j in xrange(1, 5, 1) : > > > > > > > for k in xrange(1,2,1) : > > > > > > > coords.append((i,j,k)) > > > > > > > lista+str(h)= tuple coords > > > > > > > print tuple(coords) > > > > > > > > so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do > > > > > > > it the way i show you above but it is not working properly. I wish you > > > > > > > could help me with that. Thanks again, > > > > > > >>> from itertools import repeat, izip > > > > > > >>> coords = tuple((i,j,k) for i in xrange(1,5) for j in xrange(1,5) for k in xrange(1,2)) > > > > > > >>> locals().update(("tuple%s" % i, coord) for i, coord in izip(xrange(1,11), repeat(coords))) > > > > > > >>> tuple1 > > > > > > > ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (2, 1, 1), (2, 2, 1), (2, > > > > > > 3, 1), (2 > > > > > > , 4, 1), (3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1), (4, 1, 1), (4, 2, > > > > > > 1), (4, 3 > > > > > > , 1), (4, 4, 1)) > > > > > > > Does this help? > > > > > > > But I don't understand why you need this? > > > > > > > Ivan > > > > > > Hi, > > > > > > What i need is, for example: > > > > > > tuple 1=((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)) > > > > > > tuple 2=((2, 1, 1), (2, 2, 1), (2, 3, 1), (2, 4, 1)) > > > > > > tuple 3=((3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1)) > > > > > > and so on. Please help me and sorry for not taking the time to post my > > > > > questions properly. > > > > > > Victor > > > > > Or even so: > > > > > locals().update(("tuple_%s" % i, tuple((i,j,k) for j in range(1,5) for > > > > k in range(1,2))) for i in range(1,5)) > > > > > Ivan > > > > Tried to make it readable: > > > > def iter_coords(i): > > > for j in xrange(1,5): > > > for k in xrange(1,2): > > > yield i, j, k > > > > def iter_vars(): > > > for i in xrange(1, 5): > > > yield "tuple_%s" % i, tuple(iter_coords(i)) > > > > locals().update(dict(iter_vars())) > > > locals().update() works by accident here because it's in global scope; > > it doesn't work within a function. > > > Use a proper data structure, like a dict or a list, and access each > > tuple list as 'tuples[n]' instead of 'tuple_n'. > > > George > > OP wanted variables and I showed him how to do this. I agree that a > list or a dict would be better. > > Ivan Generating variable names at runtime doesn't work for locals and it is a bad solution for globals in 99.9% of the cases. It is usually more helpful to point someone who can't even express his problem clearly to the right direction, rather than taking his pseudocode literally and coming up with a semi-working translation. George From deets at nospam.web.de Sun Jun 15 16:12:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 15 Jun 2008 22:12:00 +0200 Subject: Removing inheritance (decorator pattern ?) In-Reply-To: References: Message-ID: <6blbcoF3b6v17U1@mid.uni-berlin.de> George Sakkis schrieb: > I have a situation where one class can be customized with several > orthogonal options. Currently this is implemented with (multiple) > inheritance but this leads to combinatorial explosion of subclasses as > more orthogonal features are added. Naturally, the decorator pattern > [1] comes to mind (not to be confused with the the Python meaning of > the term "decorator"). > > However, there is a twist. In the standard decorator pattern, the > decorator accepts the object to be decorated and adds extra > functionality or modifies the object's behavior by overriding one or > more methods. It does not affect how the object is created, it takes > it as is. My multiple inheritance classes though play a double role: > not only they override one or more regular methods, but they may > override __init__ as well. Here's a toy example: > > class Joinable(object): > def __init__(self, words): > self.__words = list(words) > def join(self, delim=','): > return delim.join(self.__words) > > class Sorted(Joinable): > def __init__(self, words): > super(Sorted,self).__init__(sorted(words)) > def join(self, delim=','): > return '[Sorted] %s' % super(Sorted,self).join(delim) > > class Reversed(Joinable): > def __init__(self, words): > super(Reversed,self).__init__(reversed(words)) > def join(self, delim=','): > return '[Reversed] %s' % super(Reversed,self).join(delim) > > class SortedReversed(Sorted, Reversed): > pass > > class ReversedSorted(Reversed, Sorted): > pass > > if __name__ == '__main__': > words = 'this is a test'.split() > print SortedReversed(words).join() > print ReversedSorted(words).join() > > > So I'm wondering, is the decorator pattern applicable here ? If yes, > how ? If not, is there another way to convert inheritance to > delegation ? Factory - and dynamic subclassing, as shown here: import random class A(object): pass class B(object): pass def create_instance(): superclasses = tuple(random.sample([A, B], random.randint(1, 2))) class BaseCombiner(type): def __new__(mcs, name, bases, d): bases = superclasses + bases return type(name, bases, d) class Foo(object): __metaclass__ = BaseCombiner return Foo() for _ in xrange(10): f = create_instance() print f.__class__.__bases__ Diez From johnjsal at gmailNOSPAM.com Fri Jun 27 22:56:40 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Fri, 27 Jun 2008 22:56:40 -0400 Subject: Using just the Mako part of Pylons? Message-ID: <4865a871$0$5024$607ed4bc@cv.net> I just installed Pylons onto my hosting server so I could try out templating with Mako, but it seems a little more complicated than that. From the look of it all, the site seems to want a full Pylons application. Is it possible to just use regular HTML files with a bit of the Mako language embedded, or will I actually have to use all aspects of Pylons? In other words, can I use *just* Mako (sort of like as a replacement for PHP) without having to use a framework? For example, I'd like to just test out the <%include /> tag and see it in action, but the site doesn't seem to be looking for a regular HTML file (like index.html), it seems to want a "controller". So is Pylons overkill for just this? How would I try out *just* Mako? Thanks! From goldnery at gmail.com Thu Jun 12 22:22:58 2008 From: goldnery at gmail.com (Gandalf) Date: Thu, 12 Jun 2008 19:22:58 -0700 (PDT) Subject: Charset (hopefully for the last time I ask) References: Message-ID: <9a899d5a-fb53-4fd7-8e61-89a04a35c780@d77g2000hsb.googlegroups.com> Yes, it is 1255 it's surprising you know that. any way this is the code I tried search=cnrl.GetValue() search= search.decode("cp1255") search=search.encode("utf8") word='' category=1 cur.execute('select * from hebrew_words where word like ?', [''+search+'']) this is the error it send me : 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) have any idea? Thank you for trying any way. it worms my Jewish art :) From mensanator at aol.com Mon Jun 9 01:53:15 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 8 Jun 2008 22:53:15 -0700 (PDT) Subject: Do this as a list comprehension? References: <4848b213$0$25711$607ed4bc@cv.net><484ad07b$0$25721$607ed4bc@cv.net> <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> <484c9830$0$5009$607ed4bc@cv.net> Message-ID: On Jun 8, 9:40?pm, John Salerno wrote: > Mensanator wrote: > > On Jun 8, 3:19?am, "Terry Reedy" wrote: > >> "Mensanator" wrote in message > > >>news:8d7c0912-422f-4480-a034-078f9dbcae24 at 2g2000hsn.googlegroups.com... > >> | On Jun 7, 6:43?pm, "Terry Reedy" wrote: > >> | > zip(range(9,2000000000), iterable) > >> | > >> | Oh, dear. You didn't actually try this, did you? > > >> Works fine in Py3, which is what I use now. > > > You really ARE cruel to the newbies, aren't you? > > > Don't you think it would have been appropriate > > to attach a large red label: WARNING! PY3! > > Heh heh, don't worry. Every time I see a range function, I immediately > think "creates a list". Not sure how I got into that habit, but it > happens every time! :) You probably got into that habit because that's what it does in 2.x, create a list. Now, if you're expecting that to happen you'll in for a surprise when you switch to Py3, won't you? From wicijowski at gmail.com Tue Jun 3 08:52:18 2008 From: wicijowski at gmail.com (janislaw) Date: Tue, 3 Jun 2008 05:52:18 -0700 (PDT) Subject: Ideas for master's thesis References: <15f65d1f-0e99-4661-a33f-4f16bb7d5ad2@l64g2000hse.googlegroups.com> Message-ID: <8099fd0b-607f-41a4-b918-03c765540407@59g2000hsb.googlegroups.com> On Jun 3, 2:27?am, miller.pau... at gmail.com wrote: > I'm sure you could probably find something having to do with Pypy > (http://codespeak.net/pypy/dist/pypy/doc/home.html) that would be both > manageable and significant enough to warrant a Master's thesis. The Pypy will fade out. You can for example write a compiler for LISP to CPython bytecode. Fits well for a master thesis. Regards, Jan Wicijowski From panyongzhi at gmail.com Mon Jun 2 09:22:14 2008 From: panyongzhi at gmail.com (Fossil Pan) Date: Mon, 2 Jun 2008 06:22:14 -0700 (PDT) Subject: a question about the #prefix of sys.argv References: Message-ID: <26ccd41d-3a6a-4b0e-9583-efb2d964441d@b5g2000pri.googlegroups.com> On Jun 2, 8:50 am, Aldarion wrote: > On 6?2?, ??8?05?, Peter Otten <__pete... at web.de> wrote: > > > Aldarion wrote: > > > for the little script > > > #egg.py > > > import sys > > > for k,v in enumerate(sys.argv): > > > print k,v > > > > it ignores the part after # on linux > > > below is the running output on windows and linux. no clue here. > > > This has nothing to do with python, it's the shell that treats the # and > > everything that follows as a comment. > > > $ ./listargs.py alpha #beta > > 0 ./listargs.py > > 1 alpha > > > But you can escape it: > > > $ ./listargs.py alpha \#beta > > 0 ./listargs.py > > 1 alpha > > 2 #beta > > > $ ./listargs.py alpha '#beta' > > 0 ./listargs.py > > 1 alpha > > 2 #beta > > > Peter > > thanks everyone for the quickly reply, i see now. Thank you Aldarion for your post. From bj_666 at gmx.net Sat Jun 7 04:15:01 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Jun 2008 08:15:01 GMT Subject: Parsing a path to components References: <7d7dd66c-b2bb-4a9a-a2e4-589079cda97b@e39g2000hsf.googlegroups.com> <14bf5448-4677-4ced-9d79-b4eb0c048218@56g2000hsm.googlegroups.com> Message-ID: <6auuc5F38s3s9U1@mid.uni-berlin.de> On Fri, 06 Jun 2008 23:57:03 -0700, s0suk3 wrote: > You can just split the path on `os.sep', which contains the path > separator of the platform on which Python is running: > > components = pathString.split(os.sep) Won't work for platforms with more than one path separator and if a separator is repeated. For example r'\foo\\bar/baz//spam.py' or: In [140]: os.path.split('foo//bar') Out[140]: ('foo', 'bar') In [141]: 'foo//bar'.split(os.sep) Out[141]: ['foo', '', 'bar'] Ciao, Marc 'BlackJack' Rintsch From usenet at technicalbloke.com Thu Jun 19 04:10:28 2008 From: usenet at technicalbloke.com (Roger Heathcote) Date: Thu, 19 Jun 2008 09:10:28 +0100 Subject: Combining music or video files? In-Reply-To: <02a1ba97$0$25051$c3e8da3@news.astraweb.com> References: <4855d5a5$0$11609$607ed4bc@cv.net> <1bydnYdof97ddsjVnZ2dnUVZ_uSdnZ2d@earthlink.com> <02a1ba97$0$25051$c3e8da3@news.astraweb.com> Message-ID: <3N6dnZKoI4fricfVnZ2dneKdnZydnZ2d@bt.com> John Salerno wrote: > "Dennis Lee Bieber" wrote in message > news:1bydnYdof97ddsjVnZ2dnUVZ_uSdnZ2d at earthlink.com... >> On Sun, 15 Jun 2008 22:53:19 -0400, John Salerno >> declaimed the following in comp.lang.python: >> Even the simplest format -> WAV, which is normally uncompressed >> audio samples, is wrapped in layers of informational packets. >> >> snip other stuff!!! > > Yikes! Then what I'm reading from your post (and others) is no, I can't do > it my way. ;) It *did* seem a little too easy, after all! > > I can't speak for video (and I'd imagine it's a factor more difficult) but it's really not that hard to concatenate audio in python. What you need to do... Import the right modules for the audio formats you want to read. Decide on a master output format, say CD quality - PCM 16bit 44.1Khz Stereo. Open a file for appending Read through each of your source files loading them into memory Get the sample rate and format Run the sample data through a function to convert it to the master output format* Squirt it to disk Finally take the resulting file, calculate a new header and munge the two together. Voila :) *I'm sure several modules have functions/methods for this but it wouldn't be very hard to roll your own either. Roger Heathcote http://www.technicalbloke.com From newsgroup.spamfilter at virtualinfinity.net Mon Jun 23 21:14:41 2008 From: newsgroup.spamfilter at virtualinfinity.net (Daniel Pitts) Date: Mon, 23 Jun 2008 18:14:41 -0700 Subject: MD5 hash for url and utf unicode converting to ascii In-Reply-To: References: Message-ID: <486066cc$0$20012$7836cce5@newsrazor.net> joe shoemaker wrote: > I would like to convert url into md5 hash. My question is that md5 > hash will create collision at 2^64. If you do long(value,16), where > value is the md5 hash string, would value returned from long(value, > 16) be unique as long as md5 hashed string is unique? when you move > md5 hashed string to long, where will the collision occur, at anything MD5's are not meant to be unique keys. They are designed to make it difficult to alter the original value and maintain the same hash. This prevents both errors and malevolent data tampering. Also note, I believe MD5 are typically 128 bits long, not 64, but the calculation for collision is more complicated than that. -- Daniel Pitts' Tech Blog: From alfasub000 at gmail.com Thu Jun 12 01:41:16 2008 From: alfasub000 at gmail.com (alfasub000 at gmail.com) Date: Wed, 11 Jun 2008 22:41:16 -0700 (PDT) Subject: catastrophic regexp, help! References: <26bda6a4-ad16-4b06-aff4-12e311ebaf81@59g2000hsb.googlegroups.com> Message-ID: On Jun 11, 11:07 pm, cirfu wrote: > On 11 Juni, 10:25, Chris wrote: > > > > > On Jun 11, 6:20 am, cirfu wrote: > > > > pat = re.compile("(\w* *)*") > > > this matches all sentences. > > > if fed the string "are you crazy? i am" it will return "are you > > > crazy". > > > > i want to find a in a big string a sentence containing Zlatan > > > Ibrahimovic and some other text. > > > ie return the first sentence containing the name Zlatan Ibrahimovic. > > > > patzln = re.compile("(\w* *)* zlatan ibrahimovic (\w* *)*") > > > should do this according to regexcoach but it seems to send my > > > computer into 100%CPU-power and not closable. > > > Maybe something like this would be of use... > > > def sentence_locator(s, sub): > > cnt = s.upper().count(sub.upper()) > > if not cnt: > > return None > > tmp = [] > > idx = -1 > > while cnt: > > idx = s.upper().find(sub.upper(), (idx+1)) > > a = -1 > > while True: > > b = s.find('.', (a+1), idx) > > if b == -1: > > b = s.find('.', idx) > > if b == -1: > > tmp.append(s[a+1:]) > > break > > tmp.append(s[a+1:b+1]) > > break > > a = b > > cnt -= 1 > > return tmp > > yes, seems very unpythonic though :) > must be a simpler way that isnt slow as hell. Why wouldn't you use character classes instead of groups? i.e: pat = re.compile(r'([ \w]*Zlatan Ibrahimivoc[ \w]*)') sentence = re.match(text).groups() As has been mentioned earlier, certain evil combinations of regular expressions and groups will cause python's regular expression engine to go (righteously) crazy as they require the internal state machine to branch out exponentially. From Caseyweb at gmail.com Thu Jun 5 07:48:08 2008 From: Caseyweb at gmail.com (Casey) Date: Thu, 5 Jun 2008 04:48:08 -0700 (PDT) Subject: Python and Harry Potter? References: <6aprloF38p4l7U1@mid.dfncis.de> Message-ID: Python fan??? Harry speaks Python fluently. We should all be so lucky! I'm told Harry is looking forward to Py3K and getting rid of all the old (hog)warts .... From ptmcg at austin.rr.com Sat Jun 14 14:48:27 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 14 Jun 2008 11:48:27 -0700 (PDT) Subject: Subclassing list, what special methods do this? References: <7ba7e964-2d34-4594-8cfc-79dbf904df18@f63g2000hsf.googlegroups.com> Message-ID: On Jun 13, 1:38?pm, Mike Kent wrote: > For Python 2.5 and new-style classes, what special method is called > for mylist[2:4] = seq and for del mylist[2:4] (given that mylist is a > list, and seq is some sequence)? > > I'm trying to subclass list, and I'm having trouble determining what > special methods I have to override in my class for the above two > operations. ?From my testing, it seems to be __setslice__ for both, > but the docs say __setslice__ and brethren are deprecated. ?I would > have thought that __setitem__ and __delitem__ would be what was > called, but again, my testing says otherwise. Or you could forget this "subclassing" stuff, and just implement __setitem__, __getitem__, __delitem__, __len__, and __iter__ in your own class, and not worry about what list does or doesn't do. You could have your class contain a list to implement with, and then delegate to it from your class's code. Overall, I think Python as a language favors composition/delegation over inheritance - c/d is so easy to do with __getattribute__, and inheritance is largely unnecessary since type/interface is not checked until runtime. Yet many O-O texts are written around C++ and Java's static type models, so we see a preponderance of patterns and conventional O-O wisdom recommending inheritance. For Python, it ain't necessarily so... -- Paul From deets at nospam.web.de Fri Jun 13 12:03:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 13 Jun 2008 18:03:53 +0200 Subject: Iterate creating variables? In-Reply-To: References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> <6bfhj5F3b47fmU1@mid.uni-berlin.de> <6bfj7bF3c3npoU1@mid.uni-berlin.de> Message-ID: <6bfk3fF3btpk3U1@mid.uni-berlin.de> > > Thank you, this is much closer to where I need to be... > > The issue is (and this is the part that you don't know, because I > didn't tell you!) is that I later need to call methods on > "self.checkbox1", for instance: > > self.checkbox1.GetValue() > > to determine if the box is checked or not. > > I should have included that piece in the initial problem description; > my apologies. Then translate the above to self.checkboxes[1].GetValue() The point of all this is the following: If you have a variable (even if not changing often, or being globally configured) number of objects, it's a good idea to keep them around in a list. Even if you need specific parameters for the checkboxes, it would most probably be better to do it like this checkbox_args = [ ("name", parameter, ...), ("other_name", other_parameter, ...), ] for parameters in checkbox_args: checkboxes.append(Checbbox(*parameters)) If you know on the other hand that you will have 10 checkboxes which have all a defined meaning, it might be better to use a meaningful name for them, like: self.create_backup = Checkbox(...) self.perform_authorization = Checkbox(...) From sjmachin at lexicon.net Fri Jun 6 19:27:18 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 6 Jun 2008 16:27:18 -0700 (PDT) Subject: File-writing not working in Windows? References: <80a7b951-591b-41a2-b76c-f97d75db0dad@25g2000hsx.googlegroups.com> Message-ID: <250e2658-4b9b-45ca-b8c6-56ae71b62726@v1g2000pra.googlegroups.com> On Jun 7, 1:18 am, tda... at gmail.com wrote: > All, > [code snipped] > > This code works PERFECTLY in Linux. Where I have a match in the file > I'm processing, it gets cut out from the start of the match until the > end of the match, and written to the temporary file in tempdir. > > It does not work in Windows. It does not create or write to the > temporary file AT ALL. It creates the tempdir directory with no > problem. > > Here's the kicker: it works perfectly in Windows if Windows is running > in VMware on a Linux host! (I assume that that's because VMware is > passing some call to the host.) > > Can anyone tell me what it is that I'm missing which would prevent the > file from being created on Windows natively? > > I'm sorry I can't provide any more of the code, and I know that that > will hamper your efforts in helping me, so I apologise up front. > > Assumptions: > You can assume self.checkbox25.GetValue() is always false for now, and > self.Info[x][0] contains a two character string like "00" or "09" or > "14". There is always a match in the fileTarget, so self.Info[x][2] > will always be true at some point, as will self.Info[x][4]. I am > cutting an HTML file at predetermined comment sections, and I have > control over the HTML files that are being cut. (So I can force the > file to match what I need it to match if necessary.) Assume nothing. Don't believe anyone who says "always". Insert some print statements and repr() calls to show what's actually there. > I hope however that it's something obvious that a Python guru here > will be able to spot and that this n00b is missing! *IF* the problem is in the code, it would be easier to spot if you had removed large chunks of indentation before posting. Less is more: change "if (foo == 2):" to "if foo == 2:", "foo == True" to "foo", and "foo == False" to "not foo". Browse http://www.python.org/dev/peps/pep-0008/ HTH, John From sjmachin at lexicon.net Sat Jun 21 19:40:29 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 21 Jun 2008 16:40:29 -0700 (PDT) Subject: My n00bie brain hurts after "Python setup.py install". References: <6a4560d6-0ec5-4a2b-9c93-fa1febe23f07@p25g2000pri.googlegroups.com> Message-ID: <8d006140-582d-44d2-be15-112bb56eea68@f24g2000prh.googlegroups.com> On Jun 22, 9:05 am, bsag... at gmail.com wrote: > I downloaded Mark Pilgrims's feedparser.py in a zipfile to my Windows > machine, unzipped it and tried to install it to no avail. > > Here is the result => > > C:\>python c:\scripts\feedparser-4.1\setup.py install The convention is to run setup.py from the current directory, unless instructed otherwise; what did the package's readme say? Try: cd \scripts\feedparser-4.1 python setup.py install > running install > running build > running build_py > file feedparser.py (for module feedparser) not found > running install_lib > warning: install_lib: 'build\lib' does not exist -- no Python modules > to install > running install_egg_info > Writing C:\Python25\Lib\site-packages\feedparser-4.1-py2.5.egg-info > > WTF? The file feedparser.py did exist in the same place as setup.py. > Even if it works, what exactly does this setup.py do for me? If I just > manually place feedparser.py in my Python site-packages file it works > fine. In general, a setup.py install may do lots of things besides coping 1 file. Manually placing files in site-packages is not a good habit to get into. > As for that egg-info file, I googled "python eggs" and now I am > really confused. Eggs are part of a new experimental package distribution scheme. Don't worry about it. Cheers, John From pecora at anvil.nrl.navy.mil Mon Jun 2 11:05:43 2008 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Mon, 02 Jun 2008 17:05:43 +0200 Subject: php vs python References: Message-ID: In article , Ethan Furman wrote: > Jerry Stuckle wrote: > > > > > As I've said before - good programmers can write good code in any > > language. > > > > So... an eloquent speaker of English is also an eloquent speaker of > Spanish/French/German? Oh, Bull. Computer languages are so narrow they are more like dialects of a single language. If you know English you can learn to speak to a Brit, Scot, or Aussie. That's more like it...if you really want to stretch the definition of a language. And it is a stretch. Anyone speak C? Sheeze. -- -- Lou Pecora From pfreixes at gmail.com Thu Jun 19 04:14:15 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Thu, 19 Jun 2008 10:14:15 +0200 Subject: please critique my thread code In-Reply-To: <9ZWdnVMfvdwglMfVnZ2dnUVZ8q_inZ2d@bt.com> References: <222a1935-20dd-44a0-bc42-71a25be96d30@79g2000hsk.googlegroups.com> <9ZWdnVMfvdwglMfVnZ2dnUVZ8q_inZ2d@bt.com> Message-ID: <207312b70806190114x2802263s7c8397e300535aac@mail.gmail.com> > > MRAB wrote: > > Erm, shurely the bottleneck will be bandwidth not processor/memory?* If it > isn't then - yes, you run the risk of actually DOSing their servers! > > Your mac will run thousands of threads comfortably but your router may not > handle the thousands of TCP/IP connections you throw at it very well, > especially if it is a domestic model, and sure as hell sourceforge aren't > going to want more than a handfull of concurrent connections from you. > > Typical sourceforge page ~ 30K > Project pages to read = 240000 > > = ~6.8 Gigabytes The best path for avoid congestion network problem and probably "DOS attack" it's use a equilibrate number of parallel connection with a number of threads. One router can handle hundred connections and Mac thread implementation may be also - with a lot of memory or stack size profiling. If you run hundred threads you will be fight with OS, Webserver, Router and network starvation problems. I believe use a 64 number of threads it's ok, but probably all 64 thread connections will be performance for the same sourceforge web server - balancing algorithm - and may be that this week up suspicion to the admin. May be, you can use httplib [1] for do a persistent connection and reuse same connection for same thread. [1] http://www.python.org/doc/2.4.2/lib/httplib-examples.html -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From Michael.Coll-Barth at VerizonWireless.com Thu Jun 5 14:37:19 2008 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Thu, 5 Jun 2008 14:37:19 -0400 Subject: Please unregister this mail-address out of mailing-list. In-Reply-To: References: Message-ID: <20080605185002.46A9F1E401A@bag.python.org> > -----Original Message----- > From: Hank @ITGroup > I am writing this letter to unsubscribe this mail-address from python > mail-list. > -- > http://mail.python.org/mailman/listinfo/python-list > No problem, Hank. You will be officially off of this 'mail-list' after a visit to this site; http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From sjmachin at lexicon.net Fri Jun 20 08:12:53 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 20 Jun 2008 05:12:53 -0700 (PDT) Subject: Pyparsing performance boost using Python 2.6b1 References: Message-ID: On Jun 19, 8:40 pm, Paul McGuire wrote: > I just ran my pyparsing unit tests with the latest Python 2.6b1 > (labeled internally as Python 2.6a3 - ???), Hi, Paul. If it says 2.6a3, that's what it is. Look at the thread of replies to Barry Warsaw's announcement of 2.6b1 ... [from memory] there was a delay expected before MvL would make a Windows msi available, and in the meantime the download page would point to "the alpha version". Cheers, John From aishwaryagroup at gmail.com Wed Jun 11 01:16:31 2008 From: aishwaryagroup at gmail.com (AISHWARYA) Date: Tue, 10 Jun 2008 22:16:31 -0700 (PDT) Subject: MANAGEMENT SOFTWARE Message-ID: ******************************************************* http://maintanancemanagementsoftwareservises.blogspot.com From kay.schluehr at gmx.net Tue Jun 3 13:53:10 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 3 Jun 2008 10:53:10 -0700 (PDT) Subject: parser recommendation References: <686de663-94d2-4e8b-b079-197793d0a8cc@2g2000hsn.googlegroups.com> Message-ID: <68d0244e-d0e3-4495-b11c-9a90e38260f1@d1g2000hsg.googlegroups.com> On 3 Jun., 19:34, "Filipe Fernandes" wrote: > # The current implementation is only somewhat object-oriented. The > # LR parser itself is defined in terms of an object (which allows multiple > # parsers to co-exist). However, most of the variables used during table > # construction are defined in terms of global variables. Users shouldn't > # notice unless they are trying to define multiple parsers at the same > # time using threads (in which case they should have their head examined). > > Now, I'm invariably going to have to use threads... I'm not exactly > sure what the author is alluding to, but my guess is that to overcome > this limitation I need to acquire a thread lock first before > "defining/creating" a parser object before I can use it? Nope. It just says that the parser-table construction itself relies on global state. But you will most likely build your parser offline in a separate run. From wuwei23 at gmail.com Thu Jun 5 12:36:17 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 5 Jun 2008 09:36:17 -0700 (PDT) Subject: Import removing first module component References: <75481b47-87ec-4a84-8063-7abbdb286d62@u6g2000prc.googlegroups.com> Message-ID: On Jun 6, 1:44 am, koblas wrote: > Another person pointed out that I should check on the __init__.py and > make sure lmtp is defined in the __all__ block. I didn't have an > __init__.py at that level of the tree, which must have been causing > problems, but clearly I don't understand the full inheritance of > __init__.py and sub-directories. Heya, If you're not sure about packages, it's covered in the python docs here: http://docs.python.org/tut/node8.html#SECTION008400000000000000000 An __all__ variable doesn't have to be defined, the __init__.py can be empty, as it's the presence of that file that informs python that the folder is a package. The example in the docs should help you here. From alex.m.gusarov at gmail.com Fri Jun 20 10:39:19 2008 From: alex.m.gusarov at gmail.com (Alex Gusarov) Date: Fri, 20 Jun 2008 21:39:19 +0700 Subject: py2exe & application add-ons In-Reply-To: <11cda8d4-1359-42cb-8f8d-16dd57eb0442@z16g2000prn.googlegroups.com> References: <11cda8d4-1359-42cb-8f8d-16dd57eb0442@z16g2000prn.googlegroups.com> Message-ID: Thanks everybody, yes, I use 'exec' for files. And "freeze" modules - thanks too, I almost forgot this opportunity. -- Best regards, Alex Gusarov From geoff.bache at jeppesen.com Wed Jun 25 04:49:04 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Wed, 25 Jun 2008 01:49:04 -0700 (PDT) Subject: Terminating processes on Windows (handles and IDs) References: <98b73a28-fa07-4eac-8f3c-aec65aa819fe@k37g2000hsf.googlegroups.com> <36a78f0c-cbd4-45cd-a69f-44566f47b15f@b1g2000hsg.googlegroups.com> Message-ID: <20fee08e-b75d-4d4f-a4c9-b329fdc5d07c@t54g2000hsg.googlegroups.com> Thanks for the help Tim! Good to see this is being sorted in Python at last, although it'll be some time before I can use only Python 2.6 I suspect... I'm making use of _handle now and it works - most of the time. The remaining issues are probably PyGTK problems rather than python ones though, and hence off topic here. Regards, Geoff From tdahsu at gmail.com Sun Jun 8 10:29:48 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Sun, 8 Jun 2008 07:29:48 -0700 (PDT) Subject: File-writing not working in Windows? References: <80a7b951-591b-41a2-b76c-f97d75db0dad@25g2000hsx.googlegroups.com> <5c4313fb-3672-4b03-9d62-58fd6e3a76bd@w34g2000prm.googlegroups.com> Message-ID: On Jun 8, 4:11?am, Lie wrote: > On Jun 6, 10:18?pm, tda... at gmail.com wrote: > > > > > > > All, > > > I have the following code: > > ? ? ? ? ? ?for fileTarget in dircache.listdir("directory"): > > ? ? ? ? ? ? ? ? (dirName, fileName) = os.path.split(fileTarget) > > ? ? ? ? ? ? ? ? f = open(fileTarget).readlines() > > ? ? ? ? ? ? ? ? copying = False > > ? ? ? ? ? ? ? ? for i in range(len(f)): > > ? ? ? ? ? ? ? ? ? ? for x in range (0,24,1): > > ? ? ? ? ? ? ? ? ? ? ? ? if (re.search(self.Info[x][3], f[i])): > > #If we have a match for our start of section... > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (self.Info[x][2] == True): > > #And it's a section we care about... > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? copying = > > True ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?#Let's start copying the lines out > > to the temporary file... > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (os.name == "posix"): > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (self.checkbox25.GetValue() == > > False): > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? tempfileName = "tempdir/" + > > self.Info[x][0] + "_tmp_" + fileName + ".txt" > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? tempfileName = > > self.textctrl07.GetValue() + "/" + self.Info[x][0] + "_xyz.txt" > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (self.checkbox25.GetValue() == > > False): > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? tempfileName = "tempdir\\" + > > self.Info[x][0] + "_tmp_" + fileName + ".txt" > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? tempfileName = > > self.textctrl07.GetValue() + "\\" + self.Info[x][0] + "_xyz.txt" > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? copying = False > > ? ? ? ? ? ? ? ? ? ? ? ? if (re.search(self.Info[x][4], f[i])): > > #Now we've matched the end of our section... > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? copying = > > False ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #So let's stop copying out to > > the temporary file... > > ? ? ? ? ? ? ? ? ? ? if (copying == True): > > ? ? ? ? ? ? ? ? ? ? ? ? g = open(tempfileName, > > 'a') ? ? ? ? ? ? ? ? ? ? #Open that file in append mode... > > > g.write(f[i]) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #Write the line... > > ? ? ? ? ? ? ? ? ? ? ? ? g.close() > > > This code works PERFECTLY in Linux. ?Where I have a match in the file > > I'm processing, it gets cut out from the start of the match until the > > end of the match, and written to the temporary file in tempdir. > > > It does not work in Windows. ?It does not create or write to the > > temporary file AT ALL. ?It creates the tempdir directory with no > > problem. > > > Here's the kicker: it works perfectly in Windows if Windows is running > > in VMware on a Linux host! ?(I assume that that's because VMware is > > passing some call to the host.) > > > Can anyone tell me what it is that I'm missing which would prevent the > > file from being created on Windows natively? > > > I'm sorry I can't provide any more of the code, and I know that that > > will hamper your efforts in helping me, so I apologise up front. > > > Assumptions: > > You can assume self.checkbox25.GetValue() is always false for now, and > > self.Info[x][0] contains a two character string like "00" or "09" or > > "14". ?There is always a match in the fileTarget, so self.Info[x][2] > > will always be true at some point, as will self.Info[x][4]. ?I am > > cutting an HTML file at predetermined comment sections, and I have > > control over the HTML files that are being cut. ?(So I can force the > > file to match what I need it to match if necessary.) > > > I hope however that it's something obvious that a Python guru here > > will be able to spot and that this n00b is missing! > > > Thanks! > > Well, not to be rude, but that's quite a spaghetti code, some of the > guilt, however, was for the mailing program that cuts 80+ lines. > Others was the use of things like "for i in range(len(f)):" or "if (a > == True)". > > Try checking whether you're trying to write to a path like r"\dir > \file.txt" or r"dir\file.txt" instead of r"C:\dir\file.txt" in > Windows. > > If that doesn't solve the problem, tell us a few things: > - Any error messages? Or simply nothing is written out? > - Has a blank file get created?- Hide quoted text - > > - Show quoted text - Thanks to everyone for the help. I really do appreciate your suggestions and time; again I apologise for not being able to give you all the code to diagnose. I understand that it made this more difficult and thank you for the input! The error was not with the script. The error was with the HTML that was being parsed! It's the last thing I considered to check, and where I should have started. John, thank you for the link to the style guide. I can see its use and will make my code conform to the standards. Thanks again to everyone! From zephyrfalcon!NO_SPAM! at gmail.com Sat Jun 7 12:58:39 2008 From: zephyrfalcon!NO_SPAM! at gmail.com (Hans Nowak) Date: Sat, 07 Jun 2008 12:58:39 -0400 Subject: Dynamically naming objects. In-Reply-To: <3d2a85b2-255d-4e93-8cfb-e2772f57b69a@u6g2000prc.googlegroups.com> References: <8a99c3fa-1eeb-49b3-a714-b6063ec1daab@d19g2000prm.googlegroups.com> <3d2a85b2-255d-4e93-8cfb-e2772f57b69a@u6g2000prc.googlegroups.com> Message-ID: <15z2k.1218$LL4.885@bignews7.bellsouth.net> Kalibr wrote: > On Jun 7, 1:20 pm, Hans Nowak wrote: >> Kalibr wrote: >>> I've been developing a small script to fiddle with classes, and came >>> accross the following problem. Assuming I get some user input asking >>> for a number, how would I spawn 'n' objects from a class? >>> i.e. I have a class class 'user' and I don't know how many of them I >>> want to spawn. >>> Any ideas? >> Sure. This will give you a list of n instances of user: >> >> [user() for i in range(n)] >> >> Of course, you could also use a good old for loop: >> >> for i in range(n): >> u = user() >> ...do something with u... >> >> Hope this helps! >> >> -- >> Hans Nowak (zephyrfalcon at gmail dot com)http://4.flowsnake.org/ > > whoops, replied to author.... > > What I wanted to ask before was won't 'u' be overwritten with a new > object each time the loop ticks over? Yes, so you have to store it somewhere, if you want to keep the object around. The list comprehension mentioned above stores all the objects in a list, after which they can be accessed at will via indexing. > what I want to do is have, say 5 users in a game, so I'd have to spawn > 5 objects. I can't do that because I have'nt hardcoded any object > names for them. > > or does it somehow work? how would I address them if they all have the > name 'u'? users = [user() for i in range(n)] # use: users[0], users[1], etc -- Hans Nowak (zephyrfalcon at gmail dot com) http://4.flowsnake.org/ From shahvishang at gmail.com Fri Jun 13 14:15:21 2008 From: shahvishang at gmail.com (Vishang Shah) Date: Fri, 13 Jun 2008 11:15:21 -0700 (PDT) Subject: Python Socket programming References: <655455.29695.qm@web7907.mail.in.yahoo.com> Message-ID: <3ce3356a-2640-475f-a92d-f66fd56fb585@d19g2000prm.googlegroups.com> there is this good link for explanation on how sockets work, http://www.tutorialgrub.com/tutorials/Python/Development/Socket-Programming-HOWTO_325.html From secretofmcouple at gmail.com Sat Jun 7 02:29:52 2008 From: secretofmcouple at gmail.com (Happy Married Couple) Date: Fri, 6 Jun 2008 23:29:52 -0700 (PDT) Subject: SECRETS OF THE MOST HAPPY LOVED AND BLISSFUL COUPLES IN THE WORLD Message-ID: <89ac9588-8635-4b42-9332-41ee42cb369f@j1g2000prb.googlegroups.com> You're about to discover the 'magic ingredients' that make some couples live happy and blissful marriages for DECADES and how you can too. Dear Friend, My name is Michael Webb. I DON'T have a doctorate in counseling, marriage studies and I DON'T host a radio call in show? but I DO have what most other relationship "experts? don?t have?a blissful marriage. Which is why hundreds of men and women ask for my relationship advice and have done so for 12 years now. In fact, this may surprise you but my wife Athena and I have never even had a fight in our 17 years of marriage. Yes, it's true. Of course I know ?this sounds bizarre, even impossible but in a moment I'll explain exactly how this was possible. And more importantly, how it's possible for you. You see, I grew up in a family with 6 sisters. And in my lifetime I've seen them abused by the various men in their lives. Even my mother has the scars from two unsuccessful marriages. After witnessing this for too long, I decided be the sort of husband my mom and sisters had dreamed of but never had. I studied relationships for a long time, took good notes on what things blissful couples do differently than those who have the typical relationship full of ups and downs. (By the way, nearly all "relationship" books focus on what couples are doing wrong. I'll let you know what couples are doing right.) Several years later, I released my first book, The Romantic's Guide, which went on to become a national bestseller. It was released in February 2000 and is already in its 6th printing. From there, things started to go crazy as the media started hounding me for interviews left, right and center. To date, I've published 16 books helping both women and men with almost every imaginable relationships and marriage problem there is. Please visit our website for further details:- http://tubeurl.com/14wfhn From tjreedy at udel.edu Mon Jun 23 02:19:55 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Jun 2008 02:19:55 -0400 Subject: -1/2 In-Reply-To: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> References: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> Message-ID: Serve Lau wrote: > What is the expected result of -1/2 in python? Python 3.0b1 (r30b1:64403M, Jun 19 2008, 14:56:09) [MSC v.1500 32 bit (Intel)] n win32 Type "help", "copyright", "credits" or "license" for more information. >>> -1/2 -0.5 as expected ;-) -1//2 is as Gary Herron specified from the manual, for reasons posted here several times and which should be in the FAQ From gh at ghaering.de Thu Jun 26 07:03:27 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 26 Jun 2008 13:03:27 +0200 Subject: Urllib(1/2) how to open multiple client sockets? In-Reply-To: References: Message-ID: ShashiGowda wrote: > Hey there i made a script to download all images from a web site but > it runs damn slow though I have a lot of bandwidth waiting to be used > please tell me a way to use urllib to open many connections to the > server to download many pics simultaneously.... Any off question > suggestions are also ok... "Simultaneously" means using multiple threads (or processes). You could create worker threads that do the downloading (use the threading module for this) and communicate with them via a queue (use the Queue module for this). For example the main thread would then do the HTML parsing and push the image URLs to the worker threads via the queue. Each worker thread then polls the queue and downloads the images it gets. One issue is how to terminate the multithreaded application. A simple approach is to use a sentinel value to push to the queue to signal the worker threads to quit. Something like "QUIT" will do. Be sure to push at least as many sentinel values as you have worker threads, then. -- Gerhard From mccredie at gmail.com Tue Jun 3 16:20:14 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 3 Jun 2008 13:20:14 -0700 (PDT) Subject: Creating object in function doesn't seem to create a new object. References: <0d321eb1-8bc3-4ae4-893f-9ad137d9eca4@25g2000hsx.googlegroups.com> Message-ID: <9fada70b-8f23-468e-86f1-00d8d43f6b4c@26g2000hsk.googlegroups.com> > I thought that when I wrote fc1 = FlightCondition() in the function it > would create a new FlightCondition object which would be passed back > every time. > Instead it seems to re-reference the old version and continue to add > to it. That is exactly what is happening. You have created a class with two _class_ attributes that are lists. These attributes are attached to the _class_ not the instance that was created. You are simply mutating the list that is attached to the class. You really want to do something like this: class FlightCondition(object): def __init__(self): self.lsf = [0,'Low Speed Flare'] self.vto = [0,'Vertical Take-Off'] Other than that, its hard to tell what you are actually trying to do, but likely get_flight_condition could become a method of the FlightCondition class. Matt From rdm at rcblue.com Wed Jun 4 14:48:24 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 04 Jun 2008 11:48:24 -0700 Subject: Books for programmers In-Reply-To: <32791EDC-1033-4B65-BFB5-DF1CF71EF20D@comhem.se> References: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> <32791EDC-1033-4B65-BFB5-DF1CF71EF20D@comhem.se> Message-ID: <20080604184837.505CB1E4002@bag.python.org> Do not neglect the 2008 book, "Object-Oriented Programming in Python", by Goldwasser and Letscher. Dick Moores From sjmachin at lexicon.net Sat Jun 7 20:01:33 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 7 Jun 2008 17:01:33 -0700 (PDT) Subject: Need help porting Perl function References: <379fb630-5a4c-44e6-920e-3de7acd6bfd4@z24g2000prf.googlegroups.com> <8bb0b0ce-e840-416f-b9c1-4092fd5fa771@56g2000hsm.googlegroups.com> Message-ID: <7248c81b-0ff9-45f5-acb5-63a8b2d41817@f24g2000prh.googlegroups.com> On Jun 8, 8:17 am, eat... at gmail.com wrote: > On Jun 7, 5:56 pm, John Machin wrote: > > > > > On Jun 8, 6:05 am, eat... at gmail.com wrote: > > > > On Jun 7, 2:42 pm, "Daniel Fetchinson" > > > wrote: > > > > > > Hi. I'd like to port a Perl function that does something I don't > > > > > know how to do in Python. (In fact, it may even be something that > > > > > is distinctly un-Pythonic!) > > > > > > The original Perl function takes a reference to an array, removes > > > > > from this array all the elements that satisfy a particular criterion, > > > > > and returns the list consisting of the removed elements. Hence > > > > > this function returns a value *and* has a major side effect, namely > > > > > the target array of the original argument will be modified (this > > > > > is the part I suspect may be un-Pythonic). > > > > > > Can a Python function achieve the same effect? If not, how would > > > > > one code a similar functionality in Python? Basically the problem > > > > > is to split one list into two according to some criterion. > > > > > This function will take a list of integers and modify it in place such > > > > that it removes even integers. The removed integers are returned as a > > > > new list (disclaimer: I'm 100% sure it can be done better, more > > > > optimized, etc, etc): > > > > > def mod( alist ): > > > > old = alist[:] > > > > ret = [ ] > > > > for i in old: > > > > if i % 2 == 0: > > > > ret.append( alist.pop( alist.index( i ) ) ) > > > > > return ret > > > > > x = range(10,20) > > > > > print x > > > > r = mod( x ) > > > > print r > > > > print x > > > > > HTH, > > > > Daniel > > > > -- > > > > Psss, psss, put it down! -http://www.cafepress.com/putitdown > > > > def mod( alist ): > > > return [ alist.pop( alist.index( x ) ) for x in alist if x % 2 == > > > 0 ] > > > > alist = range(10,20) > > > blist = mod( alist ) > > > > print alist > > > print blist > > > > The same thing with list comprehensions. > > > Not the same. The original responder was careful not to iterate over > > the list which he was mutating. > > > >>> def mod(alist): > > > ... return [alist.pop(alist.index(x)) for x in alist if x % 2 == 0] > > ...>>> a = range(10) > > >>> print mod(a), a > > > [0, 2, 4, 6, 8] [1, 3, 5, 7, 9]>>> a = [2,2,2,2,2,2,2,2] > > >>> print mod(a), a > > > [2, 2, 2, 2] [2, 2, 2, 2] > > # should be [2, 2, 2, 2, 2, 2, 2, 2] [] > > Alas, it appears my understanding of list comprehensions is > significantly less comprehensive than I thought =) It's nothing to do with list comprehensions, which are syntactical sugar for traditional loops. You could rewrite your list comprehension in the traditional manner: def mod(alist): ret = [] for x in alist: if x % 2 == 0: ret.append(alist.pop(alist.index(x)) return ret and it would still fail for the same reason: mutating the list over which you are iterating. At the expense of even more time and memory you can do an easy fix: change 'for x in alist' to 'for x in alist[:]' so that you are iterating over a copy. Alternatively, go back to basics: >>> def modr(alist): ... ret = [] ... for i in xrange(len(alist) - 1, -1, -1): ... if alist[i] % 2 == 0: ... ret.append(alist[i]) ... del alist[i] ... return ret ... >>> a = [2,2,2,2,2,2,2,2,2] >>> print modr(a), a [2, 2, 2, 2, 2, 2, 2, 2, 2] [] >>> HTH, John From semanticist at gmail.com Sat Jun 14 01:15:52 2008 From: semanticist at gmail.com (Miles) Date: Sat, 14 Jun 2008 01:15:52 -0400 Subject: struct unpack issue In-Reply-To: <20080614012734.30329619.ioceanio@gmail.com> References: <20080614012734.30329619.ioceanio@gmail.com> Message-ID: On Fri, Jun 13, 2008 at 9:27 PM, Ping Zhao wrote: > However, when I tried to rewrite them in short: > > header = struct.unpack('2s1i', self.__read(src, 6)) > ... > It was weired that the required argument length increased to 8. This is an alignment issue; if you don't specify a structure format character, the struct module acts like the data is laid out in memory as a C compiler would do it. http://en.wikipedia.org/wiki/Data_structure_alignment http://docs.python.org/lib/module-struct.html Specifying little-endian byte order will force the data to be packed (unaligned), and will also make your code more portable: struct.unpack('<2s1i', ...) -Miles From sturlamolden at yahoo.no Tue Jun 3 14:04:54 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 3 Jun 2008 11:04:54 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> Message-ID: <2930ad39-a3ef-49fa-9e37-26ada87f2d95@m44g2000hsc.googlegroups.com> On Jun 2, 12:40 pm, Antoon Pardon wrote: > I think you completed missed the point. > > This is just a proof of concept thing. In a real example there would > of course no Set en Get methods but just methods that in the course > of their execution would access or update the hidden attributes I have to agree with Banks here, you have not provided an example of data hiding. It does not discriminate between attribute access from within and from outside the class. You just assume that the attribute named 'hidden' will be left alone. Also naming it hidden is stupid as it is visible. What you need is a mechanism that will thrown an exception whenever an attribue is accessed from outside the class, but not from inside. The mechanism must also be impossible to override with additional code. If Ada is what you want, Ada is what you should use. From Scott.Daniels at Acm.Org Sun Jun 29 17:40:44 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 29 Jun 2008 14:40:44 -0700 Subject: list extension ? In-Reply-To: References: Message-ID: Stef Mientki wrote: ... (approximately, I PEP-8'ed it a bit) ... > class tGrid_List(list): > def __init__(self, value=[]): > list.__init__(self, value) > # and with this new list component, I can add new attributes on the fly > a = tGrid_list([2, 3]) > a.New_Attribute = 'some text' > > # I'm not allowed to this with the standard list > Can someone explain this different behavior ? Yes, you did not add a __slots__ member, so the object will have a __dict__ attribute. The __slots__ stuff is a storage optimization for frequently used data types (not worth it if you don't plan to have more than several thousand at any one time). Lists (for that matter most Python builtin types) get used a lot, so they have that built in. You can observe that even on the most trivial extensions: class AttributableInt(int): pass class AttributeFreeInt(int): __slots__ = () --Scott David Daniels Scott.Daniels at Acm.Org From gh at ghaering.de Thu Jun 12 11:14:34 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 12 Jun 2008 17:14:34 +0200 Subject: Counting things fast - was Re: Summing a 2D list In-Reply-To: References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> Message-ID: Aidan wrote: > does this work for you? > > users = [1,1,1,2,2,3,4,4,4] > score = [0,1,5,3,1,2,3,3,2] > > d = dict() > > for u,s in zip(users,score): > if d.has_key(u): > d[u] += s > else: > d[u] = s > > for key in d.keys(): > print 'user: %d\nscore: %d\n' % (key,d[key]) I've recently had the very same problem and needed to optimize for the best solution. I've tried quite a few, including: 1) using a dictionary with a default value d = collections.defaultdict(lambda: 0) d[key] += value 2) Trying out if avoiding object allocation is worth the effort. Using Cython: cdef class Counter: cdef int _counter def __init__(self): self._counter = 0 def inc(self): self._counter += 1 def __int__(self): return self._counter def __iadd__(self, operand): self._counter += 1 return self And no, this was *not* faster than the final solution. This counter class, which is basically a mutable int, is exactly as fast as just using this one (final solution) - tada! counter = {} try: counter[key] += 1 except KeyError: counter[key] = 1 Using psyco makes this a bit faster still. psyco can't optimize defaultdict or my custom Counter class, though. -- Gerhard From norseman at hughes.net Wed Jun 25 17:00:41 2008 From: norseman at hughes.net (norseman) Date: Wed, 25 Jun 2008 14:00:41 -0700 Subject: reading from list with paths In-Reply-To: <6c1ed580-259a-4df2-b389-ecf38296a138@25g2000hsx.googlegroups.com> References: <6c1ed580-259a-4df2-b389-ecf38296a138@25g2000hsx.googlegroups.com> Message-ID: <4862B1F9.7030501@hughes.net> antar2 wrote: > Hello, > > I would like to read and print files, of which the complete filepaths > are > mentioned in another textfile. In this textfile (list.txt) are for > example the following paths: > > /data/chorec/chorec-nieuw/s01/S01C001M1/S01C001M1_1LG_f01.TextGrid > /data/chorec/chorec-nieuw/s01/S01C001M1/ > S01C001M1_1LGPseudo_f01.TextGrid > /data/chorec/chorec-nieuw/s01/S01C001M1/S01C001M1_AVI1_f01.TextGrid > > I know how to open and read one file in my current directory, > but after trying to find this out my self, I give up... > > I already got one answer for this question, but it did not work > > Thanks a lot > > Antar2 > > -- > http://mail.python.org/mailman/listinfo/python-list > > > --------------------------------- I think what you want is more like: contents of a file named printthem.py ..... import os p = open('list.txt') for vpath in p: for f in os.listdir(vpath): print '\n\tContents of:',vpath+'/'+f f = open(vpath+'/'+f) print f.read() f.close() print '\n\t\t\t\tEND OF FILE\x0C' p.close() print "All Done. Is there any paper left?" ..... usage: python printthem.py >/dev/lp0 Unix python printthem.py > prn: Microsoft On Microsoft use '\\' in place of '/' following each vpath above The \x0C is Ctrl-L aka: ff or FormFeed norseman From siona at chiark.greenend.org.uk Tue Jun 17 06:02:19 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 17 Jun 2008 11:02:19 +0100 (BST) Subject: 'string'.strip(chars)-like function that removes from the middle? References: <48569B9E.6030206@admailinc.com> <200806161839.13647.omer@no-log.org> Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: >Terry Reedy wrote: >> >>> 'abcde'.translate(str.maketrans('','','bcd')) >> 'ae' >You should mention that you are using Python 3.0 ;) >The 2.5 equivalent would be > >>>> u"abcde".translate(dict.fromkeys(map(ord, u"bcd"))) >u'ae' Only if you're using Unicode: >>> 'abcde'.translate(string.maketrans('',''), 'bcd') 'ae' >>> sys.version_info (2, 4, 4, 'final', 0) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From cokofreedom at gmail.com Fri Jun 6 03:03:00 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Fri, 6 Jun 2008 00:03:00 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <73d73b35-6203-44d4-a9b4-f30b3fc5ca65@z66g2000hsc.googlegroups.com> <34223793-086b-477e-ae1f-06feee243ef9@i36g2000prf.googlegroups.com> <3a6081bd-d90b-4ba5-bf12-a64fa63a9efb@r66g2000hsg.googlegroups.com> <32a4460f-5333-4608-bd84-69b7308c06ef@f24g2000prh.googlegroups.com> <354e862f-e19d-4f25-960f-df3309d572ab@a32g2000prf.googlegroups.com> <4847d203$0$32733$426a74cc@news.free.fr> <87lk1jzgri.fsf@mulj.homelinux.net> <39a7805f-6590-4505-bfa2-0735090d553b@t12g2000prg.googlegroups.com> Message-ID: Someone asked about Java; class FieldTest { public String publicString = "Foobar"; private String privateString = "Hello, World!"; } import java.lang.reflect.Field; public class Test4 { public static void main(String args[]) { final Field fields[] = FieldTest.class.getDeclaredFields(); for (int i = 0; i < fields.length; ++i) { System.out.println("Field: " + fields[i]); } } } OUTPUT >>>> Field: public java.lang.String FieldTest.publicString Field: private java.lang.String FieldTest.privateString And to edit it; import java.lang.reflect.Field; public class Test7 { public static void main(String args[]) throws Exception { final Field fields[] = FieldTest.class.getDeclaredFields(); for (int i = 0; i < fields.length; ++i) { if ("privateString".equals(fields[i].getName())) { FieldTest fieldTest = new FieldTest(); Field f = fields[i]; f.setAccessible(true); System.out.println(f.get(fieldTest)); f.set(fieldTest, "Modified Field"); System.out.println(f.get(fieldTest)); break; } } } } OUTPUT >>>> Hello, World! Modified Field Enjoy. From kenobi at gmail.com Tue Jun 3 09:30:06 2008 From: kenobi at gmail.com (Rick Kwan) Date: Tue, 3 Jun 2008 06:30:06 -0700 (PDT) Subject: Books for programmers References: <9cdaa72e-2bd3-4151-9deb-4837c4aba151@l64g2000hse.googlegroups.com> Message-ID: <4a32fae8-c8d0-40a5-a6bd-b55f534d2d36@m73g2000hsh.googlegroups.com> On Jun 3, 12:22 am, V wrote: > I'm a C++, Java and C programmer, and I'm searching for a (preferably > printed) book that teaches me the "Python idioms", i.e. the "Python > way" of doing something. > > Ideally, I'm searching for a book like "Effective C++" or "Effective > Java", that does not lose time teaching what is a class, or a > function, or a loop, but that enters into details and describes not > only the "how", but also the "why". I like "Core Python Programming", 2nd ed., by Wesley Chun. After a couple of years of reasonably intense learn-on-my-own Python via "Learning Python" by Mark Lutz, and other resources, I was shocked how much I didn't know about Python when I picked up Chun's book. It's pretty thick (1100 pages?) and covers a lot of basic stuff, but that can be skimmed pretty quickly. Two large reasons it is so thick: (1) lots of annotated examples; (2) pretty thorough tables on language features, some of which I didn't pick up going through docs.python.com. (Full disclosure: I joined a group of Pythonistas and got to review the 2nd edition book before it went to press; so a few of my corrections made it into print. But really, I was blown away by how much I picked up in the process.) From george.sakkis at gmail.com Thu Jun 5 11:38:26 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 5 Jun 2008 08:38:26 -0700 (PDT) Subject: Tuples part 2 References: <6d3e6d40-63a6-40d1-8ea4-5ddf40238d8d@m44g2000hsc.googlegroups.com> <99bc30fb-532a-4c4f-9f5e-e7a18c28d2a5@z72g2000hsb.googlegroups.com> <0ecaaa47-3ad4-4f67-9d48-94d5d1951bc6@y21g2000hsf.googlegroups.com> Message-ID: On Jun 5, 11:21 am, Ivan Illarionov wrote: > On 5 ???, 18:56, Ivan Illarionov wrote: > > > > > On 5 ???, 18:19, "victor.hera... at gmail.com" > > wrote: > > > > On Jun 5, 3:49 pm, Ivan Illarionov wrote: > > > > > On 5 ???, 01:57, "victor.hera... at gmail.com" > > > > wrote: > > > > > > Hi Everyone, > > > > > > i have another question. What if i wanted to make n tuples, each with > > > > > a list of coordinates. For example : > > > > > > coords = list() > > > > > for h in xrange(1,11,1): > > > > > for i in xrange(1, 5, 1) : > > > > > for j in xrange(1, 5, 1) : > > > > > for k in xrange(1,2,1) : > > > > > coords.append((i,j,k)) > > > > > lista+str(h)= tuple coords > > > > > print tuple(coords) > > > > > > so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do > > > > > it the way i show you above but it is not working properly. I wish you > > > > > could help me with that. Thanks again, > > > > >>> from itertools import repeat, izip > > > > >>> coords = tuple((i,j,k) for i in xrange(1,5) for j in xrange(1,5) for k in xrange(1,2)) > > > > >>> locals().update(("tuple%s" % i, coord) for i, coord in izip(xrange(1,11), repeat(coords))) > > > > >>> tuple1 > > > > > ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (2, 1, 1), (2, 2, 1), (2, > > > > 3, 1), (2 > > > > , 4, 1), (3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1), (4, 1, 1), (4, 2, > > > > 1), (4, 3 > > > > , 1), (4, 4, 1)) > > > > > Does this help? > > > > > But I don't understand why you need this? > > > > > Ivan > > > > Hi, > > > > What i need is, for example: > > > > tuple 1=((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)) > > > > tuple 2=((2, 1, 1), (2, 2, 1), (2, 3, 1), (2, 4, 1)) > > > > tuple 3=((3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1)) > > > > and so on. Please help me and sorry for not taking the time to post my > > > questions properly. > > > > Victor > > > Or even so: > > > locals().update(("tuple_%s" % i, tuple((i,j,k) for j in range(1,5) for > > k in range(1,2))) for i in range(1,5)) > > > Ivan > > Tried to make it readable: > > def iter_coords(i): > for j in xrange(1,5): > for k in xrange(1,2): > yield i, j, k > > def iter_vars(): > for i in xrange(1, 5): > yield "tuple_%s" % i, tuple(iter_coords(i)) > > locals().update(dict(iter_vars())) locals().update() works by accident here because it's in global scope; it doesn't work within a function. Use a proper data structure, like a dict or a list, and access each tuple list as 'tuples[n]' instead of 'tuple_n'. George From ctgaff at runbox.com Tue Jun 24 04:36:51 2008 From: ctgaff at runbox.com (Corey G.) Date: Tue, 24 Jun 2008 03:36:51 -0500 Subject: Python 3000 vs Perl 6 In-Reply-To: References: Message-ID: What I meant, in terms of dealing with accurate or non-accurate rumors is with speed, yes. There are plenty of comparisons where Perl is 4-15x faster then Python for 'some' operations regarding regular expressions, etc. For me personally, this means absolutely nothing because if I spend 50x more time comprehending spaghetti, obfuscated Perl code it's irrelevant. The main concern (my concern) is whether or not Perl 6 is more like Java with pre-compiled byte code (did I say that right) and whether or not individuals without the ability to see past the surface will begin to migrate towards Perl 6 for its seemingly faster capabilities. With Perl 6 taking 10+ years, if/when it actually gets released, will it be technically ahead of Python 3000? Is Parrot worth the extra wait the Perl 6 project is enduring? My own answer would be a resounding no, but I am curious as to what others think. :) -Thanks! On Jun 24, 2008, at 2:52 AM, cokofreedom at gmail.com wrote: > On Jun 24, 8:20 am, "Corey G." wrote: >> If Perl 6 ever does get on its feet and get released, how does it >> compare to Python 3000? Is Perl 6 more like Java now with Parrot? I >> just want to make sure that Python is staying competitive. >> >> If this is the wrong mailing list, just let me know. Thanks! > > Do you mean in terms of speed (parrot is a JIT?). I believe Python 3k > will (when out of beta) will have a speed similar to what it has > currently in 2.5, possibly with speed ups in some locations. But > competitive-wise I think the point is Python 3k tries to remove warts > from the Python Language to make it even more friendly to readers and > writers alike. In that way it should/will stay competitive. > > However towards overall usage, the general advice is to stay with the > 2.x series for now, trying to ensure your code style is moving towards > the Py3k style, and then make the jump to the 3.x series when it is > finialised. > > Another point, is Perl 6 ever going to get released :P > -- > http://mail.python.org/mailman/listinfo/python-list > From maric at aristote.info Mon Jun 16 13:07:28 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 16 Jun 2008 19:07:28 +0200 Subject: 'string'.strip(chars)-like function that removes from the middle? In-Reply-To: <48569B9E.6030206@admailinc.com> References: <48569B9E.6030206@admailinc.com> Message-ID: <200806161907.29636.maric@aristote.info> Le Monday 16 June 2008 18:58:06 Ethan Furman, vous avez ?crit?: > The strip() method of strings works from both ends towards the middle. > Is there a simple, built-in way to remove several characters from a > string no matter their location? (besides .replace() ;) > > For example: > .strip --> 'www.example.com'.strip('cmowz.') > 'example' > .??? --> --- 'www.example.com'.strip('cmowz.') > 'exaple' As Larry Bates said the python way is to use str.join, but I'd do it with a genexp for memory saving, and a set to get O(1) test of presence. to_remove = set('chars') ''.join(e for in string_ if e not in to_remove) Note that this one will hardly be defeated by other idioms in python (even regexp). Using a genexp is free and a good practice, using a set, as it introduce one more step, can be considered as premature optimisation and the one liner : ''.join(e for in string_ if e not in 'chars') may be preferred. -- _____________ Maric Michaud From pavlovevidence at gmail.com Wed Jun 4 07:11:26 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 4 Jun 2008 04:11:26 -0700 (PDT) Subject: Best way to modify code without breaking stuff. References: Message-ID: <71db4569-85df-43c9-89ff-1f047d8f2359@c58g2000hsc.googlegroups.com> On Jun 4, 3:44 am, Ivan Illarionov wrote: > On Wed, 04 Jun 2008 00:25:19 -0700, Jesse Aldridge wrote: > > I've got a module that I use regularly. I want to make some extensive > > changes to this module but I want all of the programs that depend on the > > module to keep working while I'm making my changes. What's the best way > > to accomplish this? > > Version control system. > > http://en.wikipedia.org/wiki/List_of_revision_control_software > > Make your module a versioned repository. > Make your changes in different place, then commit them. That doesn't seem like a good solution for the OP's particular problem. To do it in a "different place", as you say, he'd have to check out a new working copy, which might be a bit of overkill depending on the size of the project. It could also be problematic to have separate working copies; there could be programs outside the project that are configured to use a certain location, for instance. One thing you could do with some version control systems is to switch the particular version for the module in question between different branches depending on whether you're using the tools or changing the model. (Subversion can do this, but I'm not sure if it's for individual files or only directories.) Carl Banks From omer at no-log.org Mon Jun 30 11:16:47 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Mon, 30 Jun 2008 17:16:47 +0200 Subject: regex help In-Reply-To: <12af01c8dac1$1dc54530$a501a8c0@office.ipglobal.net> References: <12af01c8dac1$1dc54530$a501a8c0@office.ipglobal.net> Message-ID: <200806301716.47247.omer@no-log.org> Le Monday 30 June 2008 16:53:54 Support Desk, vous avez ?crit?: > Hello, > I am working on a web-app, that querys long distance numbers from a > database of call logs. I am trying to put together a regex that matches any > number that does not start with the following. Basically any number that > does'nt start with: > > > > 281 > > 713 > > 832 > > > > or > > > > 1281 > > 1713 > > 1832 > > > > > > is long distance any, help would be appreciated. sounds like str.startswith() is enough for your needs: if not number.startswith(('281', '713', '832', ...)) : ... -- C?dric Lucantis From kyosohma at gmail.com Tue Jun 10 20:50:52 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 10 Jun 2008 17:50:52 -0700 (PDT) Subject: Instructions on how to build py2exe 0.6.8 (or an installer would be nice, too!) References: <5426baaf-2ba6-41b0-a0ec-1070429b5195@x35g2000hsb.googlegroups.com> <7f3360e4-8a12-45cf-99fa-6172cb5a1aaa@a1g2000hsb.googlegroups.com> <5cde3ec8-2e8d-4c1e-bee9-1ee51f649cd8@d45g2000hsc.googlegroups.com> <9af1adfb-5bce-48e8-b17f-4d838f788b90@d77g2000hsb.googlegroups.com> Message-ID: <16697d7e-4888-4733-b40e-b935f9a44966@x35g2000hsb.googlegroups.com> Evan, > > > I finally figured out how to check out the code. I'm at work now, > > where I only have VS2008 installed so I'll have to wait until I get > > home this evening to try compiling it. I'll let you know if I have any > > luck. > > > --------------------- > > Mike > > > Python Extension Building Network: ? ? > > Thanks, Mike. Hopefully you'll have more luck than I've had : ) > > Evan I got it compiled. They are up on my website: http://pythonlibrary.org/python_modules.htm I tested it on one of my simple programs and it ran. I used the 2.5 version for that test. However, it should be noted that I haven't been able to get the tests from CVS to run. The Traceback doesn't appear to be py2exe related though. I'll post the issue to their group and see if they have any idea why that would be. In the meantime, feel free to give it a try. At worst you'll have to delete the compiled binary and the py2exe folder. Mike From larry.bates at websafe.com` Tue Jun 10 21:51:03 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 10 Jun 2008 20:51:03 -0500 Subject: Dynamic HTML from Python Script In-Reply-To: <484f151c$0$5009$607ed4bc@cv.net> References: <484f151c$0$5009$607ed4bc@cv.net> Message-ID: asdf wrote: > I have a python script whose output i want to dynamically display > on a webpage which will be hosted using Apache. How do I do that? > > > thanks Take a look at Django. It may be overkill for this first project but any time you spend learning it should be paid back in future projects. -Larry From ivan.illarionov at gmail.com Wed Jun 4 10:13:55 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 4 Jun 2008 14:13:55 +0000 (UTC) Subject: Trying to extend Python with C: undefined reference to `Py_BuildValue' References: <045458d3-771b-459d-b5ef-21d8f3c08659@2g2000hsn.googlegroups.com> Message-ID: On Wed, 04 Jun 2008 05:57:20 -0700, spectrumdt wrote: > Hello. > > I am trying to extend Python with some C code. I made a trivial > "Hello World" program in C that I am trying to wrap in "boilerplate" for > inclusion in a Python program. But I can't compile the C code. The C > compiler cannot find the required function `Py_BuildValue'. > > My C code looks like this: > > > > #include "/usr/include/python2.5/Python.h" > > /* Python wrapper for 'main'. */ > static PyObject* mpi_main() { > int res = main(); > PyObject* retval = (PyObject*)Py_BuildValue("i",res); > } > > /* Main. A 'Hello World' function. */ int main() { > printf ("Hello, World. I am a C function.\n"); > } > > > > And my error message looks like this: > > > > [ore at localhost Opgave03]$ gcc ctest.c /tmp/ccH46bs8.o: In function > `mpi_main': ctest.c:(.text+0x1d): undefined reference to > `Py_BuildValue' collect2: ld returned 1 exit status > [ore at localhost Opgave03]$ > > > > I searched the newsgroup and found this thread: > > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/ c6d70e02a6bc9528/87b836f369bd0042?lnk=gst&q=undefined+reference+to+% 60Py_BuildValue%27#87b836f369bd0042 > > It recommended that I add the option "-Wl,--export-dynamic" when > calling gcc. That makes no difference. The thread also has some more > stuff that I don't quite understand. > > Can anyone help? I am including Python.h, so why does it not find > Py_BuildValue? > > Thanks in advance. Hi! Your C code contains too many errors. I'm lazy to comment them all. Here's my take on the trivial "Hello world" in Python C API: 1. create 'hello.c' file with the following content: #include PyObject* hello(PyObject* self) { printf("Hello world!\n"); Py_RETURN_NONE; } static PyMethodDef functions[] = { {"hello", (PyCFunction)hello, METH_NOARGS}, {NULL, NULL, 0, NULL}, }; DL_EXPORT(void) init_hello(void) { Py_InitModule("_hello", functions); } 2. create 'buildme.py' file with this content: import os import sys from distutils.core import Extension, setup os.chdir(os.path.dirname(os.path.abspath(__file__))) sys.argv = [sys.argv[0], 'build_ext', '-i'] setup(ext_modules = [Extension('_hello', ["hello.c"])]) 3. run "python buildme.py" That's all. >>> from _hello import hello >>> hello() Hello world! -- Ivan From marcoberi at gmail.com Mon Jun 23 12:23:49 2008 From: marcoberi at gmail.com (Marcob) Date: Mon, 23 Jun 2008 09:23:49 -0700 (PDT) Subject: Find class attributes creation order References: Message-ID: On 23 Giu, 18:08, C?dric Lucantis wrote: > Le Monday 23 June 2008 17:53:07 Marcob, vous avez ?crit?: > > > Let's see these simple classes: > > > ? ? class base_foo() > > ? ? ? ? ?pass > > > ? ? class foo(base_foo): > > ? ? ? ? ?a=1 > > ? ? ? ? ?b={} > > ? ? ? ? ?c="zz" > > > I would like to find class foo attributes creation order. > > Using __metaclass__ is not of help because special method __new__ > > receive attrs as a dictionary and so the order isn't preserved. Any > > other idea? > > I don't really understand what you want, but __new__ may accept any kind of > attributes, this is your choice. You can use named params or a vararg list > (which will preserve params order). Ok, I'll try to make myself clearer. > But in your example you're only using class attributes, so __new__ is not > involved and they are just created once for all in the order you write them: > a, b, c. Yes, this is true but if another piece of code define class foo (and consequently a, b, c) and I would like to find how many class attributes are defined and their order, how can I do this? It's easy to find how many attributes there are: using __dict__ or dir() or whatever. But to find their order isn't so easy. Besides that I can do whatever I want with class base_foo but I can't touch class foo. Ciao. Marco. From arnodel at googlemail.com Mon Jun 2 00:36:02 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 02 Jun 2008 05:36:02 +0100 Subject: php vs python References: Message-ID: "Joel Koltner" writes: > There's potentially a large difference between a "good" speaker of > English/German/etc. vs. "eloquent." > > I'd tend to agree with Jerry that if you can write "good" code in > one language, you can in pretty much any other as well... but that > doesn't imply you're necessarily "eloquent" in any languages. :-) > Eloquence is nice, but eradicating "bad" code in this world is about > a million times more important than attempting to move people from > "good" code to "eloquent" code. This is wrong, because if you know well one language only, you tend to think that the principles that underpin it are universal. So you will try to shoehorn these principles into any other language you use. It's only when you have become reasonably proficient in a number of conceptually different languages that you start to build a picture of what "a programming language" is. I understand that there are some sane practices that are useful to know when programming in any language, but it is wrong to say that the skill of programming can be reduced to that, the rest being syntax. There is (hopefully!) a design behind the syntax, you have to understand it to use the language well. You may be great at building Turing machines. That doesn't make you a master of crafting lambda-expressions. > To be Pythonic here, "eloquent" code would perhaps often have clear, > clean list comprehensions used when "good" code would use a "for" > loop but still be easy to follow as well and perfectly acceptable in > the vast majority of cases. I find that eloquent Python speakers often tend to write a for loop when mere good ones will try to stick a list comprehension in! Regards -- Arnaud From reckoner at gmail.com Mon Jun 9 18:30:32 2008 From: reckoner at gmail.com (Reckoner) Date: Mon, 9 Jun 2008 15:30:32 -0700 (PDT) Subject: access variables from one Python session to another on the same machine? Message-ID: <6ea6b084-3897-43f9-b8e0-dff52b47f1a0@w1g2000prd.googlegroups.com> Suppose I have two different command windows going on the same machine, each running their own Python interpreters. Is it possible to access the variables in one of the interpreter- sessions from the other? It turns out I have limited control over one of the sessions (i.e. cannot control all the code that is run from there), but complete control over the other. I get the feeling this has been asked before, but I'm not sure how to pose the question in such a way that it would show up on a search. It's confusing. Thanks. From dullrich at sprynet.com Mon Jun 30 16:09:45 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Mon, 30 Jun 2008 15:09:45 -0500 Subject: Do I need "self" and "other"? References: <68566b52-100d-40ee-a0c6-bde20df9ecd4@a70g2000hsh.googlegroups.com> Message-ID: In article <68566b52-100d-40ee-a0c6-bde20df9ecd4 at a70g2000hsh.googlegroups.com>, Kurda Yon wrote: > Hi, > > I found one example which defines the addition of two vectors as a > method of a class. It looks like that: > > class Vector: > def __add__(self, other): > data = [] > for j in range(len(self.data)): > data.append(self.data[j] + other.data[j]) > return Vector(data) > > In this example one uses "self" and "other". Does one really need to > use this words? And, if yes, why? I have replaced "self" by "x" and > "other" by "y" and everything looks OK. Is it really OK or I can have > some problem in some cases? What everyone else has said: yes and no. Having said that, it seems to me like this is exactly the sort of situation where 'x' and 'y' make a lot of sense - self means that this is the object on which the method was invoked, and here that seems irrelevant: If you want to calculate x + y you use x.data and y.data... Otoh, I once saw a library (someone's Python arbitrary-precision reals package) where he used x and y, and sure enough I was confused. Otooh, I was't confused by it for long, and I quickly decided that it actually made _that_ code look like it made more sense. > Thank you! -- David C. Ullrich From george.sakkis at gmail.com Tue Jun 3 22:02:03 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 3 Jun 2008 19:02:03 -0700 (PDT) Subject: ANN: equivalence 0.2 Message-ID: <2de2caf8-7c98-41da-afa8-1332143ebaff@j22g2000hsf.googlegroups.com> Equivalence v0.2 has been released. Also the project is now hosted at http://code.google.com/p/pyquivalence/ (the name 'equivalence' was already taken but the module is still called equivalence). Changes ======= - The internals were largely rewritten, but the API remained effectively intact. - A new `equivalence(**kwds)` factory function is now the preferred way to create an equivalence. Two kwds supported for now, `key` and `bidirectional`. - Now uses the union-find algorithm on disjoint-set forests; improves the linear worst-case time to practically constant amortized time for the basic operations. - Modular redesign; the original Equivalence class has been broken down into subclasses, each trading off more features with extra overhead: - The base Equivalence class is a vanilla disjoint-sets forest; it doesn't support keys and partition() is slow, but the rest operations are faster. - KeyEquivalence adds implicit (key-based) equivalence. - BidirectionalEquivalence provides fast partition() at the cost of higher memory overhead and slowing down slightly the rest operations. - KeyBidirectionalEquivalence combines the two previous. - Added more tests and updated docs. About ===== *equivalence* is a Python module for building equivalence relations: partitionings of objects into sets that maintain the equivalence relation properties (reflexivity, symmetry, transitivity). Two objects are considered equivalent either explicitly, after being merged, or implicitly, through a key function. From cwitts at gmail.com Sat Jun 21 16:52:48 2008 From: cwitts at gmail.com (Chris) Date: Sat, 21 Jun 2008 13:52:48 -0700 (PDT) Subject: Getting column names from a cursor using ODBC module? References: Message-ID: <4fe11953-15a9-4363-819f-b54b4f05941c@y38g2000hsy.googlegroups.com> On Jun 21, 3:58?pm, dana... at yahoo.com wrote: > Is there any way to retrieve column names from a cursor using the ODBC > module? Or must I, in advance, create a dictionary of column position > and column names for a particular table before I can access column > values by column names? I'd prefer sticking with the ODBC module for > now because it comes standard in Python. > > I'm using Python 2.4 at the moment. > > Thanks. You should be able to do column_names = [d[0] for d in cursor.description] From punitha.d24 at gmail.com Sun Jun 8 03:49:47 2008 From: punitha.d24 at gmail.com (punitha.d24 at gmail.com) Date: Sun, 8 Jun 2008 00:49:47 -0700 (PDT) Subject: online money Message-ID: online money online business money is very important http://worldlangs.blogspot.com/ From p.f.moore at gmail.com Thu Jun 19 04:43:25 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Thu, 19 Jun 2008 09:43:25 +0100 Subject: [Python-3000] RELEASED Python 2.6b1 and 3.0b1 In-Reply-To: <1972109D-735D-4485-82F4-9BC8F2984967@python.org> References: <1972109D-735D-4485-82F4-9BC8F2984967@python.org> Message-ID: <79990c6b0806190143n58e51a22ubafd3fe343291dfb@mail.gmail.com> On 19/06/2008, Barry Warsaw wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On behalf of the Python development team and the Python community, I am > happy to announce the first beta releases of Python 2.6 and Python 3.0. Any ETA for Windows builds? The web pages still point to the alphas. (I'd like to see the Windows builds more closely integrated with the releases now we're in beta stage...) Paul. From mikalzet_togli at libero.it Sun Jun 1 08:15:31 2008 From: mikalzet_togli at libero.it (Taekyon) Date: Sun, 01 Jun 2008 14:15:31 +0200 Subject: Merging ordered lists References: <517cd708-4969-4e0f-a4a4-2e7bb91aa7f6@d19g2000prm.googlegroups.com> Message-ID: etal wrote: > Speed actually isn't a problem yet; it might matter some day, but for > now it's just an issue of conceptual aesthetics. Any suggestions? Looks as if set does it for you. -- Taekyon From rw.segaar at xs4all.nl Mon Jun 16 15:10:58 2008 From: rw.segaar at xs4all.nl (Robert) Date: Mon, 16 Jun 2008 21:10:58 +0200 Subject: py2exe 0.6.8 released References: Message-ID: <4856bac5$0$12058$e4fe514c@dreader20.news.xs4all.nl> Being new on on Python (but otherwise experienced programmer this message triggered me to do the install. It looks like a nice way to do a comprehensive check of your system. When running one of the py2exe samples, located in C:\Python25\Lib\site-packages\py2exe\samples\singlefile\gui I got the following error when running the resulting executable: C:\Python25\Lib\site-packages\py2exe\samples\singlefile\gui\dist\test_wx.exe\zipextimporter.py:82: DeprecationWarning: The wxPython compatibility package is no longer automatically generated or actively maintained. Please switch to the wx package as soon as possible. Traceback (most recent call last): File "test_wx.py", line 1, in File "zipextimporter.pyo", line 82, in load_module File "wxPython\__init__.pyo", line 15, in File "zipextimporter.pyo", line 82, in load_module File "wxPython\_wx.pyo", line 8, in File "zipextimporter.pyo", line 82, in load_module File "wxPython\_misc.pyo", line 456, in AttributeError: 'module' object has no attribute 'DateTime_GetNumberOfDaysinYear' I know of course the real error must be on the wx part of it all. I only have: - a python 2.5.2 install(msi) - a "wxPython2.8-win32-unicode-2.8.7.1-py25.exe" install - a "py2exe-0.6.8.win32-py2.5.exe"install. I have deleted C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wxPython because there indications that this is not needed, but other problems emerged. Any clues how to proceed next? Robert From johnjsal at gmailNOSPAM.com Thu Jun 5 23:42:07 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Thu, 05 Jun 2008 23:42:07 -0400 Subject: Do this as a list comprehension? Message-ID: <4848b213$0$25711$607ed4bc@cv.net> Is it possible to write a list comprehension for this so as to produce a list of two-item tuples? base_scores = range(8, 19) score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] print zip(base_scores, score_costs) I can't think of how the structure of the list comprehension would work in this case, because it seems to require iteration over two separate sequences to produce each item in the tuple. zip seems to work fine anyway, but my immediate instinct was to try a list comprehension (until I couldn't figure out how!). And I wasn't sure if list comps were capable of doing everything a zip could do. Thanks. From rileyrgdev at gmail.com Wed Jun 25 09:24:56 2008 From: rileyrgdev at gmail.com (Richard G Riley) Date: Wed, 25 Jun 2008 15:24:56 +0200 Subject: IDE on the level of Eclipse or DEVc++? References: <563a8619-df8b-4de2-b9af-9ae70f6cedb4@t54g2000hsg.googlegroups.com> <486214ae$0$9742$426a34cc@news.free.fr> <87ej6lq02c.fsf@benfinney.id.au> Message-ID: Jorge Godoy writes: > cokofreedom at gmail.com wrote: > >> How is emacs on a windows platform? > > Except for Windows using _emacs instead of .emacs, it was the same I had on Linux, last time I tried it... :-) > > There are packages for Windows that have a lot of things pre-packaged > to make it feel more like a Windows application, including keyboard > shortcuts. More specifically : cua-mode From larry.bates at websafe.com` Wed Jun 11 09:49:24 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 11 Jun 2008 08:49:24 -0500 Subject: Producer-consumer threading problem In-Reply-To: References: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> Message-ID: George Sakkis wrote: > On Jun 10, 11:47 pm, Larry Bates wrote: >> I had a little trouble understanding what exact problem it is that you are >> trying to solve but I'm pretty sure that you can do it with one of two methods: > > Ok, let me try again with a different example: I want to do what can > be easily done with 2.5 Queues using Queue.task_done()/Queue.join() > (see example at http://docs.python.org/lib/QueueObjects.html), but > instead of having to first put all items and then wait until all are > done, get each item as soon as it is done. > >> 1) Write the producer as a generator using yield method that yields a result >> every time it is called (something like os.walk does). I guess you could yield >> None if there wasn't anything to consume to prevent blocking. > > Actually the way items are generated is not part of the problem; it > can be abstracted away as an arbitrary iterable input. As with all > iterables, "there are no more items" is communicated simply by a > StopIteration. > >> 2) Usw somethink like Twisted insted that uses callbacks instead to handle >> multiple asynchronous calls to produce. You could have callbacks that don't do >> anything if there is nothing to consume (sort of null objects I guess). > > Twisted is interesting and very powerful but requires a different way > of thinking about the problem and designing a solution. More to the > point, callbacks often provide a less flexible and simple API than an > iterator that yields results (consumed items). For example, say that > you want to store the results to a dictionary. Using callbacks, you > would have to explicitly synchronize each access to the dictionary > since they may fire independently. OTOH an iterator by definition > yields items sequentially, so the client doesn't have to bother with > synchronization. Note that with "client" I mean the user of an API/ > framework/library; the implementation of the library itself may of > course use callbacks under the hood (e.g. to put incoming results to a > Queue) but expose the API as a simple iterator. > > George If you use a queue and the producer/collector are running in different threads you don't have to wait for "to first put all items and then wait until all are done". Producer can push items on the queue and while the collector asynchronously pops them off. I'm virtually certain that I read on this forum that dictionary access is atomic if that helps. -Larry From mdw at distorted.org.uk Tue Jun 17 11:25:02 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Tue, 17 Jun 2008 15:25:02 +0000 (UTC) Subject: 2Q's: How to autocreate instance of class;How to check for membership in a class References: <48571086$0$5010$607ed4bc@cv.net> Message-ID: asdf wrote: (Presumably nothing to do with the Common Lisp system-definition utility.) > So for example if I know that var1=jsmith. Can I somehow do > var1=User(). Something like this might work. class User (object): def __init__(me, name): me.name = name class Users (object): def __getattr__(me, name): try: return object.__getattr__(me, name) except AttributeError: u = me.__dict__[name] = User(name) return u >>> users = Users() >>> alice = users.alice >>> alice.name 'alice' >>> alice is users.alice True Not very nice, though, and not particularly good at defending against typos. > My second question is how can I check if object is a member of a class. > so let's say I create a=User(), b=User()... The built-in isinstance function seems an obvious choice. -- [mdw] From dickinsm at gmail.com Tue Jun 24 04:38:53 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 24 Jun 2008 01:38:53 -0700 (PDT) Subject: binary representation of an integer References: <14e14b5e-ce39-414a-a450-7c81baaabc3a@79g2000hsk.googlegroups.com> Message-ID: On Jun 24, 9:03?am, eliben wrote: > What would be the quickest way to do this ? I think that for dec2bin > conversion, using hex() and then looping with a hex->bin lookup table > would be probably much faster than the general baseconvert from the > recipe. I suspect you're right, but it would be easy to find out: just code up the hex->bin method and use the timeit module to do some timings. Don't forget to strip the trailing 'L' from hex(n) if n is a long. If you're prepared to wait for Python 2.6, or work with the beta version, then the conversion is already there: Macintosh-3:trunk dickinsm$ ./python.exe Python 2.6b1+ (trunk:64489, Jun 23 2008, 21:10:40) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> bin(13) '0b1101' Interestingly, unlike hex and oct, bin doesn't add a trailing 'L' for longs: >>> bin(13L) '0b1101' I wonder whether this is a bug... Mark From http Wed Jun 4 07:21:46 2008 From: http (Paul Rubin) Date: 04 Jun 2008 04:21:46 -0700 Subject: Best way to modify code without breaking stuff. References: Message-ID: <7xod6htph1.fsf@ruckus.brouhaha.com> Jesse Aldridge writes: > I've got a module that I use regularly. I want to make some extensive > changes to this module but I want all of the programs that depend on > the module to keep working while I'm making my changes. What's the > best way to accomplish this? Do you mean you want to hot-patch a running program? The short answer is: don't. From python.leojay at gmail.com Fri Jun 13 03:02:48 2008 From: python.leojay at gmail.com (Leo Jay) Date: Fri, 13 Jun 2008 15:02:48 +0800 Subject: why can i still able to reproduce the SimpleHTTPServer bug which is said fixed 3 years ago? Message-ID: <4e307e0f0806130002u6795c55ejce02b71753df33ae@mail.gmail.com> http://bugs.python.org/issue1097597 in my python 2.5.2, i still find these code in SimpleHTTPServer.py, is that deliberate? ctype = self.guess_type(path) if ctype.startswith('text/'): mode = 'r' else: mode = 'rb' try: f = open(path, mode) except IOError: self.send_error(404, "File not found") return None self.send_response(200) self.send_header("Content-type", ctype) fs = os.fstat(f.fileno()) self.send_header("Content-Length", str(fs[6])) # <-- obviously, this is not the same with len(f.read()) in windows. -- Best Regards, Leo Jay From subhabrata.iisc at hotmail.com Fri Jun 27 03:51:53 2008 From: subhabrata.iisc at hotmail.com (subhabrata.iisc at hotmail.com) Date: Fri, 27 Jun 2008 00:51:53 -0700 (PDT) Subject: Question on List Message-ID: <7f03fa3f-c8fd-45a8-b4a5-d7c66982aa4a@q27g2000prf.googlegroups.com> Dear All, I am trying to write the following code: def try1(n): a1="God Godess Borother Sister Family" a2=a1.split() a3=raw_input("PRINT A WORD") a4=a1.find(a3) print a4 a5=[] if a4>0: a5=a2.index(a3) a6=a5+1 a7=a2[a6] print "The new word is" print a7 a8=a5.append(a7) print a5 elif a4<0: a11=a3 print "The word is not availiable in String" print a11 a6=a5.append(a11) print a5 else: print "Error" Now, my question is I like to see a5 or the empty list as appended with elements. Results I am getting is a5 giving single value like ['God'],['Godess']... but I like to see it as ['God','Godess'...] etc. Am I going wrong? Do I have to rethink it in some other way? If any one can kindly let me know. Best Regards, Subhabrata. From david at hlacik.eu Wed Jun 4 18:27:32 2008 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Thu, 5 Jun 2008 00:27:32 +0200 Subject: no module named py In-Reply-To: References: Message-ID: most important method inside news class is newsauth which takes username, password and will return 1 if ldap authentification was OK. actually inn will call method authenticate which will call self.newsauth and here comes the problem .. i ve got instead of call self.newsauth error no module named py : from authenticate : try: syslog('notice', "result %s" % self.newsauth('boss','bbbb')) except Exception, msg: syslog('notice', "error %s, %s, %s" % (type(msg),msg.args,msg)) On Thu, Jun 5, 2008 at 12:26 AM, David Hl??ik wrote: > Hello, what this beautifull mesage which is messing me whole day means : > > *python: error , ('No module named py',), No module named > py* > > as a result of class pdg.py which is called from nnrpd_auth.py. > > To be detailed ... news server inn is calling that when doing > autentification , it calls nnrpd_auth.py where instance of my class is > hooked into inn , when authentification begins it calls method > authenticate(arguments) from pdg. > > I will provide as many information as needed to solve this mistery, becouse > i really need to solve it. > Thanks! > > > #!/usr/bin/env python > > import ldap > from nnrpd import syslog > class news: > > server = 'ldap://dev01.net.hlacik.eu' > user_dn = 'cn=pdg,ou=Operators,o=Polarion' > user_pw = 'Pdg1' > > connectcodes = { 'READPOST':200, > 'READ':201, > 'AUTHNEEDED':480, > 'PERMDENIED':502 > } > > authcodes = { 'ALLOWED':281, > 'DENIED':502 > } > > def newsauth(self,match_username,match_password): > base_dn = 'ou=Users,o=Polarion' > filter = "(uid=" + match_username + ")" > attrs = ['userPassword'] > > try : > l = ldap.initialize(self.server) > l.bind_s(self.user_dn, self.user_pw) > raw_res = l.search_s( base_dn, ldap.SCOPE_SUBTREE, > filter, attrs ) > l.unbind() > except ldap.SERVER_DOWN: > print "Error, server down" > return 2 > except ldap.INVALID_CREDENTIALS: > print "Error, invalid credentials" > return 2 > except ldap.LDAPError, e: > print "Error, %s" % e > for results in raw_res: > (cn,search) = results > for password in search["userPassword"]: > if password == match_password: return 1 > > return 0 > > > def authenticate(self, attributes): > > # just for debugging purposes > syslog('notice', 'nnrpd_auth authenticate() invoked: > hostname %s, ipaddress > %s, interface %s, user %s' % (\ > attributes['hostname'], \ > attributes['ipaddress'], \ > attributes['interface'], \ > attributes['user'])) > > try: > syslog('notice', "result %s" % > self.newsauth('boss','bbbb')) > except Exception, msg: > syslog('notice', "error %s, %s, %s" % > (type(msg),msg.args,msg)) > # do username passworld authentication > #if self.newsauth(attributes['user'], > str(attributes['pass'])): > # syslog('notice', 'authentication by username > succeeded') > # return ( self.authcodes['ALLOWED'], 'No error' ) > #else: > # syslog('notice', 'authentication by username failed') > # return ( self.authcodes['DENIED'], 'Access Denied!') > > ------------------- > > nnrpd_auth_py : > > # > # Sample authentication and authorization class. It defines all methods > known > # to nnrpd. > # > # Import functions exposed by nnrpd. This import must succeed, or nothing > # will work! > from nnrpd import * > from pdg import * > > myauth = news() > > # ...and try to hook up on nnrpd. This would make auth object methods > visible > # to nnrpd. > try: > set_auth_hook(myauth) > syslog('notice', "authentication module successfully hooked into > nnrpd") > except Exception, errmsg: > syslog('error', "Cannot obtain nnrpd hook for authentication method: > %s" % errmsg[0]) -------------- next part -------------- An HTML attachment was scrubbed... URL: From matthieu.brucher at gmail.com Thu Jun 5 17:26:42 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Thu, 5 Jun 2008 23:26:42 +0200 Subject: How to make py2.5 distutil to use VC2005? In-Reply-To: References: Message-ID: 2008/6/4 ?? : > Howdy, > This problem have puzzled me for a long time. I usually use > python2.5 in Windows, while VC2005 is installed. > However python25.lib is compiled by VC2003. When I use disutil to > build some C extensions, it complaints that > there is no VC2003. > Well, IMO, the format of binary files generated by VC2003 and > VC2005 is compatible in most cases. What > should I do to workaround this error? I mean, disable distutil > complaints and use VC2005 to build C extensions. > I have google-ed some discussion related on this topic. It seems that > it's real possible! > Hi, I have the same issue that you have. If you only want to create some extensions to optimize some pieces of your code, try to build them with SCons or cmake. It will work provided you don't use usual C structures (FILE, ...) Matthieu -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -------------- next part -------------- An HTML attachment was scrubbed... URL: From apardon at forel.vub.ac.be Mon Jun 2 06:37:35 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 2 Jun 2008 10:37:35 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> Message-ID: On 2008-06-02, Duncan Booth wrote: > Antoon Pardon wrote: > >> If you really need it, you can do data hiding in python. It just >> requires a bit more work. > >> --- $ python >> Python 2.5.2 (r252:60911, Apr 17 2008, 13:15:05) >> [GCC 4.2.3 (Debian 4.2.3-3)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> From Hide import Foo >>>>> var = Foo() >>>>> var.GetX() >> 0 >>>>> var.SetX(5) >>>>> var.GetX() >> 5 >>>>> var.x >> Traceback (most recent call last): >> File "", line 1, in >> AttributeError: 'Foo' object has no attribute 'x' >>>>> var.hidden.x >> Traceback (most recent call last): >> File "", line 1, in >> AttributeError: 'Foo' object has no attribute 'hidden' >> > > That sort of hiding isn't any more secure than the 'hiding' you get in C++. So? >>>> var.GetX.func_closure[0].cell_contents.x > 5 > > All you've done is force the user who wants to bypass it to use a longer > expression, and if that's your criterion for 'hiding' then just use two > leading underscores. That you can find a lock pick to get at an object doesn't contradict that the object is locked away. I think the intention of not having these variables accesable to the application programmer is much stronger expressed than with two leading underscores. Even if the current implementation of the language makes it relatively easy to get at the information if you really want to. -- Antoon Pardon From nicola.musatti at gmail.com Tue Jun 3 11:08:56 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Tue, 3 Jun 2008 08:08:56 -0700 (PDT) Subject: Code correctness, and testing strategies References: Message-ID: On Jun 3, 12:35 am, ja... at cd.chalmers.se (Jacob Hallen) wrote: > In article , > > David wrote: [...] > >That's why you have human testing & QA. Unit tests can help, but they > >are a poor substitute. If the customer is happy with the first > >version, you can improve it, fix bugs, and add more unit tests later. > > The most important aspect of usnit testing is actually that it makes the code testable. > This may sound lik an oxymoron but it is actually a really important property. Testable > code has to have a level of modularity as well as simplicity and clarity in its > interfaces that you will not achieve in code that lacks automated unit tests. I don't agree. To me the most important aspect of unit testing is that it is automated. That is, the time you spend writing new tests you reap each time you run your test suite. The fact that writing automated tests has a beneficial effect on the modularity of your code is a pleasant though hard to measure side effect. Automation should also be the most convincing argument for the OP. The most evident liability of the approach he described is the need to re- instrument his code all over again each time. Writing an equivalent set of automated tests is likely to take him more, but the time taken to write each test is time he doesn't need to spend anymore. [...] > Another aspect that you are raising is the use of human testing and QA. I agree that > these are important, but every bug they discover is a failure of the developers and > their tests. Our testers can sail through a testbed in 30 minutes if there are no bugs. > Every single bug adds 30-60 minutes of testers time in order to pinpoint the bug > and supply the developers with enough information to locate and fix it. Add some > 10 minutes to testing time on the next testbed to verify that the bug is actually > fixed. In my end of the world, tester time is not cheaper than developer time. It > is also a scarcer resource than developer time. Moreover, hand performed testing takes the same amount of time each time it is performed and doesn't enjoy the incremental aspect of automated testing. Cheers, Nicola Musatti From george.sakkis at gmail.com Thu Jun 12 15:14:50 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 12 Jun 2008 12:14:50 -0700 (PDT) Subject: Simple and safe evaluator References: <80b23a5a-8613-4232-8954-7f7e4181322e@k37g2000hsf.googlegroups.com> Message-ID: <63a81194-182f-4d31-b149-6249fc3443a0@25g2000hsx.googlegroups.com> On Jun 12, 1:51 pm, bvdp wrote: > Matimus wrote: > > On Jun 11, 9:16 pm, George Sakkis wrote: > >> On Jun 11, 8:15 pm, bvdp wrote: > > >>> Matimus wrote: > >>>> The solution I posted should work and is safe. It may not seem very > >>>> readable, but it is using Pythons internal parser to parse the passed > >>>> in string into an abstract symbol tree (rather than code). Normally > >>>> Python would just use the ast internally to create code. Instead I've > >>>> written the code to do that. By avoiding anything but simple operators > >>>> and literals it is guaranteed safe. > >>> Just wondering ... how safe would: > >>> eval(s, {"__builtins__":None}, {} ) > >>> be? From my testing it seems that it parses out numbers properly (int > >>> and float) and does simple math like +, -, **, etc. It doesn't do > >>> functions like int(), sin(), etc ... but that is fine for my puposes. > >>> Just playing a bit, it seems to give the same results as your code using > >>> ast does. I may be missing something! > >> Probably you do; within a couple of minutes I came up with this: > > >>>>> s = """ > >> ... (t for t in 42 .__class__.__base__.__subclasses__() > >> ... if t.__name__ == 'file').next()('/etc/passwd') > >> ... """>>> eval(s, {"__builtins__":None}, {} ) > > >> Traceback (most recent call last): > >> File "", line 1, in > >> File "", line 3, in > >> IOError: file() constructor not accessible in restricted mode > > >> Not an exploit yet but I wouldn't be surprised if there is one. Unless > >> you fully trust your users, an ast-based approach is your best bet. > > >> George > > > You can get access to any new-style class that has been loaded. This > > exploit works on my machine (Windows XP). > > > [code] > > # This assumes that ctypes was loaded, but keep in mind any classes > > # that have been loaded are potentially accessible. > > > import ctypes > > > s = """ > > ( > > t for t in 42 .__class__.__base__.__subclasses__() > > if t.__name__ == 'LibraryLoader' > > ).next()( > > ( > > t for t in 42 .__class__.__base__.__subclasses__() > > if t.__name__ == 'CDLL' > > ).next() > > ).msvcrt.system('dir') # replace 'dir' with something nasty > > """ > > > eval(s, {"__builtins__":None}, {}) > > [/code] > > > Matt > > Yes, this is probably a good point. But, I don't see this as an exploit > in my program. Again, I could be wrong ... certainly not the first time > that has happened :) > > In my case, the only way a user can use eval() is via my own parsing > which restricts this to a limited usage. So, the code setting up the > eval() exploit has to be entered via the "safe" eval to start with. So, > IF the code you present can be installed from within my program's > scripts ... then yes there can be a problem. But for the life of me I > don't see how this is possible. In my program we're just looking at > single lines in a script and doing commands based on the text. > Setting/evaluating macros is one "command" and I just want a method to > do something like "Set X 25 * 2" and passing the "25 * 2" string to > python works. If the user creates a script with "Set X os.system('rm > *')" and I used a clean eval() then we could have a meltdown ... but if > we stick with the eval(s, {"__builtins__":None}, {}) I don't see how the > malicious script could do the class modifications you suggest. > > I suppose that someone could modify my program code and then cause my > eval() to fail (be unsafe). But, if we count on program modifications to > be doorways to exploits then we might as well just pull the plug. You probably missed the point in the posted examples. A malicious user doesn't need to modify your program code to have access to far more than you would hope, just devise an appropriate string s and pass it to your "safe" eval. Here's a simpler example to help you see the back doors that open. So you might think that eval(s, {"__builtins__":None}, {}) doesn't provide access to the `file` type. At first it looks so: >>> eval('file', {"__builtins__":None}, {}) NameError: name 'file' is not defined >>> eval('open', {"__builtins__":None}, {}) NameError: name 'open' is not defined "Ok, I am safe from users messing with files since they can't even access the file type" you reassure yourself. Then someone comes in and passes to your "safe" eval this string: >>> s = "(t for t in (42).__class__.__base__.__subclasses__() if t.__name__ == 'file').next()" >>> eval(s, {"__builtins__":None}, {}) Oops. Fortunately the file() constructor has apparently some extra logic that prevents it from being used in restricted mode, but that doesn't change the fact that file *is* available in restricted mode; you just can't spell it "file". 25 builtin types are currently available in restricted mode -- without any explicit import -- and this number has been increasing over the years: $ python2.3 -c 'print eval("(42).__class__.__base__.__subclasses__().__len__()", {"__builtins__":None}, {})' 13 $ python2.4 -c 'print eval("(42).__class__.__base__.__subclasses__().__len__()", {"__builtins__":None}, {})' 17 $ python2.5 -c 'print eval("(42).__class__.__base__.__subclasses__().__len__()", {"__builtins__":None}, {})' 25 $ python2.6a1 -c 'print eval("(42).__class__.__base__.__subclasses__().__len__()", {"__builtins__":None}, {})' 32 Regards, George From M8R-yfto6h at mailinator.com Fri Jun 6 23:36:26 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Fri, 6 Jun 2008 20:36:26 -0700 Subject: ctypes help References: Message-ID: "gianluca" wrote in message news:e1836378-5a00-43f5-b672-2e3a4191f960 at m73g2000hsh.googlegroups.com... > hy, > I've a huge problem with ctypes. I've compiled my C library and I'd > like use it in python with ctype. One function need to pass a pointer > to typed ( like this: typedef int value_type). In python I can access > to that funtion but arise an exception because python don't know my > value_type typedef. > > Please I need help, could anybody help me? > > Gianluca Let's see if I understand you correctly. You have a typedef, and a function that is passed a pointer to that typedef. Below is a short Windows DLL, compiled with "cl /LD example.c" typedef int value_type; __declspec(dllexport) void function(value_type* x) { *x *= 2; } And here is some python code to call it: >>> from ctypes import * >>> value_type = c_int # declares a type "value_type" >>> as a ctypes integer >>> value=value_type(5) # create an instance of value_type >>> function=cdll.example.function # look up the function and declare >>> return type and arguments >>> function.restype=None >>> function.argtypes=[POINTER(value_type)] >>> function(pointer(value)) # call the function with a pointer >>> to the instance >>> value c_long(10) Hope that helps. -Mark From gabriel.rossetti at arimaz.com Tue Jun 10 08:44:13 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Tue, 10 Jun 2008 14:44:13 +0200 Subject: h2py.py bug? Message-ID: <484E771D.1050404@arimaz.com> Hello everyone, I wanted to use the h2py.py script (Tools/scripts/h2py.py) and it didn't like char litterals : Skipping: PC_ERROR = ord() where my *.h file contained : #define PC_ERROR '0' I searched the web and found a post with the same error : http://mail.python.org/pipermail/python-list/2005-September/340608.html but it got no replies, I tried the fix and it works. I have the following questions: 1) Why did it not get any attention, is something wrong with it? 2) If nothing is wrong, did the fix not get applied because a bug report wasn't filed? 3) Isn't turning a char literal into the ordinal value not contrary to what a C programmer had in mind when he/she defined it? I mean if you define a char literal then in python you would have used a string value : #define PC_ERROR '0' would become : PC_ERROR = '0' in python, and if you intended to use the char type for an 8 bit numerical value you would have done : #define PC_ERROR 0x30 where 0x30 is the '0' ascii hex value, so shouldn'it the line in the diff (see the post) be : body = p_char.sub("'\\1'", body) instead of : body = p_char.sub("ord('\\1')", body) ? Thank you, Gabriel From mensanator at aol.com Mon Jun 2 18:15:48 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 2 Jun 2008 15:15:48 -0700 (PDT) Subject: Formatting Output References: <6e94b4dc-5920-447e-9971-96ec6a48b9ce@c58g2000hsc.googlegroups.com> <6ea2e85a-d00c-4228-98be-431205fceb7b@34g2000hsf.googlegroups.com> Message-ID: On Jun 2, 2:43?pm, Doug Morse wrote: > On Mon, 2 Jun 2008 12:42:12 -0700 (PDT), Mensanator wrote: > > ?On Jun 2, 3:38?am, Chris wrote: > > > On Jun 2, 9:34?am, "victor.hera... at gmail.com" > > > > wrote: > > > > Hi, > > > > > i am building a little script and i want to output a series of columns > > > > more or less like this: > > > > > 1 ?5 ?6 > > > > 2 ?2 ?8 > > > > 2 ?9 ?5 > > ... > > I have a related question: > > Does Python have (or can emulate) the formatted output capability found in > Perl? > > For example, all I have to do to get nicely formatted (i.e., aligned) output > is provide values for special STDOUT variables (i.e., STDOUT_TOP, STDOUT, > STDOUT_BOTTOM, etc.), exemplified by: > > ? format STDOUT_TOP = > ? ---------------------------------------------------------------------------?--- > ? ~ > ? . > > ? format STDOUT = > ? @<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<< > ? $res->{'full_name'}, ?$res->{'phone_1'}, ? ? ? ? $res->{'phone_1_type'} > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $res->{'address_1a'}, ? ? ? ? ? ? ? ?$res->{'address_2a'} > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $res->{'address_1b'}, ? ? ? ? ? ? ? ?$res->{'address_2b'} > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $res->{'address_1c'}, ? ? ? ? ? ? ? ?$res->{'address_2c'} > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $city_1 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?$city_2 > ? @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ > ? $res->{'email_1'}, ? ? ? ? ? ? ? ? ? $res->{'email_2'} > ? ---------------------------------------------------------------------------?--- > ? ~ > ? . > > Then, all I have to do is populate my $res object/hash as desired -- in this > example simple the results of a SQL query -- and lastly just call the "write" > function: > > ? write; > > and Perl will produce very nicely formatted results. ?This is useful not only > for producing human readable output, but also fixed-column-width data files, > etc. ?I'd love to learn the Pythonistic way of doing the same thing. > > Thanks! > Doug I didn't know you could do that in perl. Too bad I quit using it when I switched to Python. OTOH, I can do similar formatting directly in SQL. In Access, I create a query with this SQL: SELECT "------------------------------------------------------------" & Chr(10) & Format$(SampleEventCode,"!@@@@@@@@@@@@@@@@") & Format$ (SampleEventDescr,"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") & Chr(10) & Format$(EventSortOrder,"!@@@@@@@@@@@@@@@@") & Format$("From: " & Format$(DateFrom,"YYYY/MM/ DD"),"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") & Chr(10) & Format$(SampleEventReportLabel,"!@@@@@@@@@@@@@@@@") & Format$("To: " & Format$(DateTo,"YYYY/MM/ DD"),"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") AS Expr1 FROM tblSampleEvent; Then I simply call it from Python. (I could call with the SQL code instead of invoking the Access query, but the OBDC interface can't process this particular SQL statement, tries to put brackets around the format templates, so best render unto Access the things that belong to Access.) # code import dbi import odbc con = odbc.odbc("BPWR") cursor = con.cursor() cursor.execute(""" SELECT * FROM SQLFormatTest; """) results = cursor.fetchall() for i in results: for j in i: print j # /code which prints ------------------------------------------------------------ 2000Q1 First Quarter of 2000 2000100 From: 2000/01/01 1st-Qtr 2000 To: 2000/03/31 ------------------------------------------------------------ 2000Q2 Second Quarter of 2000 2000200 From: 2000/04/01 2nd-Qtr 2000 To: 2000/06/30 ------------------------------------------------------------ 2000Q3 Third Quarter of 2000 2000300 From: 2000/07/01 3rd-Qtr 2000 To: 2000/09/30 ------------------------------------------------------------ 2000Q4 Fourth Quarter of 2000 2000400 From: 2000/10/01 4th-Qtr 2000 To: 2000/12/31 ------------------------------------------------------------ 2000Q1LF Low Flow First Quarter of 2000 2000105 From: 2000/01/01 1st-Qtr 2000 To: 2000/03/31 ------------------------------------------------------------ 2000Q2LOD LOD borings Second Quarter of 2000 2000206 From: 2000/04/01 2nd-Qtr 2000 To: 2000/06/30 . . . From apardon at forel.vub.ac.be Thu Jun 5 07:30:44 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 5 Jun 2008 11:30:44 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> <873antn9il.fsf@benfinney.id.au> <6ammujF38poe2U2@mid.uni-berlin.de> <87y75llp5x.fsf@benfinney.id.au> <6an5a7F38poe2U3@mid.uni-berlin.de> <6aok3pF38pu6cU2@mid.uni-berlin.de> <6aq0dnF3892asU2@mid.uni-berlin.de> Message-ID: On 2008-06-05, Marc 'BlackJack' Rintsch wrote: > On Thu, 05 Jun 2008 08:21:41 +0000, Antoon Pardon wrote: > >> On 2008-06-04, Marc 'BlackJack' Rintsch wrote: >>> On Wed, 04 Jun 2008 09:34:58 +0000, Antoon Pardon wrote: >>> >>>> On 2008-06-04, Marc 'BlackJack' Rintsch wrote: >>>> >>>>>>> it makes sense to me to also test if they work as documented. >>>>>> >>>>>> If they affect the behaviour of some public component, that's where >>>>>> the documentation should be. >>>>> >>>>> As I said they are public themselves for someone. >>>> >>>> Isn't that contradictory: "Public for someone" I always >>>> thought "public" meant accessible to virtually anyone. >>>> Not to only someone. >>> >>> For the programmer who writes or uses the private API it isn't really >>> "private", he must document it or know how it works. >> >> How does that make it not private. Private has never meant "accessible >> to noone". And sure he must document it and know how it works. But that >> documentation can remain private, limited to the developers of the >> product. It doesn't have to be publicly documented. > > If the audience is the programmer(s) who implement the "private" API it > is not private but public. Even the "public" API is somewhat "private" to > a user of a program that uses that API. The public is not virtually > anyone here. Depends at which level you look in the system. I think there is a general consensus about on what level to look when we are talking about private and public attributes. You can of course start talking at a whole different level and as such use these words with a meaning different than normally understood. But that will just make it harder for you to get your ideas accross. -- Antoon Pardon From ppearson at nowhere.invalid Thu Jun 26 12:20:01 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: Thu, 26 Jun 2008 11:20:01 -0500 Subject: Freeze problem with Regular Expression References: <6cf614F3f8ocoU1@mid.individual.net> Message-ID: On 25 Jun 2008 15:20:04 GMT, Kirk wrote: > Hi All, > the following regular expression matching seems to enter in a infinite > loop: > > ################ > import re > text = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA) > una ' > re.findall('[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-z]*\s*(?:[0-9] > *[A-Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$', text) > ################# > > No problem with perl with the same expression: > > ################# > $s = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA) una > '; > $s =~ /[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-z]*\s*(?:[0-9]*[A- > Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$/; > print $1; > ################# > > I've python 2.5.2 on Ubuntu 8.04. > any idea? If it will help some smarter person identify the problem, it can be simplified to this: re.findall('[^X]*((?:0*X+0*)+\s*a*\s*(?:0*X+0*\s*)*)([^X]*)$', "XXXXXXXXXXXXXXXXX (X" ) This doesn't actually hang, it just takes a long time. The time taken increases quickly as the chain of X's gets longer. HTH -- To email me, substitute nowhere->spamcop, invalid->net. From sjmachin at lexicon.net Thu Jun 26 20:12:45 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 26 Jun 2008 17:12:45 -0700 (PDT) Subject: Need help capturing output of re.search References: <771ef68a-d976-4f61-a3cc-7ed56fddc756@k37g2000hsf.googlegroups.com> <9757288e-0b48-46ee-8fd0-0adf36bbd710@p39g2000prm.googlegroups.com> <5fd345b7-6b32-4d45-8c55-662684adf5e9@34g2000hsf.googlegroups.com> Message-ID: <8e0883f9-f36d-4d62-a1a4-4cd66163a1cc@s21g2000prm.googlegroups.com> On Jun 27, 10:01 am, joemacbusin... at yahoo.com wrote: > >You may like to read this:http://www.amk.ca/python/howto/regex/ > > This is a good resource. Thank you. > Someone else pointed out that I needed to change the > > if reCheck == "None": > > to > > if reCheck == None: # removed the "s "Somebody else" should indeed remain anonymous if they told you that. Use if reCheck is None: or even better: if not reCheck: It's not obvious from your response if you got these points: (1) re.match, not re.search (2) filename.startswith does your job simply and more understandably From simon at brunningonline.net Fri Jun 13 02:56:15 2008 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 13 Jun 2008 07:56:15 +0100 Subject: e-value In-Reply-To: References: Message-ID: <8c7f10c60806122356k4809191iaaf96b855b1f23c1@mail.gmail.com> On Fri, Jun 13, 2008 at 7:45 AM, Beema shafreen wrote: > ... gi, seq, e_value = line.strip().split('\t') At this point, e_value contains a string value. You'll need to convert it to a float before you can meaningfully compare it. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From geoff.bache at jeppesen.com Wed Jun 25 08:01:14 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Wed, 25 Jun 2008 05:01:14 -0700 (PDT) Subject: Windows process ownership trouble Message-ID: <3fcf363f-3685-4b7b-8ba5-1ffc32e58af7@m44g2000hsc.googlegroups.com> Am currently being very confused over the following code on Windows import subprocess, os file = open("filename", "w") try: proc = subprocess.Popen("nosuchprogram", stdout=file) except OSError: file.close() os.remove("filename") This produces the following exception: Traceback (most recent call last): File "C:\processown.py", line 10, in os.remove("filename") WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'filename' How can it be in use by another process? The process didn't even start, right? Would appreciate some help: is this a Python bug, or a Windows bug, or just me being confused...? From antonxx at gmx.de Fri Jun 13 04:23:41 2008 From: antonxx at gmx.de (anton) Date: Fri, 13 Jun 2008 08:23:41 +0000 (UTC) Subject: using re module to find References: <5aeb32bd-923f-4b98-952b-06097ac8479d@v1g2000pra.googlegroups.com> Message-ID: John Machin lexicon.net> writes: > > On Jun 12, 7:11 pm, anton wrote: > > Hi, > > > > I want to replace all occourences of " by \" in a string. > > > > But I want to leave all occourences of \" as they are. > > > > The following should happen: > > > > this I want " while I dont want this \" ... cut text off > What you want is: > > >> import re > >> text = r'frob this " avoid this \", OK?' > >>> text > 'frob this " avoid this \\", OK?' > >> re.sub(r'(? frob this \\" avoid this \\", OK?' > >> > > HTH, > John > -- > http://mail.python.org/mailman/listinfo/python-list > > First.. thanks John. The whole problem is discussed in http://docs.python.org/dev/howto/regex.html#the-backslash-plague in the section "The Backslash Plague" Unfortunately this is *NOT* mentioned in the standard python documentation of the re module. Another thing which will always remain strange to me, is that even if in the python doc of raw string: http://docs.python.org/ref/strings.html its written: "Specifically, a raw string cannot end in a single backslash" s=r"\\" # works fine s=r"\" # works not (as stated) But both ENDS IN A SINGLE BACKSLASH ! The main thing which is hard to understand is: If a raw string is a string which ignores backslashes, then it should ignore them in all circumstances, or where could be the problem here (python parser somewhere??). Bye Anton From sjmachin at lexicon.net Thu Jun 19 19:14:40 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 19 Jun 2008 16:14:40 -0700 (PDT) Subject: Why no output from xml.dom.ext.PrettyPrint? References: Message-ID: <19999864-b381-41b5-90fa-7e3cc3996d65@w8g2000prd.googlegroups.com> On Jun 20, 7:17 am, kj wrote: > OK, the following should work but doesn't, and I can't figure out > why: > > >>> from xml.marshal.generic import dumps > >>> dumps( ( 1, 2.0, 'foo', [3,4,5] ) ) > > '12.0foo345' > > >>> from xml.dom.ext import PrettyPrint > >>> PrettyPrint( dumps( ( 1, 2.0, 'foo', [3,4,5] ) ) ) > >>> import sys > >>> PrettyPrint( dumps( ( 1, 2.0, 'foo', [3,4,5] ) ), sys.stdout ) > > Why am I seeing no output from PrettyPrint? > You need to ask whoever you got your xml package from. In standard- issue Python 2.5.2, there is an xml package with xml.dom, but it contains no xml.dom.ext nor an xml.marshal. From hongyuan1306 at gmail.com Tue Jun 10 05:28:11 2008 From: hongyuan1306 at gmail.com (Yuan HOng) Date: Tue, 10 Jun 2008 17:28:11 +0800 Subject: Py2exe and name space package Message-ID: <91320d220806100228h771c4edn3ae88b26920029ad@mail.gmail.com> Hi, I used to freeze my application into Windows executibles using py2exe. Lately I started using several zope packages in my application, like zope.interface. Now the freezed program can't run properly. Like the following example shows: My setup.py file: from distutils.core import setup import py2exe setup(name='test', zipfile=None, console=[ { 'script': 'main.py', } ]) The main.py test code: from zope.interface import Interface print Interface During the freezing process, the following warning is shown: *** copy dlls *** copying c:\Python25\lib\site-packages\py2exe-0.6.6-py2.5-win32.egg\py2exe\run.exe -> C:\temp\dist\main.exe The following modules appear to be missing ['pkg_resources', 'zope.interface'] Running main.exe gives me an import Error. C:\temp\dist>main.exe Traceback (most recent call last): File "main.py", line 1, in ImportError: No module named interface What should I do to make py2exe recognize and include zope.interface in the binary distribution? Thanks. -- Hong Yuan ????????? ??????????? http://www.homemaster.cn From bkasterm at gmail.com Mon Jun 16 06:34:06 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Mon, 16 Jun 2008 03:34:06 -0700 (PDT) Subject: String Concatenation O(n^2) (was: Re: Explaining Implementing a Binary Search Tree.) References: Message-ID: Summary: can't verify big O claim, how to properly time this? On Jun 15, 2:34 pm, "Terry Reedy" wrote: > "Bart Kastermans" wrote in message > > news:ae91857d-ea63-4204-9fc3-251049adee98 at k13g2000hse.googlegroups.com... > |I wrote a binary search tree in python, explaining as I was doing it > | how and why I did it. I am very interested in receiving comments on > | the code, process, and anything else that will improve my coding or > | writing. > | > | I wrote this all up in my blog at: > | > |http://kasterma.wordpress.com/2008/06/15/implementing-a-binary-search... > | > | The code of the class has been copied below, but the description of > | the process (mostly an attempt at approaching test driving development > | for as far as I understand the term) has not been copied. > | > | Any and all comments are appreciated. > | > | Best, > | Bart > | > | *********** python code ************************ > | > | > | import re > | > | class BSTree: > | def __init__ (self, value = None): > | self.value = value > | self.left = None > | self.right = None > > There are two possible approaches. > 1. Define 1 tree class that is also used for subtrees -- what you did. > Complication: self.value of root node can be none, so you constantly > have to check self.value for None even though only possible for root node. > 2. Define tree class and node class. This had other complications, but > removes that above and makes str easier. tree.str = '(' str(rootnode) ')' > and node.str= self.value '(' str(self.left) ')' '(' str(self.right) ')'. > > If use '' instead of None, no conditionals are needed. (This might apply > partly to your version as well.) Or define class NullTree with a singleton > instance with no attributes and a str method returning '' and an inOrder > method yielding nothing. This would also eliminate the condifionals in the > inOrder method. Not sure what is best. With a good test suite, it is easy > to make sure alternative implementations 'work' before testing for speed. Thanks for the idea. I would expect the separation to lead to somewhat more code, but all the "checking the root" code would be separated out in the tree class. The node class would be very smooth. I'll try this when I have some time (today I spend my "alloted" programming time on what is below). (also the comment about inOrder returning a generator was because I tried to figure it out, failed, and then got enough by doing it without yield. I forgot to bring my comment in line with my code. A generator would certainly be nicer, and I'll work at understanding your suggestion for it.) > > | def __str__ (self): > > string appending is an O(n**2) operations. The usual idiom, applied here, > would be slist = ['('], slist.append(str(self.value)), .... return > ''.join(slist). In other words, collect list of pieces and join at end. This is interesting. I had never attempted to verify a big O statement before, and decided that it would be worth trying. So I wrote some code to collect data, and I can't find that it goes quadratic. I have the graph at http://kasterma.wordpress.com/2008/06/16/complexity-of-string-concatenation/ It looks piecewise linear to me. The code I used to collect the data is as follows: ************************************************************************* import time NUMBER = 100 # number of strings to concatenate at given length JUMP = 500 # jump (and start length) of length of strings END = 100001 # longest length string considered def randomString (length): """ returns a random string of letters from {a,b,c,d} of length """ string = "" for i in range (0,length): string += choice ("abcd") return string def randomStrings (number, length): """ returns an array of number random strings all of length """ array = [] for i in range (0, number): array.append (randomString (length)) return array TimingData = [] for length in range (JUMP, END, JUMP): array1 = randomStrings (NUMBER, length) array2 = randomStrings (NUMBER, length) starttime = time.clock () for i in range (0, NUMBER): string = array1 [i] + array2 [i] endtime = time.clock () print "length", length, "done" TimingData.append ([length, 1000* (endtime-starttime)]) # to get a better looking graph multiply by 1000 sagefile = open ('stringConcatGraph.sage', "w") sagefile.write ("points =" + str (TimingData) + "\n") sagefile.write ("graph = line (points)\n") sagefile.write ("graph.show ()\n") sagefile.close () From dullrich at sprynet.com Mon Jun 30 15:43:45 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Mon, 30 Jun 2008 14:43:45 -0500 Subject: ask for a RE pattern to match TABLE in html References: <6a4f17690806260653i136681bdsabe0f6bb1dfab67b@mail.gmail.com> <62f752f3-d840-42de-a414-0d56d15d7c5a@w4g2000prd.googlegroups.com> <50285840-7601-41be-aa3d-865f46fe85c6@56g2000hsm.googlegroups.com> Message-ID: In article <50285840-7601-41be-aa3d-865f46fe85c6 at 56g2000hsm.googlegroups.com>, Dan wrote: > On Jun 27, 1:32 pm, "David C. Ullrich" wrote: > > In article > > <62f752f3-d840-42de-a414-0d56d15d7... at w4g2000prd.googlegroups.com>, > > Jonathan Gardner wrote: > > > > > On Jun 26, 3:22 pm, MRAB wrote: > > > > Try something like: > > > > > > re.compile(r'.*?', re.DOTALL) > > > > > So you would pick up strings like "
    foo > > td>
    "? I doubt that is what oyster wants. > > > > I asked a question recently - nobody answered, I think > > because they assumed it was just a rhetorical question: > > > > (i) It's true, isn't it, that it's impossible for the > > formal CS notion of "regular expression" to correctly > > parse nested open/close delimiters? > > Yes. For the proof, you want to look at the pumping lemma found in > your favorite Theory of Computation textbook. Ah, thanks. Don't have a favorite text, not having any at all. But wikipedia works - what I found at http://en.wikipedia.org/wiki/Pumping_lemma_for_regular_languages was pretty clear. (Yes, it's exactly that \1, \2 stuff that convinced me I really don't understand what one can do with a Python regex.) > > > > (ii) The regexes in languages like Python and Perl include > > features that are not part of the formal CS notion of > > "regular expression". Do they include something that > > does allow parsing nested delimiters properly? > > So, I think most of the extensions fall into syntactic sugar > (certainly all the character classes \b \s \w, etc). The ability to > look at input without consuming it is more than syntactic sugar, but > my intuition is that it could be pretty easily modeled by a > nondeterministic finite state machine, which is of equivalent power to > REs. The only thing I can really think of that is completely non- > regular is the \1 \2, etc syntax to match previously match strings > exactly. But since you can't to an arbitrary number of them, I don't > think its actually context free. (I'm not prepared to give a proof > either way). Needless to say that even if you could, it would be > highly impractical to match parentheses using those. > > So, yeah, to match arbitrary nested delimiters, you need a real > context free parser. > > > > > -- > > David C. Ullrich > > > -Dan -- David C. Ullrich From xng at xs4all.nl Wed Jun 18 11:57:47 2008 From: xng at xs4all.nl (Martin P. Hellwig) Date: Wed, 18 Jun 2008 17:57:47 +0200 Subject: Looking for lots of words in lots of files In-Reply-To: References: Message-ID: <485930cf$0$11744$e4fe514c@dreader19.news.xs4all.nl> Kris Kennaway wrote: > > If you can't use an indexer, and performance matters, evaluate using > grep and a shell script. Seriously. > > grep is a couple of orders of magnitude faster at pattern matching > strings in files (and especially regexps) than python is. Even if you > are invoking grep multiple times it is still likely to be faster than a > "maximally efficient" single pass over the file in python. This > realization was disappointing to me :) > > Kris Adding to this: Then again, there is nothing wrong with wrapping grep from python and revert to a pure python 'solution' if the system has no grep. Reinventing the wheel is usually only practical if the existing ones aren't round :-) -- mph From fetchinson at googlemail.com Tue Jun 3 13:10:38 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Tue, 3 Jun 2008 10:10:38 -0700 Subject: Keep a script running in the background In-Reply-To: <210b7fc6-ed52-461d-8b53-455e247d7a29@e39g2000hsf.googlegroups.com> References: <210b7fc6-ed52-461d-8b53-455e247d7a29@e39g2000hsf.googlegroups.com> Message-ID: > I need a script to keep running in the background after it's loaded > some data. It will make this data available to the main program in the > form of a dictionary, but I don't want to reload the calculated data > every time the user needs it via the main program. > > I won't be working with an UI, hope that can be made easily in Python > somehow. I'm not sure I understand exactly what you want but you might find these daemonize examples useful from the cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From Joshua.R.English at gmail.com Mon Jun 23 15:18:15 2008 From: Joshua.R.English at gmail.com (Josh English) Date: Mon, 23 Jun 2008 12:18:15 -0700 (PDT) Subject: learning unit testing in python References: Message-ID: <41389b77-423c-4ec8-9eb0-6b9a0e025939@l28g2000prd.googlegroups.com> A good starting point is Mark Pilgrim's Dive Into Python. http://www.diveintopython.org/unit_testing/index.html Josh On Jun 23, 7:55 am, Alex wrote: > Hi all. > > I'd like learn some basic unit testing with python. > I red some articles about different testing framework like unittest or > nose, but I'm a bit confused: what is the best choice? I'm not a > professional developer (I'm a SEO) but I belive that unit testing is a > good and pragmatic way to produce working software, so I'd like to > find something really simple ad straightforward because I don't have > to manage big programming projects. > > Thanks in advance, > > Alex From kyrie at uh.cu Thu Jun 12 08:33:33 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Thu, 12 Jun 2008 08:33:33 -0400 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <8d5ff104-6469-4397-b96c-74c4cc6448f6@s21g2000prm.googlegroups.com> <484e3526$0$30894$426a74cc@news.free.fr> <530581fb-e566-44da-8a3b-19ac1a334ff3@c19g2000prf.googlegroups.com> <783c55ec-a294-4600-91d9-4a0d78632c49@t12g2000prg.googlegroups.com> <4b4d6092-0ed5-40b3-859e-976c29fca71e@w1g2000prd.googlegroups.com> <484f880c$0$6412$426a74cc@news.free.fr> Message-ID: <1213274013.4851179d0a274@comuh.uh.cu> Quoting Dennis Lee Bieber : > On Wed, 11 Jun 2008 21:54:33 -0700 (PDT), Michele Simionato > declaimed the following in > comp.lang.python: > > > > > It looks like in French (as in Italian) *experimented* has the > > meaning of "tried and tested on the field" when applied to a > > person. > > > > > Fascinating Spanish also. I translate "experimentado" to "experienced", perhaps because I had seen it before, but I never imagined that "experimented" would be wrong. Fascinating x2 -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie From jzakiya at gmail.com Fri Jun 13 13:38:36 2008 From: jzakiya at gmail.com (jzakiya) Date: Fri, 13 Jun 2008 10:38:36 -0700 (PDT) Subject: Ultimate Prime Sieve -- Sieve Of Zakiya (SoZ) References: <5ebb27cd-e938-4f06-9aad-4ea056b851a9@c65g2000hsa.googlegroups.com> Message-ID: <1a768188-bbb8-4f0e-919a-76ac6bc0a336@p25g2000hsf.googlegroups.com> On Jun 13, 1:12?pm, jzakiya wrote: > This is to announce the release of my paper "Ultimate Prime Sieve -- > Sieve of Zakiiya (SoZ)" in which I show and explain the development of > a class of Number Theory Sieves to generate prime numbers. ? I used > Ruby 1.9.0-1 as my development environment on a P4 2.8 Ghz laptop. > > You can get the pdf of my paper and Ruby and Python source from here: > > http://www.4shared.com/dir/7467736/97bd7b71/sharing.html > > Below is a sample of one of the simple prime generators. I did a > Python version of this in my paper (see Python source too). ?The Ruby > version below is the minimum array size version, while the Python has > array of size N (I made no attempt to optimize its implementation, > it's to show the method). > > class Integer > ? ?def primesP3a > ? ? ? # all prime candidates > 3 are of form ?6*k+1 and 6*k+5 > ? ? ? # initialize sieve array with only these candidate values > ? ? ? # where sieve contains the odd integers representatives > ? ? ? # convert integers to array indices/vals by ?i = (n-3)>>1 = > (n>>1)-1 > ? ? ? n1, n2 = -1, 1; ?lndx= (self-1) >>1; ?sieve = [] > ? ? ? while n2 < lndx > ? ? ? ? ?n1 +=3; ? n2 += 3; ? sieve[n1] = n1; ?sieve[n2] = n2 > ? ? ? end > ? ? ? #now initialize sieve array with (odd) primes < 6, resize array > ? ? ? sieve[0] =0; ?sieve[1]=1; ?sieve=sieve[0..lndx-1] > > ? ? ? 5.step(Math.sqrt(self).to_i, 2) do |i| > ? ? ? ? ?next unless sieve[(i>>1) - 1] > ? ? ? ? ?# p5= 5*i, ?k = 6*i, ?p7 = 7*i > ? ? ? ? ?# p1 = (5*i-3)>>1; ?p2 = (7*i-3)>>1; ?k = (6*i)>>1 > ? ? ? ? ?i6 = 6*i; ?p1 = (i6-i-3)>>1; ?p2 = (i6+i-3)>>1; ?k = i6>>1 > ? ? ? ? ?while p1 < lndx > ? ? ? ? ? ? ?sieve[p1] = nil; ?sieve[p2] = nil; ?p1 += k; ?p2 += k > ? ? ? ? ?end > ? ? ? end > ? ? ? return [2] if self < 3 > ? ? ? [2]+([nil]+sieve).compact!.map {|i| (i<<1) +3 } > ? ?end > end > > def primesP3(val): > ? ? # all prime candidates > 3 are of form ?6*k+(1,5) > ? ? # initialize sieve array with only these candidate values > ? ? n1, n2 = 1, 5 > ? ? sieve = [False]*(val+6) > ? ? while ?n2 < val: > ? ? ? ? n1 += 6; ? n2 += 6; ?sieve[n1] = n1; ? sieve[n2] = n2 > ? ? # now load sieve with seed primes 3 < pi < 6, in this case just 5 > ? ? sieve[5] = 5 > > ? ? for i in range( 5, int(ceil(sqrt(val))), 2) : > ? ? ? ?if not sieve[i]: ?continue > ? ? ? ?# ?p1= 5*i, ?k = 6*i, ?p2 = 7*i, > ? ? ? ?p1 = 5*i; ?k = p1+i; ?p2 = k+i > ? ? ? ?while p2 <= val: > ? ? ? ? ? sieve[p1] = False; ?sieve[p2] = False; ?p1 += k; ?p2 += k > ? ? ? ?if p1 <= val: ?sieve[p1] = False > > ? ? primes = [2,3] > ? ? if val < 3 : return [2] > ? ? primes.extend( i for i in range(5, val+(val&1), 2) ?if sieve[i] ) > > ? ? return primes > > Now to generate an array of the primes up to some N just do: > > Ruby: ? ?10000001.primesP3a > Python: primesP3a(10000001) > > The paper presents benchmarks with Ruby 1.9.0-1 (YARV). ?I would love > to see my various prime generators benchmarked with optimized > implementations in other languages. ?I'm hoping Python gurus will do > better than I, though the methodology is very very simple, since all I > do is additions, multiplications, and array reads/writes. > > Have fun with the code. ?;-) > CORRECTION: http://cr.yp.to/primegen.html NOT "primesgen" Jabari Zakiya From timr at probo.com Sat Jun 28 00:30:50 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 28 Jun 2008 04:30:50 GMT Subject: Mako vs. Cheetah? References: <4862f57c$0$11621$607ed4bc@cv.net> <4863bf9c$0$14081$c3e8da3@news.astraweb.com> Message-ID: "John Salerno" wrote: > >Is it correct to say that Mako allows you to embed Python code within HTML, >whereas Cheetah requires a certain amount of "tweaking" of Python code so >that it isn't really code you could just run independently in the >interpreter? > >I'm getting that impression from what I see so far. What gives you that impression? I'm just curious. Other than the special characters used, my impression is that the two are far more similar than they are different. As I posted on one of the mailing lists this week, the most important criteria in your choice of a templating system really is personal preference. Personally, I really like Cheetah. I find it simple and intuitive, with a minimum of syntax interference. However, many people believe it violates the "separation of presentation and computation" rule too much, and that's just fine. Others really like the TAL scheme in Zope. For my taste, TAL just requires too much non-essential syntax; it interferes with the reading of the page. So, the folks who like TAL can go ahead and be productive with TAL, and I'll keep on being productive with Cheetah. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bearophileHUGS at lycos.com Mon Jun 23 09:46:04 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 23 Jun 2008 06:46:04 -0700 (PDT) Subject: Sending arrays of a structure as an argument via ctypes References: Message-ID: <6307e79b-be4e-410a-9d84-6200dafc5e1c@k37g2000hsf.googlegroups.com> Knut Saua Mathiesen: > Any help? :p My faster suggestion is to try ShedSkin, it may help you produce a fast enough extension. If ShedSkin doesn't compile it, its author (Mark) may be quite willing to help. bye, bearophile From paddy3118 at googlemail.com Fri Jun 13 00:42:44 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 12 Jun 2008 21:42:44 -0700 (PDT) Subject: Mapping None. Why? References: <6bdbtuF3aqe92U1@mid.uni-berlin.de> <6bddafF3b1u2tU1@mid.uni-berlin.de> Message-ID: On Jun 12, 8:55 pm, "Diez B. Roggisch" wrote: > > And the OP's question was about map not being conforming to the > definition on wikipedia - which I don't think it's not. It is not > defined what map is to do with None (or NULL or nil or... ) as argument. > > Diez Oh no! Sorry to give that impression. I don't think that map should be like what Wikipedia says, I was just looking for another example of an implementation that might mention the behaviour. I just want to know the thoughts behind this behaviour in the Python map. - Paddy. From kirk at daycos.com Wed Jun 18 10:48:57 2008 From: kirk at daycos.com (Kirk Strauser) Date: Wed, 18 Jun 2008 09:48:57 -0500 Subject: question relateding to parsing dbf files. References: Message-ID: <87wskm6bom.fsf@internal.daycos.com> At 2008-06-18T12:50:20Z, "Krishnakant Mane" writes: > hello all. > I need to parse some dbf files through python. > the reason being that I have to migrate some old data from dbf files > to postgresql. > all that I need to know is if some one has got a working code sample > using dbfpy. > I found this module suitable for my work but can't figure out how to use it. > else, if there is any other module, please recommend so. > happy hacking. > Krishnakant. Does it have to by in Python? I host this project, written in C++: http://honeypot.net/project/xbasetopg . If that's too complicated, I've written a replacement in straight C but I haven't published it yet. I use these programs to sync our legacy FoxPro database to our new PostgreSQL servers on an hourly basis. Syncing 4GB of data tables about 10 minutes. -- Kirk Strauser The Day Companies From gherron at islandtraining.com Thu Jun 5 20:17:07 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 05 Jun 2008 17:17:07 -0700 Subject: Newb question: underscore In-Reply-To: References: Message-ID: <48488203.8080105@islandtraining.com> Skye wrote: > What is this doing? > > print >> fd, _(__doc__) > > > I'm guessing line-splitting __doc__ into a list, but what's that > leading underscore do? > It's calling a function with a single argument, like sqrt(x), except the function is named _ and the argument is named __doc__. The underscores have no special significance here, but they do make the code hard to read. The first part of the statement directs the print to send the output to a file, named fd, which was presumably opened earlier ... but I don't think that was part of your question. Gary Herron > Thanks! > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Mon Jun 2 23:53:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 03 Jun 2008 00:53:11 -0300 Subject: mmap class has slow "in" operator References: <483F2B61.6050306@FreeBSD.org> Message-ID: En Thu, 29 May 2008 19:17:05 -0300, Kris Kennaway escribi?: > If I do the following: > > def mmap_search(f, string): > fh = file(f) > mm = mmap.mmap(fh.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ) > > return mm.find(string) > > def mmap_is_in(f, string): > fh = file(f) > mm = mmap.mmap(fh.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ) > > return string in mm > > then a sample mmap_search() call on a 50MB file takes 0.18 seconds, but > the mmap_is_in() call takes 6.6 seconds. Is the mmap class missing an > operator and falling back to a slow default implementation? Presumably > I can implement the latter in terms of the former. Looks like you should define the sq_contains member in mmap_as_sequence, and the type should have the Py_TPFLAGS_HAVE_SEQUENCE_IN flag set (all in mmapmodule.c) -- Gabriel Genellina From geoff.bache at jeppesen.com Thu Jun 26 11:25:40 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Thu, 26 Jun 2008 08:25:40 -0700 (PDT) Subject: Windows process ownership trouble References: <3fcf363f-3685-4b7b-8ba5-1ffc32e58af7@m44g2000hsc.googlegroups.com> Message-ID: <990516b7-f7ef-464a-97d0-fd55a0354ab4@y21g2000hsf.googlegroups.com> Thanks Tim, very helpful again. I've now reported this as http://bugs.python.org/issue3210 and implemented your suggested workaround. Regards, Geoff On Jun 25, 9:19 pm, Tim Golden wrote: > geoffbache wrote: > > Am currently being very confused over the following code on Windows > > > import subprocess, os > > > file = open("filename", "w") > > try: > > proc = subprocess.Popen("nosuchprogram", stdout=file) > > except OSError: > > file.close() > > os.remove("filename") > > Forgot to say: slightly awkward, but you can work around > it like this: > > > import os > import subprocess > > f = open ("filename", "w") > try: > proc = subprocess.Popen ("blah", stdout=f) > except OSError: > os.close (f.fileno ()) > > os.remove ("filename") > > > > TJG From woodygar at sky.com Thu Jun 5 09:43:56 2008 From: woodygar at sky.com (garywood) Date: Thu, 5 Jun 2008 14:43:56 +0100 Subject: No subject Message-ID: <000c01c8c712$347dd660$1300a8c0@Home> Hi there. So I have a challenge in the Python book I am using (python programming for the absolute beginner) that tells me to improve an ask_number() function, so that it can be called with a step value, and I havn't been able to find out yet what's meant by a step value, but i'll keep looking of course. I'd just be grateful if someone could illimunate this for me. def ask_number(question, low, high): """Ask for a number within a range.""" response = None while response not in range(low, high): response = int(raw_input(question)) return response Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sun Jun 15 13:52:56 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Jun 2008 19:52:56 +0200 Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> Message-ID: ram.rachum at gmail.com wrote: > I have a physical system set up in which a body is supposed to > accelerate and to get very close to lightspeed, while never really > attaining it. After approx. 680 seconds, Python gets stuck and tells > me the object has passed lightspeed. I put the same equations in > Mathematica, again I get the same mistake around 680 seconds. So I > think, I have a problem with my model! Then I pump up the > WorkingPrecision in Mathematica to about 10. I run the same equations > again, and it works! At least for the first 10,000 seconds, the object > does not pass lightspeed. That the values are possible doesn't mean that you can trust them. > I concluded that I need Python to work at a higher precision. How is WorkingPrecision defined? Python floats have about 16 significant digits in base 10, so at first glance I would guess that you switched to a /lower/ precision. But I've come to agree with Christian that it would be good to show your model to a physics and/or numerical maths expert. Perhaps you can find a way for the errors to cancel out rather than accumulate. Peter From aweraw at gmail.com Tue Jun 10 20:51:53 2008 From: aweraw at gmail.com (Aidan) Date: Wed, 11 Jun 2008 10:51:53 +1000 Subject: Dynamic HTML from Python Script In-Reply-To: <484f151c$0$5009$607ed4bc@cv.net> References: <484f151c$0$5009$607ed4bc@cv.net> Message-ID: <484f21aa$1@dnews.tpgi.com.au> asdf wrote: > I have a python script whose output i want to dynamically display > on a webpage which will be hosted using Apache. How do I do that? > > > thanks Well, there's a few ways you could approach it. You could create a cgi program from your script - this is probably the solution you're looking for. You could have the script run periodically and create a static html file in the webroot... this would be acceptable, maybe preferable, if the output from your script doesn't change frequently. There's also more advanced ways you can make python code run in a web-service. Cherrypy comes to mind, as well as the myriad python MVC frameworks. From leechat2001 at gmail.com Mon Jun 30 16:11:59 2008 From: leechat2001 at gmail.com (leechat2001 at gmail.com) Date: Mon, 30 Jun 2008 13:11:59 -0700 (PDT) Subject: URLLIb2 problem Message-ID: <156e077b-1305-476c-885f-0b798f4ce699@s21g2000prm.googlegroups.com> I am trying to write somecode of this kind :) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) opener.addheaders = [('User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14'), ('Accept','text/xml,application/xml,application/xhtml+xml,text/ html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'),('Accept- Language','en-us,en;q=0.5'),('Accept-Encoding','gzip,deflate'), ('Accept-Charset','ISO-8859-1,utf-8;q=0.7,*;q=0.7'),('Keep- Alive','300'),('Connection','keep-alive'),('Content-Type','application/ x-www-form-urlencoded')] urllib2.install_opener(opener) fu = urllib2.urlopen('http://www.google.com') print fu.read() I am not able to open any webpage as the content is junk characters.something like below..what could be the problem????????????? if I don't install the 'opener' I get everything properly ?]?s?H? ?T? ?Cj2????x:&? ?c???????~J ?????I??w???????ZB??q?? ?T9?R???????????4 ?7?????V??.i??"?????????W>? ??y?=vm??)?????6??y???????9????l????>?????????(?g[??? L?S??????????e???????GcS??w s????/??G??|???9??F`??????*?????BV,????????o??pzn??;?y9?4 ???f????z8???b?n??K}|? From sir.heyhey at gmail.com Tue Jun 3 10:12:53 2008 From: sir.heyhey at gmail.com (Ivan Velev) Date: Tue, 3 Jun 2008 07:12:53 -0700 (PDT) Subject: need help with timezone conversion (unexpected side effect of time.mktime ??) Message-ID: Hello, Minimal example below - it gives me different output if I comment / uncomment the extra time.mktime call - note that this call is not related in any way to main logic flow. When "problematicStamp = ..." is commented I get gmtStamp: 1130634600.0 when I uncomment that line I get gmtStamp: 1130631000.0 I have tried this on a couple of Linux machines and it was reproducible everyewhere. One of those machines has the following Python version (If needed I can provide more details) > Python 2.5 (r25:51908, Mar 26 2007, 23:34:03) Any idea what' happening there ? Ivan --------------- import time, os # to see the difference, uncomment this line # problematicStamp = time.mktime((2004, 10, 30, 4, 10, 0, 6, 303, -1)) os.putenv("TZ", "Europe/Sofia") time.tzset() gmtStamp = time.mktime((2005, 10, 30, 3, 10, 0, 6, 303, -1)) print "gmtStamp:", gmtStamp From kyrie at uh.cu Sun Jun 29 01:11:45 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Sun, 29 Jun 2008 01:11:45 -0400 Subject: Why is recursion so slow? In-Reply-To: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> Message-ID: <1214716305.4867199171034@comuh.uh.cu> Quoting slix : > Recursion is awesome for writing some functions, like searching trees > etc but wow how can it be THAT much slower for computing fibonacci- > numbers? The problem is not with 'recursion' itself, but with the algorithm: > def fibr(nbr): > if nbr > 1: > return fibr(nbr-1) + fibr(nbr-2) > if nbr == 1: > return 1 > if nbr == 0: > return 0 If you trace, say, fibr(5), you'll find that your code needs to compute fibr(4) and fibr(3), and to compute fibr(4), it needs to compute fibr(3) and fibr(2). As you can see, fibr(3), and it whole subtree, is computed twice. That is enough to make it an exponential algorithm, and thus, untractable. Luckily, the iterative form is pretty readable and efficient. If you must insist on recursion (say, perhaps the problem you are solving cannot be solved iteratively with ease), I'd suggest you to take a look at 'dynamic programming', or (easier but not necesarily better), the 'memoize' disgn pattern. > is the recursive definition counting fib 1 to fib x-1 for every x? Yes - that's what the algorithm says. (Well, actually, the algorithm says to count more than once, hence the exponential behaviour). The memoize patter could help in this case. > is > that what lazy evaluation in functional languages avoids thus making > recursive versions much faster? Not exactly... Functional languages are (or should be) optimized for recursion, but if the algorithm you write is still exponential, it will still take a long time. > is recursive fibonacci in haskell as fast as an imperative solution in > a procedural language? > [...] > i found a version in Clojure that is superfast: I've seen the haskell implementation (quite impressive). I don't know Clojure (is it a dialect of Lisp?), but that code seems similar to the haskell one. If you look closely, there is no recursion on that code (no function calls). The haskell code works by defining a list "fib" as "the list that starts with 0,1, and from there, each element is the sum of the element on 'fib' plus the element on 'tail fib'). The lazy evaluation there means that you can define a list based on itself, but there is no recursive function call. Cheers, (I'm sleepy... I hope I made some sense) -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie From alex at moreati.org.uk Tue Jun 17 18:15:33 2008 From: alex at moreati.org.uk (moreati) Date: Tue, 17 Jun 2008 15:15:33 -0700 (PDT) Subject: Calling pcre with ctypes Message-ID: <947df973-8bae-4364-bf76-64a9a7d4a51f@s50g2000hsb.googlegroups.com> Recently I discovered the re module doesn't support POSIX character classes: Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> r = re.compile('[:alnum:]+') >>> print r.match('123') None So I thought I'd try out pcre through ctypes, to recreate pcredemo.c in python. The c code is at: http://vcs.pcre.org/viewvc/code/trunk/pcredemo.c?view=markup Partial Python code is below I'm stuck, from what I can tell a c array, such as: int ovector[OVECCOUNT]; translates to ovector = ctypes.c_int * OVECOUNT but when I pass ovector to a function I get the traceback $ python pcredemo.py [a-z] fred Traceback (most recent call last): File "pcredemo.py", line 65, in compiled_re, None, subject, len(subject), 0, 0, ovector, OVECOUNT ctypes.ArgumentError: argument 7: : Don't know how to convert parameter 7 What is the correct way to construct and pass ovector? With thanks, Alex # PCRE through ctypes demonstration program import ctypes import getopt import sys import pcre_const OVECOUNT = 30 # Should be a multiple of 3 pcre = ctypes.cdll.LoadLibrary('libpcre.so') compiled_re = None error = ctypes.c_char_p() pattern = '' subject = '' name_table = ctypes.c_ubyte() erroffset = ctypes.c_int() find_all = 0 namecount = 0 name_entry_size = 0 ovector = ctypes.c_int * OVECOUNT options = 0 # First, sort out the command line. There is only one possible option at # the moment, "-g" to request repeated matching to find all occurrences, # like Perl's /g option. We set the variable find_all to a non-zero value # if the -g option is present. Apart from that, there must be exactly two # arguments. opts, args = getopt.getopt(sys.argv[1:], 'g') for o, v in opts: if o == '-g': find_all = 1 # After the options, we require exactly two arguments, which are the # pattern, and the subject string. if len(args) != 2: print 'Two arguments required: a regex and a subject string' sys.exit(1) pattern = args[0] subject = args[1] subject_length = len(subject) # Now we are going to compile the regular expression pattern, and handle # and errors that are detected. compiled_re = pcre.pcre_compile( pattern, options, ctypes.byref(error), ctypes.byref(erroffset), None ) From circularfunc at yahoo.se Wed Jun 11 18:39:20 2008 From: circularfunc at yahoo.se (cirfu) Date: Wed, 11 Jun 2008 15:39:20 -0700 (PDT) Subject: web2py forum or mailing list? References: Message-ID: web2py > django mailing list: http://groups.google.com/group/web2py From exarkun at divmod.com Mon Jun 23 13:46:12 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 23 Jun 2008 13:46:12 -0400 Subject: Using Python to run SSH commands on a remote server In-Reply-To: <03a078c8$0$3229$c3e8da3@news.astraweb.com> Message-ID: <20080623174612.4714.2084698320.divmod.quotient.12235@ohm> On Mon, 23 Jun 2008 13:30:55 -0400, John Salerno wrote: >Generally speaking, what tools would I use to do this? Is there a built-in >module for it? I looked at the telnetlib module, but the documentation >wasn't really complete enough for me to get a good idea of it. Is Telnet and >SSH even the same thing? Telnet and SSH are different things. There's nothing in the standard library for making an SSH connection (aside from the process control libraries, which let you run an external SSH client in a child process). > >Basically, I want to write a script that will automate the process of making >all .py files on my web server executable (chmod 755, or something similar). There are several third-party SSH libraries, eg Twisted Conch and Paramiko. Jean-Paul From aweraw at gmail.com Thu Jun 12 10:39:49 2008 From: aweraw at gmail.com (Aidan) Date: Fri, 13 Jun 2008 00:39:49 +1000 Subject: Summing a 2D list In-Reply-To: References: <1be42ab4-091c-4c53-a585-64948be600b5@x35g2000hsb.googlegroups.com> <6bcokhF3b2mo7U1@mid.uni-berlin.de> <485131a1$0$11175$c3e8da3@news.astraweb.com> Message-ID: Mark wrote: > John, it's a QuerySet coming from a database in Django. I don't know > enough about the structure of this object to go into detail I'm > afraid. > > Aidan, I got an error trying your suggestion: 'zip argument #2 must > support iteration', I don't know what this means! well, if we can create 2 iterable sequences one which contains the user the other the scores, it should work the error means that the second argument to the zip function was not an iterable, such as a list tuple or string can you show me the lines you're using to retrieve the data sets from the database? then i might be able to tell you how to build the 2 lists you need. > Thanks to all who have answered! Sorry I'm not being very specific! From hwcowan at hotmail.com Mon Jun 23 12:10:47 2008 From: hwcowan at hotmail.com (hwcowan at hotmail.com) Date: Mon, 23 Jun 2008 09:10:47 -0700 (PDT) Subject: Using Python and MS-SQL Server Message-ID: <734a9927-a18b-4af6-a717-eaf2631b4836@c58g2000hsc.googlegroups.com> Hello, I have programmed before, but I am new to using Python. I am currently using the ArcGIS software which uses Python as its scripting language for automating tasks. The current script that I am working on requires pulling in some information from a Microsoft SQL Server. I was wondering if anyone could suggest the best way of doing this? I have looked at the different modules that are specific to SQL server, but none of them seem to be active or up to date. If not, could anyone make any suggestions? Or would it be better to go the ODBC route? I am not talking about large amounts of data, so I am not concerned about performance so ODBC would be fine to use as well. Also, being new to Python, I recently read about dictionaries and was wondering if there was a quick way to dump a table into a dictionary? For example, I have a customer list with a customer ID. It would be great to have the ID as the "key" and the name as the "data" (or even better, have a list as the data element containing all the information about the customer). I am sure that this could be done manually, by looping through each record and adding it to the dictionary -- but I was just wondering if something like this has already been done (I don't need to reinvent the wheel here). Thanks so much, Hugh From __peter__ at web.de Sun Jun 1 20:05:19 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 Jun 2008 02:05:19 +0200 Subject: a question about the #prefix of sys.argv References: Message-ID: Aldarion wrote: > for the little script > #egg.py > import sys > for k,v in enumerate(sys.argv): > print k,v > > it ignores ?the part after # on linux > below is the running output on windows and linux. no clue here. This has nothing to do with python, it's the shell that treats the # and everything that follows as a comment. $ ./listargs.py alpha #beta 0 ./listargs.py 1 alpha But you can escape it: $ ./listargs.py alpha \#beta 0 ./listargs.py 1 alpha 2 #beta $ ./listargs.py alpha '#beta' 0 ./listargs.py 1 alpha 2 #beta Peter From yonnym at googlemail.com Wed Jun 11 10:36:00 2008 From: yonnym at googlemail.com (uo) Date: Wed, 11 Jun 2008 07:36:00 -0700 (PDT) Subject: Object Manipulation and Frames Message-ID: <41d99183-665d-43f7-802d-5636506629fe@a1g2000hsb.googlegroups.com> Hello people, I would like to get some advice on the method that i should use to develop a cyber billing wxpython app.I had started but i hit a snag when i realised i could not launch or fiddle with properties of a Frame object within another frame object, what i had intended to do was to first launch a login frame where members would login and after successful authentication , the frame would be hidden and another would be launched for billing...i had a LoginFrame and a BillingFrame but after successful auth i found it hard to switch the BillingFrame.Show(True), can this be done ...and would making use of MDI make it beter? ...and if not could anyone please suggest a better/ workable alternative..Thank you. From musiccomposition at gmail.com Mon Jun 16 22:59:27 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 16 Jun 2008 19:59:27 -0700 (PDT) Subject: Context manager for files vs garbage collection References: <74f25d98-a6a5-4034-b3b7-06a8ca40ce04@e39g2000hsf.googlegroups.com> <4856699b$0$12566$426a74cc@news.free.fr> Message-ID: <2c43384e-5755-4869-ac61-c7bdd207ee30@a1g2000hsb.googlegroups.com> On Jun 16, 8:24 am, Bruno Desthuilliers wrote: > > IIRC (please someone correct me if I'm wrong), proper release of file > resources as soon as the file object gets out of scope is not garanteed > in the language spec and is implementation dependant. Right. Resources are freed in CPython right after they drop out of scope. This is not true in other implementations, so it's best to be explicit. From kris at FreeBSD.org Wed Jun 18 09:39:45 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Wed, 18 Jun 2008 15:39:45 +0200 Subject: ZFS bindings Message-ID: <48591021.1020303@FreeBSD.org> Is anyone aware of python bindings for ZFS? I just want to replicate (or at least wrap) the command line functionality for interacting with snapshots etc. Searches have turned up nothing. Kris From chardish at gmail.com Tue Jun 10 11:04:18 2008 From: chardish at gmail.com (chardish at gmail.com) Date: Tue, 10 Jun 2008 08:04:18 -0700 (PDT) Subject: Instructions on how to build py2exe 0.6.8 (or an installer would be nice, too!) Message-ID: <5426baaf-2ba6-41b0-a0ec-1070429b5195@x35g2000hsb.googlegroups.com> Hello, I'm trying to build an executable with py2exe, but unfortunately the version I have is 0.6.6, which has a rather annoying bug that doesn't let you rename the executable file if you bundle everything in a single executable. It seems fairly unacceptable to tell our customers that they can't rename a file we send them. I hear this problem is fixed in 0.6.8, but unfortunately there's no standalone installer for py2exe 0.6.8 - the most recent version that has an installer is 0.6.6 way back from 2006 (!). Is there a standalone installer for py2exe 0.6.8 anywhere? If not, how do I build it from source? (There's no instructions in the readme - it just says "How to install: download the standalone installer" and doesn't include building instructions.) Cheers, Evan From castironpi at gmail.com Tue Jun 10 20:33:08 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 10 Jun 2008 17:33:08 -0700 (PDT) Subject: Python doesn't understand %userprofile% References: <484f1375_1@news.tm.net.my> Message-ID: On Jun 10, 6:51?pm, TheSaint wrote: > On 00:11, mercoled? 11 giugno 2008 Tim Golden wrote: > > > "%USERPROFILE%/dir/file". > > os.environ('USERPROFILE') should return an info regarding that environment > variable. > I guess that, not yet tried. > -- > Mailsweeper Home :http://it.geocities.com/call_me_not_now/index.html I found: from os import environ r'%(HOMEPATH)s\My Documents\My Pictures\pycon.bmp'% environ But 'os.join' is supposedly more correct. From george.sakkis at gmail.com Sun Jun 15 14:25:04 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 15 Jun 2008 11:25:04 -0700 (PDT) Subject: Removing inheritance (decorator pattern ?) Message-ID: I have a situation where one class can be customized with several orthogonal options. Currently this is implemented with (multiple) inheritance but this leads to combinatorial explosion of subclasses as more orthogonal features are added. Naturally, the decorator pattern [1] comes to mind (not to be confused with the the Python meaning of the term "decorator"). However, there is a twist. In the standard decorator pattern, the decorator accepts the object to be decorated and adds extra functionality or modifies the object's behavior by overriding one or more methods. It does not affect how the object is created, it takes it as is. My multiple inheritance classes though play a double role: not only they override one or more regular methods, but they may override __init__ as well. Here's a toy example: class Joinable(object): def __init__(self, words): self.__words = list(words) def join(self, delim=','): return delim.join(self.__words) class Sorted(Joinable): def __init__(self, words): super(Sorted,self).__init__(sorted(words)) def join(self, delim=','): return '[Sorted] %s' % super(Sorted,self).join(delim) class Reversed(Joinable): def __init__(self, words): super(Reversed,self).__init__(reversed(words)) def join(self, delim=','): return '[Reversed] %s' % super(Reversed,self).join(delim) class SortedReversed(Sorted, Reversed): pass class ReversedSorted(Reversed, Sorted): pass if __name__ == '__main__': words = 'this is a test'.split() print SortedReversed(words).join() print ReversedSorted(words).join() So I'm wondering, is the decorator pattern applicable here ? If yes, how ? If not, is there another way to convert inheritance to delegation ? George [1] http://en.wikipedia.org/wiki/Decorator_pattern From tjreedy at udel.edu Tue Jun 24 15:26:35 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Jun 2008 15:26:35 -0400 Subject: percent string replacement with index In-Reply-To: <7ci7j5-uu7.ln1@satorlaser.homedns.org> References: <7ci7j5-uu7.ln1@satorlaser.homedns.org> Message-ID: Ulrich Eckhardt wrote: > What I'm surprised is that this isn't supported: > > "%(1)s %(2)s" % ("zero", "one", "two") > > i.e. specifying the index in a sequence instead of the key into a map (maybe > I would use [1] instead of (1) though). Further, the key can't be a simple > number it seems, which makes this even more inconvenient to me. > > Can anyone explain this to me? History. See below. > > Also, why isn't the 's' conversion (i.e. to a string) the default? I > personally would like to just write something like this: > > "%1 is not %2" % ("zero", "one", "two") > > or maybe > > "%[1] is not %[2]" % ("zero", "one", "two") In 2.6 (I believe) and 3.0: >>> "{1} is not {2} or {0}. It is just {1}".format("zero", "one", "two") 'one is not two or zero. It is just one' From paul.hankin at gmail.com Sun Jun 22 19:23:34 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sun, 22 Jun 2008 16:23:34 -0700 (PDT) Subject: listcomprehension, add elements? References: <13452c64-ef91-49a2-bb73-7f33c088660e@d45g2000hsc.googlegroups.com> Message-ID: <7dc3d1d6-12d7-4a9e-ac7a-91406610e106@d19g2000prm.googlegroups.com> On Jun 23, 10:32?am, cirfu wrote: > [a+b for a,b in zip(xrange(1,51), xrange(50,0,-1))] > > [51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, > 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, > 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51] > > i want to add all the elemtns a s well. can i do this all in a > listcomprehension? > > i can do this ofc: > reduce(lambda x,y:x+y,[a+b for a,b in zip(xrange(1,51), > xrange(50,0,-1))]) > > but reduce is a functional way of doing it, what is the more pythonic > way of doing this? Use the builtin 'sum' function. sum(a + b for a, b in zip(xrange(1, 51), xrange(50, 0, -1))) -- Paul Hankin From gagsl-py2 at yahoo.com.ar Mon Jun 16 02:20:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 16 Jun 2008 03:20:32 -0300 Subject: os.walk Value Error? References: Message-ID: En Sat, 14 Jun 2008 19:06:16 -0300, escribi?: > I'm using os.walk as follows: > > (basedir, pathnames, files) = os.walk("results", topdown=True) > > and I'm getting the error: > > ValueError: too many values to unpack > >> From my googling, that means: > > This is the standard message when Python tries to unpack a tuple > into fewer variables than are in the tuple. > >> From what I can see of the examples on the python site, I'm using it > correctly. I have commas in my original code, and the "results" > directory exists and is directly under the directory from which my > script is run. Look the examples more carefully again - they don't use an assignment, but another Python statement... -- Gabriel Genellina From xushunttr2 at yahoo.cn Sun Jun 29 08:26:52 2008 From: xushunttr2 at yahoo.cn (jinole) Date: Sun, 29 Jun 2008 05:26:52 -0700 (PDT) Subject: Classical nurses site Message-ID: <82b3df24-8e1a-4153-8158-57a5b3eed716@p25g2000pri.googlegroups.com> Recommended for everyone to an Asian pornographic website?There are many beauty photos and movies.URL: http://www.loioi.com If you need more sites, then contact me. e-mail: aa459ss at live.cn From fuzzyman at gmail.com Mon Jun 23 15:21:11 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 23 Jun 2008 12:21:11 -0700 (PDT) Subject: installed 3.0, rebind winprompt to 2.5? References: <212d2320-0c9e-4744-823b-bf715d4bb9ee@c65g2000hsa.googlegroups.com> Message-ID: On Jun 23, 6:53?pm, cirfu wrote: > i installed python 3.0. now when im laucnhing from the dos prompt in > win vista it searches in python3.0 > > i want to rebind it to 2.5, what do i need to change? Reinstalling 2.5 should work. Michael Foord http://www.ironpythoninaction.com/ From mr.williamchang at gmail.com Wed Jun 18 17:25:04 2008 From: mr.williamchang at gmail.com (MisterWilliam) Date: Wed, 18 Jun 2008 14:25:04 -0700 (PDT) Subject: extra positional arguments before optional parameters syntax Message-ID: I noticed that in PEP 3105, the PEP about turning print to print(), the syntax for print() is defined as follows: def print(*args, sep=' ', end='\n', file=None) Ignoring the fact that print is a reserved keyword in python, this is not valid python because extra positional arguments (*args), cannot come before optional parameters (sep=' ', end='\n', file=None). >>> def f(*args, sep=' ', end='\n', file=None): File "", line 1 def f(*args, sep=' ', end='\n', file=None): ^ SyntaxError: invalid syntax Am I misunderstanding something? Is this type of syntax suppose to be allowed in a future version of Python? (I can't find anything about this through my searching.) This kind of syntax seems useful, especially one wants to overwrite the new function print(). Thanks, William Chang From gh at ghaering.de Sun Jun 8 05:00:21 2008 From: gh at ghaering.de (=?UTF-8?B?R2VyaGFyZCBIw6RyaW5n?=) Date: Sun, 08 Jun 2008 11:00:21 +0200 Subject: SQlite none english char In-Reply-To: References: Message-ID: <6b1ld5F3a4hsvU1@mid.uni-berlin.de> Gandalf wrote: > I works with python 2.5 on windows, And I use sqlite3 > > Now, I have problem searching string in Hebrew in my database > > I have table called "test" with field num and test > firs row i insert "1" and "?????" (that is "Hebrew" in Hebrew) > second row i insert "2" and "English" [...] I recommend you use Unicode strings for all your Python strings in the application. You can then be that things will just work with the sqlite3 module. The problem is that the sqlite3 module doesn't currently check if what you insert into the database is in UTF-8 encoding. But if it isn't, you're likely to run into problems later on. So, let's assume that you've written your Python using a UTF-8 editor, you can then use something like: # coding: utf-8 as the first line in the script. Among others, this will allow you to write Unicode literals in UTF-8, i. e. do something like: data = u"?????". then you can insert this into the database: cur.execute("insert into test(test) values (?)", (data,)) Note that I use the parametrized form of execute() with ? as placeholders. *Always* use this when the SQL statement is not constant, but has parameters of some sort. > [...] > cur.execute("select * from `test` where text like '%"+i+"%' ") > for row in cur: > print row[1] > > but this one print me nothing > instead of ????? This could be two problems. Either (likely) it simply isn't found because you inserted garbage (non-UTF-8 data) or you got a decoding error to UTF-8 executing the select, which the sqlite3 module will currently unfortunately ignore and return a None value instead. Again, use the parametrized form of the execute() statement with Unicode Python strings to avoid any problems. cur.execute("select * from test where text like '%' || ? || '%'", (searchstr,)) !!! Ok, I just found out that you used the + operator in SQL to concatenate strings. Don't, as it will not work (except on maybe MySQL). Use the || operator instead! Note that when you use cur.execute(sql, params), then params is actually a tuple of parameters. In the above examples there was only one parameter, so it was a one-tuple, which is written as (element,). Dont'write it as (element), because Python will not recognize it as a tuple then. Don't hesitate to ask if you need further help. -- Gerhard From sjmachin at lexicon.net Thu Jun 19 19:51:10 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 19 Jun 2008 16:51:10 -0700 (PDT) Subject: Hamming Distance References: <6d9f011f-3c35-4aae-81a6-e0fa47ff7056@a9g2000prl.googlegroups.com> Message-ID: <876fd21a-c53e-4c8b-b431-92a9f94c5faa@x19g2000prg.googlegroups.com> On Jun 20, 9:27 am, godavemon wrote: > I need to calculate the Hamming Distance of two integers. The hamming > distance is the number of bits in two integers that don't match. I > thought there'd be a function in math or scipy but i haven't been able > to find one. This is my function but it seems like there should be a > faster way. I do this computation many times and speed up is > important. > > def hamdist( a, b , bits = 32): > def _hamdist( x, bits): > if bits: > return (x & 1) + _hamdist(x >> 1, bits-1) > return x & 1 > return _hamdist( a ^ b, bits) > > Another alternative would be to convert the XOR to a binary string and Isn't it a "binary string" already? > count the # of 1's. My guess is that counting the 1-bits in (a ^ b) would be hard to beat, and that a recursive function is just not in the race. > > Which would be fastest? Implement both and time them. > Are there better alternatives? I doubt it. BTW one presumes that your integers are non-negative ... HTH Cheers, John From washakie at gmail.com Fri Jun 13 23:45:05 2008 From: washakie at gmail.com (John [H2O]) Date: Fri, 13 Jun 2008 20:45:05 -0700 (PDT) Subject: numpy: handling float('NaN') different in XP vs. Linux Message-ID: <17835502.post@talk.nabble.com> I have a script: from numpy import float OutD=[] v=['3','43','23.4','NaN','43'] OutD.append([float(i) for i in v[1]]) On linux: Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 [john at andLinux analysis]$ python jnk.py [[3.0, 43.0, 23.399999999999999, nan, 43.0]] On XP: Python 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\analysis>C:\Python25\python.exe jnk.py Traceback (most recent call last): File "jnk.py", line 4, in OutD.append([float(i) for i in v]) ValueError: invalid literal for float(): NaN WTF? -- View this message in context: http://www.nabble.com/numpy%3A-handling-float%28%27NaN%27%29-different-in-XP-vs.-Linux-tp17835502p17835502.html Sent from the Python - python-list mailing list archive at Nabble.com. From notnorwegian at yahoo.se Sun Jun 29 00:06:15 2008 From: notnorwegian at yahoo.se (slix) Date: Sat, 28 Jun 2008 21:06:15 -0700 (PDT) Subject: Why is recursion so slow? Message-ID: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> Recursion is awesome for writing some functions, like searching trees etc but wow how can it be THAT much slower for computing fibonacci- numbers? is the recursive definition counting fib 1 to fib x-1 for every x? is that what lazy evaluation in functional languages avoids thus making recursive versions much faster? is recursive fibonacci in haskell as fast as an imperative solution in a procedural language? def fibr(nbr): if nbr > 1: return fibr(nbr-1) + fibr(nbr-2) if nbr == 1: return 1 if nbr == 0: return 0 def fibf(n): sum=0 a=1 b=1 if n<=2: return 1 for i in range(3,n+1): sum=a+b a=b b=sum return sum i found a version in Clojure that is superfast: (def fib-seq (concat [0 1] ((fn rfib [a b] (lazy-cons (+ a b) (rfib b (+ a b)))) 0 1))) (defn fibx [x] (last (take (+ x 1) fib-seq))) (fibx 12000) is delivered instantly. is it using lazy evaluation? From omer at no-log.org Mon Jun 16 12:39:13 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Mon, 16 Jun 2008 18:39:13 +0200 Subject: 'string'.strip(chars)-like function that removes from the middle? In-Reply-To: <48569B9E.6030206@admailinc.com> References: <48569B9E.6030206@admailinc.com> Message-ID: <200806161839.13647.omer@no-log.org> Hi, > Greetings. > > The strip() method of strings works from both ends towards the middle. > Is there a simple, built-in way to remove several characters from a > string no matter their location? (besides .replace() ;) > > For example: > .strip --> 'www.example.com'.strip('cmowz.') > 'example' > .??? --> --- 'www.example.com'.strip('cmowz.') > 'exaple' > -- I don't see any string method to do that, but you can use a regexp : >>> re.sub('[cmowz.]', '', 'www.example.com') 'exaple' -- C?dric Lucantis From ivan.illarionov at gmail.com Fri Jun 6 12:01:33 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Fri, 6 Jun 2008 16:01:33 +0000 (UTC) Subject: Image Processing (batch) References: <6akqd5F37rofnU1@mid.individual.net> Message-ID: On Thu, 05 Jun 2008 07:10:56 +0000, Tim Roberts wrote: > Thomas Guettler wrote: >> >>I tried PIL for image batch processing. But somehow I don't like it >> - Font-Selection: You need to give the name of the font file. - >> Drawing on an image needs a different object that pasting and saving. >> - The handbook is from Dec. 2006. I don't want to dissapoint you but PIL font handling sucks terribly. > I have repeatedly seen the attitude in your last point, and I simply do > not understand it. What on Earth is wrong with having a product that > actually becomes stable? > > We all complain about Microsoft's feature bloat, rolling out unnecessary > new releases of their products year after year with features that no one > really needs. But when an open source product FAILS to produce a new > release every six weeks, we start seeing posts questioning whether the > product is still viable or has become abandonware. I think if you really TRY to create your own project you'll understand what's going on here. >From near 10 open source projects that I've started only 1 is living today. > Once a product does the job it was designed to do, IT'S DONE. Because there's no such thing as "do the job you where designed to do" Example: designed for image manipulation. No matter how many features you've already implemented there's always something more to do. > Personally, I think PIL is a great solution for batch processing, but > the beauty of the open source world is that the ARE alternatives. Yes, it's open source, and everybody will win if you'll extend PIL to do what you want. Really, I do have some working snippets of code that do handle fonts nicely with PIL images, read and parse OpenType tables, but I can't publish it because it's optimized for my private needs like only two languages: Russian and English. I had to rewrite PIL's FreeType layer from scratch to do what I want. You can do the same. Ivan From phillip.oldham at gmail.com Fri Jun 13 19:40:05 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Fri, 13 Jun 2008 16:40:05 -0700 (PDT) Subject: Making HEAD/PUT/DELETE requests with urllib2? Message-ID: In my attempt to learn python in a weekend, I've fallen foul at line 10 of my second scripting attempt. Basically I'm writing a simple spider, but currently I'm unable to find any documentation on making HEAD requests using the urllib2 library to test whether a file exists on a remote webserver. I've checked the docs on urllib2 from docs.python.org, and unless I'm missing something there doesn't seem to be a way to do *any* request other than a GET and POST. Surely this can't be correct? If so, we're all going to have a hell of a time creating RESTful web apps. Any help on the matter would be greatly appreciated. From hyugaricdeau at gmail.com Mon Jun 16 09:28:47 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Mon, 16 Jun 2008 06:28:47 -0700 (PDT) Subject: Iterate creating variables? References: <64f00c0a-8991-49f8-9f6f-9a66c01889d9@b1g2000hsg.googlegroups.com> Message-ID: On Jun 13, 11:34 am, "Reedick, Andrew" wrote: > > -----Original Message----- > > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- > > list-bounces+jr9445=att.... at python.org] On Behalf Of tda... at gmail.com > > Sent: Friday, June 13, 2008 11:11 AM > > To: python-l... at python.org > > Subject: Iterate creating variables? > > > I have twenty-five checkboxes I need to create (don't ask): > > > self.checkbox1 = ... > > self.checkbox2 = ... > > . > > . > > . > > self.checkbox25 = ... > > > Right now, my code has 25 lines in it, one for each checkbox, since > > these are all variables. > > > Is there a way to write a loop so that I can have fewer lines of code > > but still keep the variables? > > > I've tried: > > > for o in xrange(25): > > self.checkbox[o] = ... > > > which didn't work, and > > > for o in xrange(25): > > self.checkbox[''%d'%(o)] = ... > > > which also didn't work. > > > Both give the error message: "Attribute error: Main.App has no > > attribute "checkbox"", which clearly indicates that I'm not keeping > > the "variability" aspect I want. > > > Is there a way? > > > I appreciate any and all answers! > > Either store the checkboxes in an array or hash/dictionary. If that's > not practical, then > You can use strings to build the code and use eval to execute the string > as code. Ex: > > for i in range(10): > code = "%d + %d" % (i, i) > print eval(code) Don't do this. You want for idx in range(10): setattr(self, 'checkbox_%i' % idx) From dstromberglists at gmail.com Fri Jun 13 12:41:46 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Fri, 13 Jun 2008 16:41:46 GMT Subject: Automatically restarting system calls? Message-ID: I wrote a script(1) replacement in python (http://stromberg.dnsalias.org/ ~dstromberg/pypty/), but I'm encountering a problem in it. I think I know the solution to the problem, but I'd've thought python was high level enough that this solution isn't required, so I wanted to inquire about it here. Specifically, the program has a signal handler for window size changes. And if the window is resized during an os.write() (for example), I get a python exception about needing to restart the system call. In C, I know you're supposed to wrap your system calls with while loops until you don't get an ERESTART, but does one really need to wrap all of one's os.write()'s (for example) with such while loops in python? Thanks! From sk8in_zombi at yahoo.com.au Sun Jun 29 16:16:07 2008 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Sun, 29 Jun 2008 13:16:07 -0700 (PDT) Subject: UnboundLocalError problems Message-ID: <637159.47140.qm@web54507.mail.re2.yahoo.com> Hi, I am writing a small script that changes my pidgin status to away when I lock my screen.I'm using the DBUS API for pidgin and gnome-screensaver.Here's the code: #!/usr/bin/env python import dbus, gobject from dbus.mainloop.glib import DBusGMainLoop dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SessionBus() obj = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject") purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface") STATUS_AVAILABLE = 2 STATUS_AWAY = 5 ORIG_TYPE = 0 ORIG_MSG = "" def my_func2(IsEnabled): if IsEnabled: ORIG_TYPE,ORIG_MSG = get_current() set_status(STATUS_AWAY,"I'm not at my desk") else: set_status(ORIG_TYPE,ORIG_MSG) def set_status(kind, message): status = purple.PurpleSavedstatusNew("", kind) purple.PurpleSavedstatusSetMessage(status, message) purple.PurpleSavedstatusActivate(status) def get_current(): typ = purple.PurpleSavedstatusGetType(purple.PurpleSavedstatusGetCurrent()) current = purple.PurpleSavedstatusGetCurrent() msg = purple.PurpleSavedstatusGetMessage(dbus.Int32(current)) return typ,msg bus.add_signal_receiver(my_func2, dbus_interface="org.gnome.ScreenSaver", signal_name="SessionIdleChanged") loop = gobject.MainLoop() loop.run() When I run it,it errors out at : set_status(ORIG_TYPE,ORIG_MSG) giving the error "UnboundLocalError: local variable 'ORIG_TYPE' referenced before assignment" .This happens Aren't ORIG_TYPE and ORIG_MSG global variables? Where am I going wrong?Everything works fine if I set the arguments manually to the set_status function. Regards, SZ Get the name you always wanted with the new y7mail email address. www.yahoo7.com.au/mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From mccredie at gmail.com Wed Jun 11 20:05:22 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 11 Jun 2008 17:05:22 -0700 (PDT) Subject: Simple and safe evaluator References: Message-ID: On Jun 11, 4:38 pm, bvdp wrote: > I'm finding my quest for a safe eval() quite frustrating :) > > Any comments on this: Just forget about getting python to do this and, > instead, grab my set of values (from a user supplied text file) and call > an external program like 'bc' to do the dirty work. I think that this > would avoid someone from embedding os.system("rm ...") in what I thought > would be a math expression and having it maybe do damage? Perhaps I'm > getting too paranoid in my old age. > > I guess this would slow things down a bit, but that is not a big > concern. Bigger concern would be that I'm not sure if 'bc' or whatever > is guaranteed to be on other platforms than *nix. And if I want to be > really paranoid, I could worry that someone had planted a bad 'bc' on > the target. The solution I posted should work and is safe. It may not seem very readable, but it is using Pythons internal parser to parse the passed in string into an abstract symbol tree (rather than code). Normally Python would just use the ast internally to create code. Instead I've written the code to do that. By avoiding anything but simple operators and literals it is guaranteed safe. If you only want numbers you can even remove a bunch of code: [code] import _ast class SafeEvalError(Exception): pass class UnsafeCode(SafeEvalError): pass def num_eval(text): "similar to eval, but only works on numerical values." ast = compile(text, "", 'eval', _ast.PyCF_ONLY_AST) return _traverse(ast.body) def _traverse(ast): if isinstance(ast, _ast.Num): return ast.n elif isinstance(ast, _ast.Expr): return _traverse(ast.value) elif isinstance(ast, _ast.BinOp): if isinstance(ast.op, _ast.Add): return _traverse(ast.left) + _traverse(ast.right) elif isinstance(ast.op, _ast.Sub): return _traverse(ast.left) - _traverse(ast.right) elif isinstance(ast.op, _ast.Div): return _traverse(ast.left) / _traverse(ast.right) elif isinstance(ast.op, _ast.FloorDiv): return _traverse(ast.left) // _traverse(ast.right) elif isinstance(ast.op, _ast.Mod): return _traverse(ast.left) % _traverse(ast.right) elif isinstance(ast.op, _ast.Mult): return _traverse(ast.left) * _traverse(ast.right) elif isinstance(ast.op, _ast.Pow): return _traverse(ast.left) ** _traverse(ast.right) elif isinstance(ast.op, _ast.BitAnd): return _traverse(ast.left) & _traverse(ast.right) elif isinstance(ast.op, _ast.BitOr): return _traverse(ast.left) | _traverse(ast.right) elif isinstance(ast.op, _ast.BitXor): return _traverse(ast.left) ^ _traverse(ast.right) elif isinstance(ast.op, _ast.LShift): return _traverse(ast.left) << _traverse(ast.right) elif isinstance(ast.op, _ast.RShift): return _traverse(ast.left) >> _traverse(ast.right) elif isinstance(ast, _ast.UnaryOp): if isinstance(ast.op, _ast.Invert): return ~_traverse(ast.operand) elif isinstance(ast.op, _ast.USub): return -_traverse(ast.operand) elif isinstance(ast.op, _ast.UAdd): return +_traverse(ast.operand) raise UnsafeCode() [/code] To use: print num_eval("1 + 44 / 3") From jaraco at jaraco.com Thu Jun 12 20:16:52 2008 From: jaraco at jaraco.com (Jason R. Coombs) Date: Thu, 12 Jun 2008 17:16:52 -0700 (PDT) Subject: Wording suggestion for documentation (Data Model) Message-ID: <512da201-973f-4737-a5de-1efa48d84394@8g2000hse.googlegroups.com> #!python """ In the documentation for __del__ (under Python Language Reference/Data Model), the following warning is indicated: Warning [Caveat in 2.6]: Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead. ... That statement appears, however, to be incorrect. Perhaps the warning should be re-worded to say "When __del__() methods are invoked, exceptions that occur during the execution of such methods must be caught and handled within the scope of the __del__() method call. Otherwise unhandled exceptions will be ignored except for a warning printed to sys.stderr instead." For example, """ class X(object): def __del__(self): print 'deleting', self try: raise Exception, "OMG!" except: print 'caught exception, np' print 'made it past the exception' x = X() del x print 'x has been deleted, now what?' """ All this prints something like: deleting <__main__.X object at 0x01BB1A50> caught exception, np made it past the exception x has been deleted, now what? """ # - Jason R. Coombs From __peter__ at web.de Mon Jun 30 06:06:53 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 30 Jun 2008 12:06:53 +0200 Subject: Getting sorting order References: <7cb9ebb7-e722-41e1-bdf2-693954a21b92@j22g2000hsf.googlegroups.com> Message-ID: leodp wrote: > >> Or provide a better explanation and an example. Do you mean something >> like this? >> > > Hi Peter, > a small example: > > master=[1,4,3,2] > slave1=['d','c','b','a'] > slave2=[1,2,3,4] > > master.sort() # this is ok, but does not return infos on how the list > was sorted > slave1.sort(key=_maybe_something_here_referring_to_master_) > slave2.sort(key=_maybe_something_here_referring_to_master_) > > Then I should get: > master=[1,2,3,4] > slave1=['d','a','b','c'] > slave2=[1,4,3,2] > > > Hope it is more clear now. > Thanks, leodp You need a helper list (called master_index in the example below): >>> master=[1,4,3,2] >>> slave1=['d','c','b','a'] >>> slave2=[1,2,3,4] >>> master_index = range(len(master)) >>> master_index.sort(key=master.__getitem__) >>> master[:] = [master[i] for i in master_index] >>> slave1[:] = [slave1[i] for i in master_index] >>> slave2[:] = [slave2[i] for i in master_index] >>> master [1, 2, 3, 4] >>> slave1 ['d', 'a', 'b', 'c'] >>> slave2 [1, 4, 3, 2] If you don't care about list object identity you can use master = [...] instead of master[:] = [...] etc. Peter From martin at v.loewis.de Sun Jun 15 12:47:16 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 15 Jun 2008 18:47:16 +0200 Subject: Making wxPython a standard module? In-Reply-To: <0bb2d727-4bd8-4baf-be34-716daec1ddff@d1g2000hsg.googlegroups.com> References: <48512f69$0$11262$c3e8da3@news.astraweb.com> <0bb2d727-4bd8-4baf-be34-716daec1ddff@d1g2000hsg.googlegroups.com> Message-ID: <48554794.3050203@v.loewis.de> > I know there must be at least a few very solid answers to this, but, > just to hear it from the Pythonistas: Why can't there be several GUI > toolkits on the standard library? Why do you think there can't be several GUI toolkits in the standard library? There is nothing that prohibits such a thing per se. See my other message on why wxPython isn't part of the standard library: it hasn't been contributed, yet. Regards, Martin From phillip.oldham at gmail.com Fri Jun 13 22:25:50 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Fri, 13 Jun 2008 19:25:50 -0700 (PDT) Subject: Best way to make a number of tests against an object('s attributes) with absence of switch statement? Message-ID: <15aaceb5-2f9c-4891-98c2-fe7ac3e19f1c@k37g2000hsf.googlegroups.com> What would be the optimal/pythonic way to subject an object to a number of tests (based on the object's attributes) and redirect program flow? Say I had the following: pets[0] = {'name': 'fluffy', 'species': 'cat', 'size': 'small'} pets[1] = {'name': 'bruno', 'species': 'snake', 'size': 'small'} pets[2] = {'name': 'rex', 'species': 'dog', 'size': 'large'} What I'd like to do is loop through 'pets', and test each object. Some of the tests I'd like to perform are: Is the size 'small' and species not 'dog'? Is the species 'cat' and name 'fluffy'? Is the species not 'dog' or 'cat'? In PHP I'd use a switch statement similar to the following: foreach( $pets as $pet) { switch(true) { case ( $pet['size'] === 'small' && $pet['species'] !== 'dog' ): // do something break; // etc... } } Now, I understand from a bit of googling that python doesn't have a switch statement, and because of this people rely on python's polymorphism. Thats great, but I've yet to come across a decent example which make a "click". Any thoughts on how to proceed? From jaywgraves at gmail.com Fri Jun 6 16:35:40 2008 From: jaywgraves at gmail.com (jay graves) Date: Fri, 6 Jun 2008 13:35:40 -0700 (PDT) Subject: File-writing not working in Windows? References: <80a7b951-591b-41a2-b76c-f97d75db0dad@25g2000hsx.googlegroups.com> <08442be2-13c0-44fc-add4-4907c1202f96@r66g2000hsg.googlegroups.com> <300fece5-da15-4323-9b3a-f49b90d9c74b@34g2000hsh.googlegroups.com> <1f2ddd19-bfd5-4d6b-984b-42e382704215@d1g2000hsg.googlegroups.com> <225a6635-256f-4dd1-b470-58de72d10345@p25g2000hsf.googlegroups.com> Message-ID: <1aa4ebfa-272c-439c-ba18-3e358fce268c@25g2000hsx.googlegroups.com> On Jun 6, 3:19 pm, tda... at gmail.com wrote: > This did not make a difference in my script. However, I did what you > suggested, and tried the simple script it Windows, and it works as it > should. > (It's really annoying because it works on the Mac and Linux! (I just > tested my script on the Mac as well.) It only doesn't work on > Windows, though clearly the file processing I am doing SHOULD work.) Is there a global exception handler somewhere in your code that could be eating an error that only happens on windows? (something weird like file permissions.) I'm really at a loss. Sorry. ... Jay From bearophileHUGS at lycos.com Wed Jun 4 19:37:08 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 4 Jun 2008 16:37:08 -0700 (PDT) Subject: Tuples part 2 References: Message-ID: <295215b0-83b4-46a7-ac94-ed94be57ccad@27g2000hsf.googlegroups.com> victor.hera... at gmail.com: Do you mean something like this? (notice the many formatting differences, use a formatting similar to this one in your code) coords = [] for i in xrange(1, 5): for j in xrange(1, 5): for k in xrange(1, 2): coords.append( (i, j, k) ) coords *= 10 print coords Bye, bearophile From sjmachin at lexicon.net Wed Jun 4 10:59:38 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 05 Jun 2008 00:59:38 +1000 Subject: Zipfile module errors In-Reply-To: <07ba0098-e073-46b9-8240-4915c4b5ad4d@c65g2000hsa.googlegroups.com> References: <1bea3f60-5866-4ecb-a2a2-51f7130f03c8@y21g2000hsf.googlegroups.com> <8a2a1e8d-cde2-45f4-9329-407e0c2980c8@l28g2000prd.googlegroups.com> <07ba0098-e073-46b9-8240-4915c4b5ad4d@c65g2000hsa.googlegroups.com> Message-ID: <4846ADDA.3@lexicon.net> jwesonga wrote: > I've added the line to the script, added a zipped file into the > folder. I've made sure the file exists. The error is now this: Please get some clues: (1) Don't reply off-list unless specifically invited. (2) Don't top-post. (3) Do read and try to understand *all* of each reply that you get ... e.g. """ P.S. Printing the contents of filelist immediately after it's been created might be a good idea. You say "pick the zipped files" but the only condition I see is a test using os.path.isdir. """ (4) Do read and try to understand the output from your own script, e.g. > > [jwesonga at web38 processor_files]$ python2.4 processor3.py > trying to unzip '/home/jwesonga/received/log.txt' whose size is 752 > bytes Doesn't that tell you anything? Like you are trying to unzip your own logfile?? > Traceback (most recent call last): > File "processor3.py", line 125, in ? > unzip(infolder) > File "processor3.py", line 54, in unzip > zfile = zipfile.ZipFile(one,'r') > File "/usr/lib/python2.4/zipfile.py", line 210, in __init__ > self._GetContents() > File "/usr/lib/python2.4/zipfile.py", line 230, in _GetContents > self._RealGetContents() > File "/usr/lib/python2.4/zipfile.py", line 242, in _RealGetContents > raise BadZipfile, "File is not a zip file" > zipfile.BadZipfile: File is not a zip file > > This is strange because I can see the zipped file inside the folder / > home/jwesonga/received what could be the problem? > > On Jun 4, 2:45 pm, John Machin wrote: >> On Jun 4, 8:06 pm, jwesonga wrote: >> >>> Hi, >>> I have a python script that supposed to go through a folder, pick the >>> zipped files, unzip them and process the data inside. I'm not sure >>> where i'm going wrong with this script because it all seems correct: >> Nothing is ever as it seems. Let's try to work backwards from the >> error message ... and we don't need your magnificent script, just the >> traceback will do for now, so: >> >> [ big snip] >> >> >> >>> The error I keep getting is: >>> Traceback (most recent call last): >>> File "processor3.py", line 124, in ? >>> unzip(infolder) >>> File "processor3.py", line 53, in unzip >> The error says that you are trying to seek 22 bytes backwards from the >> end of a file that you presume is a zip file, and this is deemed to be >> invalid. Hypotheses: (1) zipfile.py is buggy (2) your file is less >> than 22 bytes long. Let's park hypothesis 1 for the moment. Insert the >> following code before the call to zipfile.ZipFile: >> >> print "trying to unzip %r whose size is %d bytes" \ >> % (one, os.stat(one).st_size) >> >> and tell us your conclusions. >> >>> zfile = zipfile.ZipFile(one,'r') >>> File "/usr/lib/python2.4/zipfile.py", line 210, in __init__ >>> self._GetContents() >>> File "/usr/lib/python2.4/zipfile.py", line 230, in _GetContents >>> self._RealGetContents() >>> File "/usr/lib/python2.4/zipfile.py", line 240, in _RealGetContents >>> endrec = _EndRecData(fp) >>> File "/usr/lib/python2.4/zipfile.py", line 83, in _EndRecData >>> fpin.seek(-22, 2) # Assume no archive comment. >>> IOError: [Errno 22] Invalid argument >> P.S. Printing the contents of filelist immediately after it's been >> created might be a good idea. You say "pick the zipped files" but the >> only condition I see is a test using os.path.isdir. >> >> HTH, >> John > > > > > From johnjsal at gmailNOSPAM.com Sun Jun 8 22:40:39 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sun, 08 Jun 2008 22:40:39 -0400 Subject: Do this as a list comprehension? In-Reply-To: References: <4848b213$0$25711$607ed4bc@cv.net><484ad07b$0$25721$607ed4bc@cv.net> <8d7c0912-422f-4480-a034-078f9dbcae24@2g2000hsn.googlegroups.com> Message-ID: <484c9830$0$5009$607ed4bc@cv.net> Mensanator wrote: > On Jun 8, 3:19?am, "Terry Reedy" wrote: >> "Mensanator" wrote in message >> >> news:8d7c0912-422f-4480-a034-078f9dbcae24 at 2g2000hsn.googlegroups.com... >> | On Jun 7, 6:43?pm, "Terry Reedy" wrote: >> | > zip(range(9,2000000000), iterable) >> | >> | Oh, dear. You didn't actually try this, did you? >> >> Works fine in Py3, which is what I use now. > > You really ARE cruel to the newbies, aren't you? > > Don't you think it would have been appropriate > to attach a large red label: WARNING! PY3! Heh heh, don't worry. Every time I see a range function, I immediately think "creates a list". Not sure how I got into that habit, but it happens every time! :) From sjmachin at lexicon.net Wed Jun 25 19:03:52 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 25 Jun 2008 16:03:52 -0700 (PDT) Subject: struct.pack behavior References: Message-ID: On Jun 26, 9:00 am, "Steven Clark" wrote: > Can anyone explain to me why > struct.pack('HB',1,2) gives 3 bytes, whereas struct.pack('BH',1,2) > gives 4 bytes? > Alignment -- read the manual. From tnleeuw at gmail.com Wed Jun 11 05:22:27 2008 From: tnleeuw at gmail.com (Tim van der Leeuw) Date: Wed, 11 Jun 2008 11:22:27 +0200 Subject: Python regex question Message-ID: Hi, I'm trying to create a regular expression for matching some particular XML strings. I want to extract the contents of a particular XML tag, only if it follows one tag, but not follows another tag. Complicating this, is that there can be any number of other tags in between. So basically, my regular expression should have 3 parts: - first match - any random text, that should not contain string '.*?(?P\d+)' (hopefully without typos) Here '' is my first match, and '(?P\d+)' is my second match. In this expression, I want to change the generic '.*?', which matches everything, with something that matches every string that does not include the substring ' From bsagert at gmail.com Mon Jun 16 17:56:39 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Mon, 16 Jun 2008 14:56:39 -0700 (PDT) Subject: Please explain Python "__whatever__" construct. Message-ID: <02c8f509-2889-433b-a548-62ead677bd19@p39g2000prm.googlegroups.com> After a couple of weeks studying Python, I already have a few useful scripts, including one that downloads 1500 Yahoo stock quotes in 6 seconds. However, many things are puzzling to me. I keep on seeing things like "__main__" in scripts. A more obscure example would be "__add__" used in string concatenation. For example, I can use "Hello "+"world (or just "Hello" "world") to join those two words. But I can also use "Hello ".__add__("world"). When and why would I ever use "__main__" or the many other "__whatever__" constructs? From swapna.nitw at gmail.com Mon Jun 23 07:57:03 2008 From: swapna.nitw at gmail.com (swapna mudavath) Date: Mon, 23 Jun 2008 17:27:03 +0530 Subject: xml to mysql (vice versa ) too Message-ID: Hi, I need to write a python script to store data which is in XML to MYSQL and even vice versa.... what should be the approach? i am able to establish a connection,create tables and insert data ..... but how to read an xml file and store in MYSQL.... my XML structure is like . .... ... can somebody please help me......i am really confused!!!!!! thanks in advance :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From metalkeys404 at gmail.com Fri Jun 27 21:12:23 2008 From: metalkeys404 at gmail.com (Ampedesign) Date: Fri, 27 Jun 2008 18:12:23 -0700 (PDT) Subject: lxml and links Message-ID: I'm trying to extract all the links on a page with lxml. Ideally, I would like it to return me a list of hrefs of each link on the page, in a list. How would I go about doing this? From madhav.bnk at gmail.com Fri Jun 27 04:23:07 2008 From: madhav.bnk at gmail.com (madhav) Date: Fri, 27 Jun 2008 01:23:07 -0700 (PDT) Subject: Email Bounce Detection References: Message-ID: <164ab83d-311b-40ce-a112-c8a8cb9d077d@t12g2000prg.googlegroups.com> On Jun 27, 12:34?pm, Maric Michaud wrote: > Le Friday 27 June 2008 09:03:15 madhav, vous avez ?crit?: > > > Hello everybody, I need a mechanism to detect email bounces. I tried > > browsing through smtplib implementation and found not helpful in this > > case. Actually it is said in the documentation that if a mail is sent > > to say: "somerandomn... at randomorg.com", then "_send()" in the > > SMTPConnection class returns 550(Unknown recceipient). I checked the > > same but its not returning 550 and return 250(receipient ok). > > This is not the same scenario, the SMTP server that will respond 550 is the MX > for the domain, if you send your mails using an outgoing SMTP server, it > can't know in advance the list of remote adressesbut will bounce your message > when receiving the 550 from the remote MX. > > > Later, I tried getting the smtp error code from the mail body of a > > bounced msg. the "Message" class doesnot have any error code attribute > > by default. We need to get it from the mailbody(by regex ing), which i > > think is not a valid solution, as "550" can occur anywhere in the body > > of any message otherthan the bounced msg also. > > Please help me regarding this. > > Thanks in advance. > > Bounces are multipart messages easily parsed with the email package of the > stdlib (dont' use regexes here). > > Abounce message is of type : > > Content-Type: multipart/report; > ? report-type=delivery-status; ? > > a delivery-status imply that one of the subpart of the message is a > message/delivery-status with all needed infos set in the headers. This one is > taken from a real example : > > Content-Description: Delivery report > Content-Type: message/delivery-status > > Reporting-MTA: dns; aristote.info > X-Postfix-Queue-ID: 1D07D1409FF > X-Postfix-Sender: rfc822; ma... at aristote.info > Arrival-Date: Fri, 27 Jun 2008 09:10:14 +0200 (CEST) > > Final-Recipient: rfc822; unknownadr... at nerim.net > Original-Recipient: rfc822;unknownadr... at nerim.net > Action: failed > Status: 5.0.0 > Remote-MTA: dns; tyrande.nerim.net > Diagnostic-Code: smtp; 550 : Recipient address > rejected: > ? ? User unknown in local recipient table > > So, for example : > > >>>[48]: import email > >>>[49]: bounce = email.message_from_string(open('ex.eml').read()) > >>>[50]: bounce.get_content_type() > > ...[50]: 'multipart/report' > > >>>[51]: > >>>[52]: for i in bounce.get_payload() : > > ? ?....: ? ?if i.get_content_type() == 'message/delivery-status' : > ? ?....: ? ? ? ? print i.get_payload()[1]['status'] > ? ?....: > ? ?....: > 5.0.0 > > -- > _____________ > > Maric Michaud Thankyou somuch Maric. Will try the approach you have mentioned. :) From rhamph at gmail.com Wed Jun 11 15:41:27 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Wed, 11 Jun 2008 12:41:27 -0700 (PDT) Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <6e6df35e-e641-44d9-9f56-c0732306eec2@q27g2000prf.googlegroups.com> <13db98b5-ed2e-45ef-97ec-ad3caeeed10e@j1g2000prb.googlegroups.com> <074caf4a-de1e-4290-b688-30148786952c@z72g2000hsb.googlegroups.com> <776fd3e3-7c2e-45b1-8196-7cde93e72da3@w1g2000prd.googlegroups.com> <98d541c3-e974-4a8c-961c-2a59f6bf32ea@v26g2000prm.googlegroups.com> <4beb7bc4-61ae-4c61-b182-270ec1dd06cf@25g2000hsx.googlegroups.com> Message-ID: <30a1ac0c-a8a3-418c-a40b-4859d13c81c5@x19g2000prg.googlegroups.com> On Jun 11, 1:17 pm, Fuzzyman wrote: > On Jun 11, 6:49 pm, Rhamphoryncus wrote: > > On Jun 11, 7:56 am, Fuzzyman wrote: > > > On Jun 11, 6:56 am, Rhamphoryncus wrote: > > > > I'm not saying it can't be made to work in your specific case - it > > > > likely does work well for you. I'm saying it can't work *in > > > > general*. Stretching it out for general use turns those little cracks > > > > into massive canyons. A language needs a general mechanism that does > > > > work - such as a polite cancellation API. > > > > Neither *works in general* - polite cancellation *doesn't* work for > > > our us. That's my point - you probably want *both* for different use > > > cases. :-) > > > Yeah, but mine's less icky. ;) > > But requires more code. :-) Both require significant support from the implementation, and you're not the one volunteering to write it (I am). Besides, they're complementary, so we should have both anyway. The question is how best to fit them together. > > I think the ideal for you would be a separate process. I'd also > > suggest a restricted VM only in a thread, but that probably wouldn't > > work for those long-running .NET APIs. Now, if those long- > > running .NET APIs did polite cancellation, then you could combine that > > with a restricted VM to get what you need. > > No - we need to pull a large object graph *out* of the calculation > (with no guarantee that it is even serializable) and the overhead for > marshalling that puts using multiple processes out of the running. Ouch. So if it fails you want it isolated and killed, but if it succeeds you want to share it with the rest of the program. > What we *want* is what we've got! And it works very well... None of > the problems you predict. :-) Which points to an unknown mechanism protecting the vulnerable code, such as using a different language. I think we've run out of material to discuss. We're about 80% in agreement, with a 20% disagreement on philosophy. From arslanburney at gmail.com Fri Jun 13 06:11:31 2008 From: arslanburney at gmail.com (arslanburney at gmail.com) Date: Fri, 13 Jun 2008 03:11:31 -0700 (PDT) Subject: Plotting Graphs + Bestfit lines References: <1a919a2b-6430-4e2e-a190-2e00e43a6138@25g2000hsx.googlegroups.com> <022d382b-0b7b-4757-855a-f07019791fcc@d45g2000hsc.googlegroups.com> <05e67e40-db9c-4d85-94c1-f0e31dd5da38@27g2000hsf.googlegroups.com> Message-ID: Got the problem solved finally. Missed out theses two lines: plot1 = Gnuplot.PlotItems.Data(original, title="Original") plot2 = Gnuplot.PlotItems.Data(expected, title="Expected") plot3 = Gnuplot.PlotItems.Data(actual, title="Acutal") plot4 = Gnuplot.PlotItems.Func('%f * x+%f'%(bf1[0],bf1[1]), title = "Expected Best Fit") plot5 = Gnuplot.PlotItems.Func('%f * x+%f'%(bf2[0],bf2[1]), title = "Actual Best Fit") The last 2 ones.... thnx nyways From george.sakkis at gmail.com Tue Jun 10 23:33:44 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 10 Jun 2008 20:33:44 -0700 (PDT) Subject: Producer-consumer threading problem Message-ID: <1f8adb7a-1257-4a56-b69a-557115c60050@k37g2000hsf.googlegroups.com> I'd like some feedback on a solution to a variant of the producer- consumer problem. My first few attempts turned out to deadlock occasionally; this one seems to be deadlock-free so far but I can't tell if it's provably correct, and if so, whether it can be simplified. The generic producer-consumer situation with unlimited buffer capacity is illustrated at http://docs.python.org/lib/condition-objects.html. That approach assumes that the producer will keep producing items indefinitely, otherwise the consumer ends up waiting forever. The extension to the problem I am considering requires the consumer to be notified not only when there is a new produced item, but also when there is not going to be a new item so that it stops waiting. More specifically, I want a generator (or iterator class) with the following generic signature: def iter_consumed(items, produce, consume): '''Return an iterator over the consumed items. :param items: An iterable of objects to be `produce`()d and `consume`()d. :param produce: A callable `f(item)` that produces a single item; the return value is ignored. What "produce" exactly means is application- specific. :param consume: A callable `f()` that consumes a previously produced item and returns the consumed item. What "consume" exactly means is application-specific. The only assumption is that if `produce` is called `N` times, then the next `N` calls to `consume` will (eventually, though not necessarily immediatelly) return, i.e they will not block indefinitely. ''' One straightforward approach would be to serialize the problem: first produce all `N` items and then call consume() exactly N times. Although this makes the solution trivial, there are at least two shortcomings. First, the client may have to wait too long for the first item to arrive. Second, each call to produce() typically requires resources for the produced task, so the maximum resource requirement can be arbitrarily high as `N` increases. Therefore produce() and consume() should run concurrently, with the invariant that the calls to consume are no more than the calls to produce. Also, after `N` calls to produce and consume, neither should be left waiting. I pasted my current solution at http://codepad.org/FXF2SWmg. Any feedback, especially if it has to do with proving or disproving its correctness, will be appreciated. George From alexnbryan at gmail.com Sun Jun 29 12:50:16 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sun, 29 Jun 2008 09:50:16 -0700 (PDT) Subject: using urllib2 In-Reply-To: <25d97d35-6d28-43ef-9e54-d8ae7a03bc8f@b1g2000hsg.googlegroups.com> References: <18150669.post@talk.nabble.com> <200806271227.17081.maric@aristote.info> <25d97d35-6d28-43ef-9e54-d8ae7a03bc8f@b1g2000hsg.googlegroups.com> Message-ID: <18182864.post@talk.nabble.com> No I figured it out. I guess I never knew that you aren't supposed to split a url like "http://www.goo\ gle.com" But I did and it gave me all those errors. Anyway, I had a question. On the original code you had this for loop: for tabs in soup.findAll('table', {'class': 'luna-Ent'}): yield tabs.findAll('td')[-1].contents[-1].string I hate to be a pain, but I was looking at the BeautifulSoup docs, and found the findAll thing. But I want to know why you put "for tabs," also why you need the "'table', {'class': 'luna-Ent'}):" Like why the curly braces and whatnot? Jeff McNeil-2 wrote: > > On Jun 27, 10:26?pm, Alexnb wrote: >> Okay, so I copied your code(and just so you know I am on a mac right now >> and >> i am using pydev in eclipse), and I got these errors, any idea what is >> up? >> >> Traceback (most recent call last): >> ? File >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", >> line 14, in >> ? ? print list(get_defs("cheese")) >> ? File >> "/Users/Alex/Documents/workspace/beautifulSoup/src/firstExample.py", >> line 9, in get_defs >> ? ? dictionary.reference.com/search?q=%s' % term)) >> ? File >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib.py", >> line 82, in urlopen >> ? ? return opener.open(url) >> ? File >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib.py", >> line 190, in open >> ? ? return getattr(self, name)(url) >> ? File >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib.py", >> line 325, in open_http >> ? ? h.endheaders() >> ? File >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/httplib.py", >> line 856, in endheaders >> ? ? self._send_output() >> ? File >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/httplib.py", >> line 728, in _send_output >> ? ? self.send(msg) >> ? File >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/httplib.py", >> line 695, in send >> ? ? self.connect() >> ? File >> "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/httplib.py", >> line 663, in connect >> ? ? socket.SOCK_STREAM): >> IOError: [Errno socket error] (8, 'nodename nor servname provided, or not >> known') >> >> Sorry if it is hard to read. >> >> >> >> Jeff McNeil-2 wrote: >> >> > Well, what about pulling that data out using Beautiful soup? If you >> > know the table name and whatnot, try something like this: >> >> > #!/usr/bin/python >> >> > import urllib >> > from BeautifulSoup import BeautifulSoup >> >> > def get_defs(term): >> > ? ? soup = BeautifulSoup(urllib.urlopen('http:// >> > dictionary.reference.com/search?q=%s' % term)) >> >> > ? ? for tabs in soup.findAll('table', {'class': 'luna-Ent'}): >> > ? ? ? ? yield tabs.findAll('td')[-1].contents[-1].string >> >> > print list(get_defs("frog")) >> >> > jeff at martian:~$ python test.py >> > [u'any tailless, stout-bodied amphibian of the order Anura, including >> > the smooth, moist-skinned frog species that live in a damp or >> > semiaquatic habitat and the warty, drier-skinned toad species that are >> > mostly terrestrial as adults. ', u' ', u' ', u'a French person or a >> > person of French descent. ', u'a small holder made of heavy material, >> > placed in a bowl or vase to hold flower stems in position. ', u'a >> > recessed panel on one of the larger faces of a brick or the like. ', >> > u' ', u'to hunt and catch frogs. ', u'French or Frenchlike. ', u'an >> > ornamental fastening for the front of a coat, consisting of a button >> > and a loop through which it passes. ', u'a sheath suspended from a >> > belt and supporting a scabbard. ', u'a device at the intersection of >> > two tracks to permit the wheels and flanges on one track to cross or >> > branch from the other. ', u'a triangular mass of elastic, horny >> > substance in the middle of the sole of the foot of a horse or related >> > animal. '] >> >> > HTH, >> >> > Jeff >> >> > On Jun 27, 7:28?pm, Alexnb wrote: >> >> I have read that multiple times. It is hard to understand but it did >> help >> >> a >> >> little. But I found a bit of a work-around for now which is not what I >> >> ultimately want. However, even when I can get to the page I want lets >> >> say, >> >> "Http://dictionary.reference.com/browse/cheese", I look on firebug, >> and >> >> extension and see the definition in javascript, >> >> >> >> >> >> >> >> >> >> >> >> >> >> Jeff McNeil-2 wrote: >> >> >> > the problem being that if I use code like this to get the html of >> that > >> >> > page in python: >> >> >> > response = urllib2.urlopen("the webiste....") >> >> > html = response.read() >> >> > print html >> >> >> > then, I get a bunch of stuff, but it doesn't show me the code with >> the >> >> > table that the definition is in. So I am asking how do I access this >> >> > javascript. Also, if someone could point me to a better reference >> than >> >> the >> >> > last one, because that really doesn't tell me much, whether it be a >> >> book >> >> > or anything. >> >> >> > I stumbled across this a while back: >> >> >http://www.voidspace.org.uk/python/articles/urllib2.shtml. >> >> > It covers quite a bit. The urllib2 module is pretty straightforward >> >> > once you've used it a few times. ?Some of the class naming and >> whatnot >> >> > takes a bit of getting used to (I found that to be the most >> confusing >> >> > bit). >> >> >> > On Jun 27, 1:41 pm, Alexnb wrote: >> >> >> Okay, I tried to follow that, and it is kinda hard. But since you >> >> >> obviously >> >> >> know what you are doing, where did you learn this? Or where can I >> >> learn >> >> >> this? >> >> >> >> Maric Michaud wrote: >> >> >> >> > Le Friday 27 June 2008 10:43:06 Alexnb, vous avez ?crit : >> >> >> >> I have never used the urllib or the urllib2. I really have >> looked >> >> >> online >> >> >> >> for help on this issue, and mailing lists, but I can't figure >> out >> >> my >> >> >> >> problem because people haven't been helping me, which is why I >> am >> >> >> here! >> >> >> >> :]. >> >> >> >> Okay, so basically I want to be able to submit a word to >> >> >> dictionary.com >> >> >> >> and >> >> >> >> then get the definitions. However, to start off learning >> urllib2, I >> >> >> just >> >> >> >> want to do a simple google search. Before you get mad, what I >> have >> >> >> found >> >> >> >> on >> >> >> >> urllib2 hasn't helped me. Anyway, How would you go about doing >> >> this. >> >> >> No, >> >> >> >> I >> >> >> >> did not post the html, but I mean if you want, right click on >> your >> >> >> >> browser >> >> >> >> and hit view source of the google homepage. Basically what I >> want >> >> to >> >> >> know >> >> >> >> is how to submit the values(the search term) and then search for >> >> that >> >> >> >> value. Heres what I know: >> >> >> >> >> import urllib2 >> >> >> >> response = urllib2.urlopen("http://www.google.com/") >> >> >> >> html = response.read() >> >> >> >> print html >> >> >> >> >> Now I know that all this does is print the source, but thats >> about >> >> all >> >> >> I >> >> >> >> know. I know it may be a lot to ask to have someone show/help >> me, >> >> but >> >> >> I >> >> >> >> really would appreciate it. >> >> >> >> > This example is for google, of course using pygoogle is easier in >> >> this >> >> >> > case, >> >> >> > but this is a valid example for the general case : >> >> >> >> >>>>[207]: import urllib, urllib2 >> >> >> >> > You need to trick the server with an imaginary User-Agent. >> >> >> >> >>>>[208]: def google_search(terms) : >> >> >> > ? ? return >> >> >> urllib2.urlopen(urllib2.Request("http://www.google.com/search?" >> >> >> > + >> >> >> > urllib.urlencode({'hl':'fr', 'q':terms}), >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? >> >> ?headers={'User-Agent':'MyNav >> >> >> > 1.0 >> >> >> > (compatible; MSIE 6.0; Linux'}) >> >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ? ).read() >> >> >> > ? ?.....: >> >> >> >> >>>>[212]: res = google_search("python & co") >> >> >> >> > Now you got the whole html response, you'll have to parse it to >> >> recover >> >> >> > datas, >> >> >> > a quick & dirty try on google response page : >> >> >> >> >>>>[213]: import re >> >> >> >> >>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('

    > >> >> class=r>.*?

    ', >> >> >> > res) ] >> >> >> > ...[229]: >> >> >> > ['Python Gallery', >> >> >> > ?'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des >> Monty >> >> >> ...', >> >> >> > ?'Re: os x, panther, python & co: msg#00041', >> >> >> > ?'Re: os x, panther, python & co: msg#00040', >> >> >> > ?'Cardiff Web Site Design, Professional web site design services >> >> ...', >> >> >> > ?'Python Properties', >> >> >> > ?'Frees < Programs < Python < Bin-Co', >> >> >> > ?'Torb: an interface between Tcl and CORBA', >> >> >> > ?'Royal Python Morphs', >> >> >> > ?'Python & Co'] >> >> >> >> > -- >> >> >> > _____________ >> >> >> >> > Maric Michaud >> >> >> > -- >> >> >> >http://mail.python.org/mailman/listinfo/python-list >> >> >> >> -- >> >> >> View this message in >> >> >> >> context:http://www.nabble.com/using-urllib2-tp18150669p18160312.html >> >> >> Sent from the Python - python-list mailing list archive at >> Nabble.com. >> >> >> > -- >> >> >http://mail.python.org/mailman/listinfo/python-list >> >> >> -- >> >> View this message in >> >> context:http://www.nabble.com/using-urllib2-tp18150669p18165634.html >> >> Sent from the Python - python-list mailing list archive at Nabble.com. >> >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> -- >> View this message in >> context:http://www.nabble.com/using-urllib2-tp18150669p18166785.html >> Sent from the Python - python-list mailing list archive at Nabble.com. > > I tried it on a Mac after reading your reply and I had no issues. Are > you certain you copied it correctly? > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/using-urllib2-tp18150669p18182864.html Sent from the Python - python-list mailing list archive at Nabble.com. From Lie.1296 at gmail.com Sun Jun 29 05:53:40 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 29 Jun 2008 02:53:40 -0700 (PDT) Subject: help debugging noob code - converting binary data to images... References: <56955a42-155c-4c37-9bf6-5a99cadb5c79@l42g2000hsc.googlegroups.com> Message-ID: On Jun 29, 4:47?pm, Lie wrote: > On Jun 29, 11:18?am, la... at portcommodore.com wrote: > > > > > Ok I'm a Python noob, been doing OK so far, working on a data > > conversion program and want to create some character image files from > > an 8-bit ROM file. > > > Creating the image I've got down, I open the file and use TK to draw > > the images... but > > > 1) ?It does not seem to end (running in IDLE), I have to kill the > > process to retry it seems tkinter does not close(?) > > > 2) Once I added the Image module open won't open my binary file > > (complains its not an image file, which is isnt.) ?I am sure I need to > > prefix open with something but I can't seem to find an example of how > > to word it, > > > Below is the code (if it is lousy its because I've mainly been > > borrowing by examples as I go...) Any suggestions are gretly > > appreciated. > > > #!/usr/local/bin/python > > > from Tkinter import * > > from string import * > > from Image import * > > DON'T DO THAT... > > You're importing everything to the current namespace and this corrupts > the current namespace, specifically the 'open' function inside > Image.open would shadow the built-in 'open' function. > > use: > import Tkinter > import string > import Image > > There are use cases where doing 'from blah import *' is useful, such > as importing constants, but in general try to avoid importing > everything to current namespace. > > > root = Tk() > > root.title('Canvas') > > If you used 'import Tkinter', you'd have to change that code to: > root = Tkinter.Tk() > > > #open commodore Cset rom > > cset ?= open("chargen","r") > > Because you shadowed the built-in 'open' with the 'from Image import > *', this would call Image.open instead of the built-in open. > > > canvas = Canvas(width=16, height=16, bg='white') > > If you used 'import Tkinter', you'd have to change that code to: > canvas = Tkinter.Canvas(...) > > > canvas.pack(expand=YES, fill=BOTH) > > > # character size factor > > size = 2 > > > # read all 512 characters from ROM > > for cchar in range(0, 511, 1): > > You can use this instead: > for cchar in range(511): > > but beware, this creates range with length 511 (so do the original > range), which means you're lacking on space for the last char. > You probably wanted this instead: > for cchar in range(512): > > But again, python can loop directly over string/list/file, etc, so > this might be best: > for char in cset.read(): > > > ? ? #draw line > > ? ? while charline < 8: > > ? ? ? ? position = 0 > > ? ? ? ? x = cset.read(1) > > ? ? ? ? ch = ord(x) > > ? ? ? ? # draw pixels > > ? ? ? ? while position < 8: > > ? ? ? ? ? ? if ch & ( 2 ** position ): > > ? ? ? ? ? ? ? ? xp = 1+(7-position)*size > > ? ? ? ? ? ? ? ? yp = 1+charline*size > > ? ? ? ? ? ? ? ? canvas.create_rectangle(xp,yp,xp+size,yp+size, > > fill='black', width=0) > > ? ? ? ? ? ? position += 1 > > Since you're planning to use Image module (from PIL/Python Imaging > Library) why not use functions from Image instead to create the image. > The format of the file you're using seems to be RAW format (i.e. > simple uncompressed bitmap, without any kinds of header). That means > Image.fromstring() should work. > > > ? ? ? ? charline += 1 > > ? ? #save character image > > ? ? outfile = "/home/mydir/work/char"+zfill(cchar,3)+".png" > > ? ? canvas.save(outfile,"png") > > ? ? #clear canvas for next char... > > ? ? canvas.create_rectangle(1,1,size*8,size*8, fill='white', width=0) > > root.mainloop() > > btw, PIL Handbook is a good tutorial/reference for Python Imaging Library: http://www.pythonware.com/library/pil/handbook/index.htm for info on raw mode: http://www.pythonware.com/library/pil/handbook/decoder.htm From timothywayne.cook at gmail.com Thu Jun 19 14:56:47 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Thu, 19 Jun 2008 15:56:47 -0300 Subject: Python Package Construction Message-ID: <1213901807.2875.95.camel@localhost.localdomain> Hi All, I would like feedback on the proper/best 'Pythonic' approach. This is a rather subjective question. Where is the trade-off between package name lengths and faithfulness to the specifications? [Discussion follows] I am implementing a set of specifications for healthcare IT for Python programmers to be able to develop interoperable healthcare applications. I am using ZCA (aka.Zope3) extensively. My desire is to implement the specs as faithfully as possible for two reasons: 1) teachability - how easy/difficult is it to teach the framework and specifications to new developers? 2) maintainability - which approach, if either, will make it easier to maintain the framework if/when the specifications change? My first pass was to develop a skeleton of the specs using Interfaces from the ZCA approach and then the implementations following the document structure of the specs. The specs are available via SVN at: http://www.openehr.org/svn/specification/TRUNK/publishing/architecture/ It is best to probably use real examples. Following the document structure for packaging AND using the ZCA convention of having a sub-directory for interfaces caused massive circular import issues due to some classes being used in the interface definition of classes inside the same interface file being imported into the implementation file. If that sounds confusing; it is. It was confusing to write too. :-) If anyone has questions I'll try to expand. It is best to probably use specific, real examples. http://www.openehr.org/svn/specification/TRUNK/publishing/architecture/rm/data_types_im.pdf (note class names are converted from the upper case, underscore separated style to CamelCase) The package openehr.rm.datatypes.text defines the implementation class CodePhrase. The associated interface file openehr.rm.datatypes.interfaces.text needed CodePhrase as an attribute type in DvCodedText and TermMapping needs both CodePhrase and DvCodedText. This quickly got out of control. So my solution to solving the circular imports is to take each interface and implementation and put them into one file. Research tells me that this is probably the second mostly popular ZCA approach. So, ICodePhrase and CodePhrase are now in openehr/rm/datatypes/codephrase.py, DvCodeText and IDvCodedText in openehr/rm/datatypes/dvcodedtext.py, etc. But wait, now I don't have a 'text package'. So if codephrase.py and dvcodedtext.py were in openehr/rm/datatypes/text/ that would solve the problem. BUT! Throughout the specs many of the names are VERY long already. Adding another package name that is from 4 - 15 (or more) characters long adds to the length of already long import statements, i.e. (sorry for the email line wraps) from openehr.am.archetype.creferenceobject import ICReferenceObject,CReferenceObject should really be from openehr.am.archetype.constraintmodel.creferenceobject import ICReferenceObject,CReferenceObject Thoughts, opinions and jeers all gratefully accepted. :-) --Tim -- Timothy Cook, MSc Health Informatics Research & Development Services LinkedIn Profile:http://www.linkedin.com/in/timothywaynecook Skype ID == timothy.cook ************************************************************** *You may get my Public GPG key from popular keyservers or * *from this link http://timothywayne.cook.googlepages.com/home* ************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From gagsl-py2 at yahoo.com.ar Mon Jun 2 21:49:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 02 Jun 2008 22:49:47 -0300 Subject: Compare 2 files and discard common lines References: <8d55718c-6881-4844-b8d1-bbe1c5929f46@x35g2000hsb.googlegroups.com> <740c3aec0805291408w40eb3ca1ma07be5c62fe5a63d@mail.gmail.com> Message-ID: 2008/5/29, loial : >> I have a requirement to compare 2 text files and write to a 3rd file >> only those lines that appear in the 2nd file but not in the 1st file. En Thu, 29 May 2008 18:08:28 -0300, BJ?rn Lindqvist escribi?: > Open('3rd','w').writelines(set(open('2nd').readlines())-set(open('1st'))) Is the asymmetry 1st/2nd intentional? I think one could omit .readlines() in 2nd file too. -- Gabriel Genellina From beema.shafreen at gmail.com Sat Jun 14 03:15:47 2008 From: beema.shafreen at gmail.com (Beema shafreen) Date: Sat, 14 Jun 2008 12:45:47 +0530 Subject: sorting a file Message-ID: Hi all, I have a file with three columns i need to sort the file with respect to the third column. How do I do it uisng python. I used Linux command to do this. Sort but i not able to do it ? can any body ssuggest me -- Beema Shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From danb_83 at yahoo.com Fri Jun 20 23:48:47 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Fri, 20 Jun 2008 20:48:47 -0700 (PDT) Subject: Weird local variables behaviors References: Message-ID: <8e8a1d67-4d5f-4b52-a1aa-5a08f9530b75@y21g2000hsf.googlegroups.com> On Jun 20, 7:32?pm, Matt Nordhoff wrote: > Sebastjan Trepca wrote: > > Hey, > > > can someone please explain this behavior: > > > The code: > > > def test1(value=1): > > ? ? def inner(): > > ? ? ? ? print value > > ? ? inner() > > > def test2(value=2): > > ? ? def inner(): > > ? ? ? ? value = value > > ? ? inner() > > > test1() > > test2() > > > [trepca at sauron ~/dev/tests]$ python locals.py > > 1 > > Traceback (most recent call last): > > ? File "locals.py", line 13, in > > ? ? test2() > > ? File "locals.py", line 10, in test2 > > ? ? inner() > > ? File "locals.py", line 9, in inner > > ? ? value = value > > UnboundLocalError: local variable 'value' referenced before assignment > > > Why can't he find the variable in the second case? > > > Thanks, Sebastjan > > Python doesn't like when you read a variable that exists in an outer > scope, then try to assign to it in this scope. > > (When you do "a = b", "b" is processed first. In this case, Python > doesn't find a "value" variable in this scope, so it checks the outer > scope, and does find it. But then when it gets to the "a = " part... > well, I don't know, but it doesn't like it.) In a language like C++, the scope of a variable is determined by the declaration. int x; // A class Example { int x; // B void f() { int x; // C x = 42; // Which x? } }; The "x" referred to in the statement "x = 42;" refers to local variable of Example::f. If line C were removed, then it would refer to the member variable of class Example. And if line B were removed, then it would refer to the global variable. In Python, however, there are no declarations. Therefore, it requires another approach. What it chose was: (1) Explicit "self" for object attributes. (2) A function's local variables are defined as those appearing on the left side of an assignment. Whether the name happens to refer to a global is NOT considered. From mr.edel at gmx.at Tue Jun 3 06:22:58 2008 From: mr.edel at gmx.at (Matt) Date: Tue, 03 Jun 2008 10:22:58 +0000 Subject: ctypes, function pointers and a lot of trouble References: Message-ID: Hello! ouch, I should have seen that c_char... :S Well, I guess I just prove that it's useless to go to work and do some programming while having a headache like I had yesterday... okay well, back to topic: The DLL function seems to accept my parameters now, but unfortunately Python terminates after the DLL gets the result from the "open" callback function (at least its printouts are the last I get before it terminates). So without any kind of error message it's getting more difficult now. Well, since I didn't invest much time into my callback functions I suspect the error must be somewhere in there. This is my code: ------------------------------CODE----------------------------------------- class MemStreamData(Structure): _fields_ = [("mode", c_byte), ("lPos", c_uint), ("dwVisibleSize", c_uint), ("dwBufferSize", c_uint), ("cpBuffer", POINTER(c_char))] class FilStreamData (Structure): _fields_ = [("szFileName", c_char * 30), ("hFile", c_uint)] def pystreamopen (contextH, mode, pErr=0): print "opening..." print contextH print mode print pErr return 0 cstreamopen = CFUNCTYPE(c_uint, c_ushort, c_uint) def pystreamclose (contextH, pErr): print "closing..." return 0 cstreamclose = CFUNCTYPE(c_uint, c_uint) def pystreamread (contextH, pBuf, pBufsize, pErr): print "reading..." return 0 cstreamread = CFUNCTYPE(c_uint, c_void_p, c_uint, c_uint) def pystreamtell (contextH, pErr): print "telling..." return 0 cstreamtell = CFUNCTYPE(c_uint, c_uint) def pystreamseek (contextH, origin, offset, pErr): print "seeking..." return 0 cstreamseek = CFUNCTYPE(c_uint, c_uint, c_uint, c_uint) def pystreamwrite (contextH, origin, offset, pErr): print "writing..." return 0 cstreamwrite = CFUNCTYPE(c_uint, c_void_p, c_uint, c_uint) class cdStream(Structure): _fields_ = [("contextH", POINTER(MemStreamData)), ("open", cstreamopen), ("close", cstreamclose), ("read", cstreamread), ("write", cstreamwrite), ("seek", cstreamseek), ("tell", cstreamtell)] -----------------------------/CODE----------------------------------------- This is the way I create the vars: ------------------------------CODE----------------------------------------- databuf = create_string_buffer(100000) cbuffer=MemStreamData() cbuffer.mode = c_byte(0) cbuffer.lPos = c_uint(0) cbuffer.dwVisibleSize = 100000 cbuffer.dwBufferSize = 100000 cbuffer.cpBuffer = databuf stream = cdStream() stream.contextH = POINTER(MemStreamData)(cbuffer) stream.open = cstreamopen(pystreamopen) stream.close = cstreamclose(pystreamclose) stream.write = cstreamwrite(pystreamwrite) stream.tell = cstreamtell(pystreamtell) stream.read = cstreamread(pystreamread) data = cdStgMedium() data.Type = c_uint(1) # 0...FilStream 1...MemStream data.u.pStream = POINTER(cdStream)(stream) errorcode = cdsdk.CDGetReleasedData(devicehandle, byref(cbfunct), c_uint(0), c_uint(0), byref(datainfo), POINTER(cdStgMedium)(data)) ------------------------------/CODE----------------------------------------- Now I have two problems: 1st: since contextH is not a c_uint (and pErr is a pointer) as I thought earlier, I tried to change my definition of the open function to: cstreamopen = CFUNCTYPE(POINTER(MemStreamData), c_ushort, POINTER(c_uint)) unfortunately that throws an error when I try to: stream.open = cstreamopen(pystreamopen) 2nd: as may saw, I defined "def pystreamopen (contextH, mode, pErr=0)". The pErr variable should be a pointer to a c_uint where my function can tell the DLL that opening the stream went well (or give some errorcode). When I do not define pErr=0 and simply say pErr, I get the following error: Traceback (most recent call last): File "\loewis\25\python\Modules\_ctypes\callbacks.c", line 206, in 'calling callback function' TypeError: pystreamopen() takes exactly 3 arguments (2 given) At first I thought okay, maybe there's no pErr and there's some error in the C-Code, but when I do "def pystreamopen (contextH, mode)" I get the same Error with: TypeError: pystreamopen() takes exactly 3 arguments (2 given) Any ideas? And another question: my callback functions are all defined as void... in C. That means that there shouldn't be anything returned. I tried this by using the pass statement, but got an error that returntype int was expected. Also "return" or "return None" don't work. Why? Puh, long mail again... hope you're so kind again and take the time to help me out. Best regards from Austria, Matt From spoier at gmail.com Mon Jun 9 18:35:56 2008 From: spoier at gmail.com (Skye) Date: Mon, 9 Jun 2008 15:35:56 -0700 (PDT) Subject: Question by someone coming from C... References: Message-ID: <20e41490-ef8f-44de-b1cd-a2f678fdd28b@w5g2000prd.googlegroups.com> Very cool - I'm liking the pythonic way of doing things more and more. The logger namespace/singleton idea makes great sense! I see how the module variables make globals irrelevant, thanks! Skye From info at thegrantinstitute.com Sat Jun 7 00:50:30 2008 From: info at thegrantinstitute.com (Anthony Jones) Date: 06 Jun 2008 21:50:30 -0700 Subject: Professional Grant Proposal Writing Workshop (August 2008: Ann Arbor, Michigan - University of Phoenix Campus) Message-ID: <20080606215029.D038B49E2FD2CAAE@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From roopesh.raj at gmail.com Wed Jun 25 11:11:13 2008 From: roopesh.raj at gmail.com (Roopesh) Date: Wed, 25 Jun 2008 08:11:13 -0700 (PDT) Subject: Problems with file IO in a thread, and shutil Message-ID: Hi, I have a multithreaded application. There are two threads, T1 and T2. Suppose that there are two folders A, B. Thread T1 fetches data from network and creates files in folder A and after creating each file, it moves the file to folder B, using shutil.move(). Thread T2, takes files from folder B and processes it. Note: Only the thread T1 has access to the files in folder A. psuedo code ========= class T1(thread): def run(): self.download() def download(): data = from_network filename = os.path.join ( "A", "file1") f = open ( filename, "w") for d in data: f.write ( d + "\n" ) f.flush() f.close() shutil.move(os.path.join ( "A", "file1"), os.path.join("B", "file1")) class T2(thread): run() process(listdir(os.path.join("B"))) All the files has similar contents. But in some cases(very rare), when thread T1 tries to move the newly created file from folder A to folder B, an exception occurs (on shutil.move()). The exception is WindowsError(32, 'The process cannot access the file because it is being used by another process'). I looked inside the shutil.move. What I found was due to this WindowsError, the usual os.rename() inside shutil.move() fails and the file is copied using copy2(src, dst). Finally os.unlink() also failed. (So though copying occurred, deleting the source file failed) I am not getting why this error comes. Has anyone faced similar situation? Please help me. Thanks and Regards Roopesh From mensanator at aol.com Thu Jun 19 16:47:13 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 19 Jun 2008 13:47:13 -0700 (PDT) Subject: python/ruby question.. References: <3b017f08-2d42-4c65-9003-19ffc606234d@l64g2000hse.googlegroups.com> Message-ID: <7a6d9240-8caa-440b-81c3-1619e507ece4@2g2000hsn.googlegroups.com> On Jun 19, 5:14?am, Matt Nordhoff wrote: > Mensanator wrote: > You're supposed to use the subprocess module. Yeah, I know, but I couldn't get it to work the last time I tried it. > > In this case, something like: > > import subprocess > factor_program = ['factor!', '-d200'] > > ... > > p = subprocess.Popen(factor_program + [n], stdout=subprocess.PIPE) > p.wait() # wait for it to finish; not sure how necessary it is > the_output = p.stdout.readlines() Just like how this doesn't work either: Traceback (most recent call last): File "C:\Program Files\PyGTK\Python\user\factor_timing.py", line 26, in p = subprocess.Popen(factor_program + [the_comp[1]], stdout=subprocess.PIPE) File "C:\Program Files\PyGTK\Python\lib\subprocess.py", line 586, in __init__ errread, errwrite) = self._get_handles(stdin, stdout, stderr) File "C:\Program Files\PyGTK\Python\lib\subprocess.py", line 681, in _get_handles p2cread = self._make_inheritable(p2cread) File "C:\Program Files\PyGTK\Python\lib\subprocess.py", line 722, in _make_inheritable DUPLICATE_SAME_ACCESS) TypeError: an integer is required > > See subprocess's documentation [1], which includes guides on replacing > os.popen* and other functions with it. I have seen it - it's utterly incomprehensible. What do you suppose you did wrong? The complete program (with the deprecated code commented out - which works, BTW): #import os import time import subprocess #factor_program = 'factor! -d200 ' factor_program = ['factor!','-d200'] the_composites = [['COMPOSITE_FACTOR','50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749']] the_primes = [] the_intractables = [] phase = 1 the_times = [] while the_composites: print "="*40 print 'Phase',phase the_comp = the_composites.pop(0) print the_comp print the_times.append(time.time()) # time how long it takes to run factor!.exe #the_output = os.popen(factor_program+the_comp[1]).readlines() # change to subprocess p = subprocess.Popen(factor_program + [the_comp[1]], stdout=subprocess.PIPE) p.wait() the_output = p.stdout.readlines() the_times.append(time.time()) new_factors = [i.split() for i in the_output] for i in new_factors: print i print if len(new_factors) == 1: if new_factors[0][0] == 'PRIME_FACTOR': the_primes.append([new_factors[0][0],long(new_factors[0][1])]) else: the_intractables.append([new_factors[0][0],long(new_factors[0] [1])]) new_factors.pop() while new_factors: j = new_factors.pop(0) if j[0] == 'PRIME_FACTOR': the_primes.append([j[0],long(j[1])]) else: the_composites.append(j) print the_times[phase] - the_times[phase-1],'seconds' phase += 1 print "="*40 print print 'Factoring complete' print the_primes.sort() the_intractables.sort() the_primes.extend(the_intractables) for i in the_primes: print i[0],i[1] print print "="*40 When working, it produces: ## ======================================== ## Phase 1 ## ['COMPOSITE_FACTOR', '50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749'] ## ## ['PRIME_FACTOR', '37'] ## ['PRIME_FACTOR', '43'] ## ['PRIME_FACTOR', '167'] ## ['COMPOSITE_FACTOR', '507787751'] ## ['PRIME_FACTOR', '69847'] ## ['PRIME_FACTOR', '30697'] ## ['PRIME_FACTOR', '89017'] ## ['PRIME_FACTOR', '3478697'] ## ['PRIME_FACTOR', '434593'] ## ['PRIME_FACTOR', '49998841'] ## ['PRIME_FACTOR', '161610704597143'] ## ['PRIME_FACTOR', '14064370273'] ## ['COMPOSITE_FACTOR', '963039394703598565337297'] ## ['PRIME_FACTOR', '11927295803'] ## ## 0.860000133514 seconds ## ======================================== ## Phase 2 ## ['COMPOSITE_FACTOR', '507787751'] ## ## ['PRIME_FACTOR', '29819'] ## ['PRIME_FACTOR', '17029'] ## ## 0.0780000686646 seconds ## ======================================== ## Phase 3 ## ['COMPOSITE_FACTOR', '963039394703598565337297'] ## ## ['PRIME_FACTOR', '518069464441'] ## ['PRIME_FACTOR', '1858900129817'] ## ## 0.0469999313354 seconds ## ======================================== ## ## Factoring complete ## ## PRIME_FACTOR 37 ## PRIME_FACTOR 43 ## PRIME_FACTOR 167 ## PRIME_FACTOR 17029 ## PRIME_FACTOR 29819 ## PRIME_FACTOR 30697 ## PRIME_FACTOR 69847 ## PRIME_FACTOR 89017 ## PRIME_FACTOR 434593 ## PRIME_FACTOR 3478697 ## PRIME_FACTOR 49998841 ## PRIME_FACTOR 11927295803 ## PRIME_FACTOR 14064370273 ## PRIME_FACTOR 518069464441 ## PRIME_FACTOR 1858900129817 ## PRIME_FACTOR 161610704597143 ## ## ======================================== From hall.jeff at gmail.com Mon Jun 23 14:55:35 2008 From: hall.jeff at gmail.com (hall.jeff at gmail.com) Date: Mon, 23 Jun 2008 11:55:35 -0700 (PDT) Subject: socket error: connection refused? References: <51343a50-1891-48be-99ad-3618310dca97@34g2000hsh.googlegroups.com> Message-ID: <5277a799-16b2-4857-81b7-a9cd1bc15b73@t54g2000hsg.googlegroups.com> It's a security conflict. You should be able to run it again and have it work. Our company's cisco does the same thing (even after we approve the app) From Sengly.Heng at gmail.com Wed Jun 11 13:10:32 2008 From: Sengly.Heng at gmail.com (Sengly) Date: Wed, 11 Jun 2008 10:10:32 -0700 (PDT) Subject: Finding a sense of word in a text Message-ID: Dear all, This might be off group but I am looking for a python library that can help me to find a sense of a word in a text and eventually a list of synonyms of that term. I searched the web and found one but it is written in perl (http://www.d.umn.edu/~tpederse/senserelate.html) :( I appreciate any pointers. Thank you before hand. Kind regards, Sengly From vronskij at gmail.com Tue Jun 3 16:56:36 2008 From: vronskij at gmail.com (vronskij at gmail.com) Date: Tue, 3 Jun 2008 13:56:36 -0700 (PDT) Subject: Q about object identity Message-ID: Hello, I am testing object identity. If I do it from the interpreter, I get strange results. >>> print [] is [] False >>> print id([]), id([]) 3083942700 3083942700 Why is that? Isn't this an error? If I test it in a script, all is OK. #!/usr/bin/python a = [] b = [] print a == b print a is b print id(a), id(b) print id(None), id(None) print id(True), id(True) On my computer, I got these results: True False 3083769036 3083793516 135553336 135553336 135526444 135526444 All as expected. jan bodnar From exarkun at divmod.com Sun Jun 15 19:58:59 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 15 Jun 2008 19:58:59 -0400 Subject: The best way to package a Python module? In-Reply-To: <87od629vbb.fsf@benfinney.id.au> Message-ID: <20080615235859.4714.602158763.divmod.quotient.9503@ohm> On Mon, 16 Jun 2008 08:39:52 +1000, Ben Finney wrote: >Jean-Paul Calderone writes: > >> On Mon, 16 Jun 2008 01:37:47 +0900, js wrote: >> >By "package", I meant APT, Ports for BSD, MacPorts, etc. >> >> I don't know about ports or macport, but Debian has recently >> switched to a different policy for python packages which does not >> involve as many Python version specific copies of things. You might >> want to look at "python-central" and stdeb. > >The version-specific copies are still there in the latest Debian >practices. That's a necessary artefact of the per-version >site-packages of Python. > >What has changed is that the tools in common use for Debian packaging >of Python libraries have taken on the role of generating those >per-version copies at install time. > >This means that, for pure-Python libraries, the source package need >only contain a version-independent source and a declaration of which >Python versions it should be installed for. The installation tool will >take care of making the per-version copies in various places. Maybe. I'm no expert on Debian packaging. However, exarkun at boson:~$ ls -l /usr/lib/python2.{4,5}/site-packages/sqlite/main.py lrwxrwxrwx 1 root root 63 2007-12-27 15:29 /usr/lib/python2.4/site-packages/sqlite/main.py -> /usr/share/pycentral/python-sqlite/site-packages/sqlite/main.py lrwxrwxrwx 1 root root 63 2007-12-27 15:29 /usr/lib/python2.5/site-packages/sqlite/main.py -> /usr/share/pycentral/python-sqlite/site-packages/sqlite/main.py exarkun at boson:~$ That doesn't seem to agree with your statement. Am I missing something? Jean-Paul > >-- > \ "Nothing so needs reforming as other people's habits." -- Mark | > `\ Twain, _Pudd'n'head Wilson_ | >_o__) | >Ben Finney >-- >http://mail.python.org/mailman/listinfo/python-list > From cokofreedom at gmail.com Mon Jun 23 11:01:28 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 23 Jun 2008 08:01:28 -0700 (PDT) Subject: String question References: Message-ID: <695fec18-8a3a-48e1-b467-d4957f9065fa@26g2000hsk.googlegroups.com> On Jun 23, 4:45 pm, Andreu wrote: > I want to split a sentence and assign each word to a variable. > In Ruby I can do it as: > > v1,v2,v3,v4,v5 = str1.split > > Which will be the Python equivalent ? Thanks. > > Andrew. Well a straight copy would be... >>> example = "Hello, how are you" >>> v1, v2, v3, v4 = example.split() >>> print v1, v2, v3, v4 Hello, how are you >>> print v1 Hello, However I would make a list of it. >>> v_list = example.split() >>> print v_list ['Hello,', 'how', 'are', 'you'] >>> for word in v_list: print word Hello, how are you That seems to me to be the more pythonic way to do it, since it is dynamic. From bruno.42.desthuilliers at websiteburo.invalid Thu Jun 5 07:53:55 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 05 Jun 2008 13:53:55 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <67d580bb-059a-4485-aa9f-8f0a02517ea5@g16g2000pri.googlegroups.com> <93b00173-8abc-4c32-ab86-91367ce03b82@m45g2000hsb.googlegroups.com> <45b9ffbb-9eb9-4d56-85df-ed558a244303@u6g2000prc.googlegroups.com> Message-ID: <4847d39d$0$7614$426a74cc@news.free.fr> Russ P. a ?crit : >(snip) > (answering to Carl Bank) I thought you were saying that encapsulation or so-called "data > hiding" is worthless. As far as I'm concerned, I view encapsulation as very desirable, and data-hidding as totally worthless when applied to Python's object model. > Here's what I think Python should have. I think it should have a > keyword, something like "priv," to identify data or functions as > "private." As I said earlier, "private" for class data or functions > ("methods") could be implemented like "protected" in C++. That means > that derived classes would have access to it, but clients of the class > would not. If the client really needs or wants access, he could be > given a sort of "back door" access similar to the current Python rule > regarding double leading underscores. Thus, the client would have > access, but he would know very well that he is using something that > the original designer did not intend for him to use. > It's just a suggestion. I'm not a language expert, and I realize that > I could be missing something important. Given your very recent discovery of what 'dynamic' *really* means in Python (like, for exemple, dynamically adding / replacing attributes - including methods - on a per-class or per-instance basis), possibly, yes. > I also realize, by the way, that Python allows a client of a class to > define a new class member from completely outside the class > definition. Obviously, that cannot be declared private. Why so ? > But if the > same identifier is already declared private within the class, than the > new definition should not be allowed (because it would defeat the > whole idea of "private" class members). Why so ? Metaprogramming (including monkeypatching) is part of the pythoneer's toolbox, and while it's not something to use without pretty good reasons, it has many times proven to be a real life saver. In languages not allowing it, the solutions to the class of problems easily solved by monkeypatching happens to be at best a kludge, at worst plain unsolvable, at least without too much effort to be even worth it. Your above proposition would arbitrarily make possible and useful things either uselessly complicated or near impossible. From drobinow at gmail.com Tue Jun 10 14:21:42 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Tue, 10 Jun 2008 11:21:42 -0700 (PDT) Subject: Python doesn't understand %userprofile% References: Message-ID: On Jun 10, 2:09 pm, Duncan Booth wrote: > bsag... at gmail.com wrote: > > In xp when I try os.path.getmtime("%userprofile/dir/file%") Python > > bites back with "cannot find the path specified" Since my script has > > to run on machines where the username is unspecified I need a fix. > > Thanks in advance. > >>> os.path.expanduser("~/dir/file") > > 'C:\\Documents and Settings\\Duncan/dir/file' "~" appears to look first at the HOME environment variable. That is not necessarily the same as "USERPROFILE". On my machine it is not. From ark at acm.org Sun Jun 1 11:30:18 2008 From: ark at acm.org (Andrew Koenig) Date: Sun, 01 Jun 2008 15:30:18 GMT Subject: Python's doc problems: sort References: <929d5ce9-9063-4e6c-98aa-89526f89fba3@y18g2000pre.googlegroups.com> Message-ID: wrote in message news:929d5ce9-9063-4e6c-98aa-89526f89fba3 at y18g2000pre.googlegroups.com... > I want to emphasize a point here, as i have done quite emphatically in > the past. The Python documentation, is the world's worst technical > writing. As far as technical writing goes, it is even worse than > Perl's in my opinion. I think that this claim says more about its author than it does about its subject. Welcome to my killfile. From apardon at forel.vub.ac.be Wed Jun 11 06:30:39 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 11 Jun 2008 10:30:39 GMT Subject: How to kill a thread? References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> <6e6df35e-e641-44d9-9f56-c0732306eec2@q27g2000prf.googlegroups.com> <98ce48ed-c7c7-43c5-8c9c-f08628a2e98e@y22g2000prd.googlegroups.com> Message-ID: On 2008-06-10, Rhamphoryncus wrote: > On Jun 10, 1:55 am, Antoon Pardon wrote: >> On 2008-06-09, Rhamphoryncus wrote: >> >> >> >> > On Jun 9, 5:33 am, Antoon Pardon wrote: >> >> On 2008-06-07, Rhamphoryncus wrote: >> >> >> > On Jun 6, 12:44 pm, The Pythonista wrote: >> >> >> It's always been my understanding that you can't forcibly kill a thread >> >> >> in Python (at least not in a portable way). The best you can do is >> >> >> politely ask it to die, IIRC. >> >> >> > Inherently, the best you can do in most languages is ask them politely >> >> > to die. Otherwise you'll leave locks and various other datastructures >> >> > in an inconvenient state, which is too complex to handle correctly. >> >> > The exception is certain functional languages, which aren't capable of >> >> > having threads and complex state in the same sense. >> >> >> Well it would of course depend on what is considered asking politely? >> >> >> If one thread could cause an exception being thrown in an other thread, >> >> would this be considered a polite way to ask? Would it be considered >> >> an acceptable way? >> >> > The exception must not be raised until a point explicitly designed as >> > safe is hit. Otherwise, any function that manipulates data you'll >> > still use will potentially be buggered. Consider sys.stdout: codecs, >> > buffering, lots to go wrong. >> >> I don't see the point. Exceptions are raised now without the ability >> of an explicitly designed safe point. If something unexpected happens >> your code can raise an exception and leave your data buggered too if >> you didn't anticipate it propely. > > Although in theory you could get any exception at any point, in > practise you shouldn't unless your program is broken. If it is broken > the exceptions shouldn't be caught and should cause the program to > terminate, so the harm is reduced. The exceptions that should happen > (such as IOError) should be from predicted points, and anticipated. In pratice you can schedule an alarm and have the alarm handler raise an exception in your code. It is the resposibility of the developer to write his code in such a way that it can handle such an interruption as it should. Given that the above is already possible I don't see why we should protect the programmer from such an asynchronous exception merely because they can be raised from an other thread. -- Antoon Pardon From calvin.cheng at od-eon.com Thu Jun 19 12:14:03 2008 From: calvin.cheng at od-eon.com (Calvin Cheng) Date: Fri, 20 Jun 2008 00:14:03 +0800 Subject: Getting Python to run Python Scripts in cygwin Message-ID: <719d28270806190914t38c3eb55gec5f7f3f8613b560@mail.gmail.com> Hi guys, This may be a cygwin issue but I was hoping to get some answers here as well if someone has fixed this problem before. Basically, I am able to run "python .py" python files in command prompt. Unfortunately, I can't seem to get it to work in cygwin. I always get an error that says: python: can't open file '.py': [Errno 2] No such file or directory I have looked at my environment variables and it seems to be correct. Would be grateful if someone who has gotten python to work correctly on cygwin could point me in the right direction. It is very cumbersome switching back-and-forth between command prompt and cygwin just to run python scripts. Thank you in advance, Calvin From mike at ipglobal.net Tue Jun 3 10:29:26 2008 From: mike at ipglobal.net (Support Desk) Date: Tue, 3 Jun 2008 09:29:26 -0500 Subject: regex help In-Reply-To: References: <0ac601c8c57e$3c9d6bc0$a501a8c0@office.ipglobal.net> <0ada01c8c583$24f60630$a501a8c0@office.ipglobal.net> Message-ID: <0ade01c8c586$39816510$a501a8c0@office.ipglobal.net> That?s it exactly..thx -----Original Message----- From: Reedick, Andrew [mailto:jr9445 at ATT.COM] Sent: Tuesday, June 03, 2008 9:26 AM To: Support Desk Subject: RE: regex help The regex will now skip anything with an '@'in the filename on the assumption it's already in the correct format. Uncomment the os.rename line once you're satisfied you won't mangle anything. import glob import os import re for filename in glob.glob('*.abook'): newname = filename newname = re.sub(r'^[^@]+\.abook$', '@domain.com.abook', filename) if filename != newname: print "rename", filename, "to", newname #os.rename(filename, newname) > -----Original Message----- > From: Support Desk [mailto:mike at ipglobal.net] > Sent: Tuesday, June 03, 2008 10:07 AM > To: Reedick, Andrew > Subject: RE: regex help > > Thx for the reply, > > I would first have to list all files matching user.abook then rename > them to > user at domain.com.abook something like Im still new to python and haven't > had > much experience with the re module > > import os > import re > > emails = os.popen('ls').readlines() > for email in emails: > print email, '-->', > print re.findall(r'\.abook$', email) > > > > -----Original Message----- > From: Reedick, Andrew [mailto:jr9445 at ATT.COM] > Sent: Tuesday, June 03, 2008 8:52 AM > To: Support Desk; python-list at python.org > Subject: RE: regex help > > > From: python-list-bounces+jr9445=att.com at python.org > > [mailto:python-list-bounces+jr9445=att.com at python.org] > > On Behalf Of Support Desk > > Sent: Tuesday, June 03, 2008 9:32 AM > > To: python-list at python.org > > Subject: regex help > > > > I am trying to put together a regular expression that will > > rename users address books on our server due to a recent > > change we made.? Users with address books user.abook need > > to be changed to user at domain.com.abook I'm having trouble > > with the regex. Any help would be appreciated. > > > import re > > emails = ('foo.abook', 'abook.foo', 'bob.abook.com', 'john.doe.abook') > > for email in emails: > print email, '-->', > print re.sub(r'\.abook$', '@domain.com.abook', email) > > > > ***** > > The information transmitted is intended only for the person or entity > to > which it is addressed and may contain confidential, proprietary, and/or > privileged material. Any review, retransmission, dissemination or other > use > of, or taking of any action in reliance upon this information by > persons or > entities other than the intended recipient is prohibited. If you > received > this in error, please contact the sender and delete the material from > all > computers. GA623 > > From paul at boddie.org.uk Fri Jun 20 18:42:00 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 20 Jun 2008 15:42:00 -0700 (PDT) Subject: How do I create a new Node using pulldom? References: Message-ID: <55fd3d79-5865-4f2d-a534-9472c60d78d8@b1g2000hsg.googlegroups.com> On 20 Jun, 22:17, "susan_... at hotmail.com" wrote: > I'm using xml.dom.pulldom to parse through an XML file. I use > expandNode() to scrutinize certain blocks of it that I'm interested > in. Right. This is the thing which differentiates pulldom from traditional DOM implementations, which I'll discuss below. > Once I find a block of XML in the input file that I'm interested in, I > need to add my own block ..... to the pulldom tree I'm > building in memory. Understood. > The documentation on PullDom is worse than atrocious. It is simply non- > existant. I can't even find a simple explanation of what the functions > are named and what arguments they take. Sheesh. Sheesh, indeed. I think the authors assumed a familiarity with the DOM APIs, but they're regarded as being somewhat "old school" by many these days, so it's possible that you aren't too familiar with the PyXML/DOM style of the API employed. > When I have a node N of the tree, I think that I can use > N.appendChild() to do what I want (just guessing from the function > name which I can see). > > appendChild takes 1 argument -- a new node. Correct. I think that you also need to have expanded the part of the document where the node will be placed. For example: stream = xml.dom.pulldom.parseString(s) for event, node in stream: if : stream.expandNode(node) > But I don't know how to create such a node. This is a traditional DOM activity, but it's easy to be disoriented if you don't already have a document object (which has the necessary methods). However, such an object is readily available: doc = node.ownerDocument You can then create a node using the usual create* methods. For example: element = doc.createElement("new") And then you can use appendChild on the original node: node.appendChild(element) Note that since the document under node has been expanded, subsequent nodes pulled from the stream will start with an END_ELEMENT event involving the node concerned. > Can someone out there please post a code fragment showing how to > create a pulldom node? The simpler and more commented it is the > better. Try this: import xml.dom.pulldom s = "xxx" # Start parsing. stream = xml.dom.pulldom.parseString(s) # Process each event. for event, node in stream: # Do the addition of an element within "node". if event == xml.dom.pulldom.START_ELEMENT and \ node.localName == "node": # Have to expand first. stream.expandNode(node) # Get the document and create the element. doc = node.ownerDocument element = doc.createElement("new") # Add the element; see what we've produced. node.appendChild(element) print node.toxml() Hope this helps! Paul From gh at ghaering.de Fri Jun 6 07:21:52 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 06 Jun 2008 13:21:52 +0200 Subject: How to kill a thread? In-Reply-To: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> References: <608040960806060330n497aa393jc4f9125dea291190@mail.gmail.com> Message-ID: John Dohn wrote: > Hi there, > > How can I kill a threading.Thread subclass from MainThread? > > My threads are waiting for data in Queue.get() method: > class MyThread(threading.Thread): > def run(self): > while True: > data = queue.get() # <- here it waits most of the time > ... process data > > From the main thread I start several working threads: > thr = MyThread() > thr.start() > ... feed the queue > and at the end for each thread I'd like to do something like thr.kill() > or thr.stop() or thr.destroy() or ... you got the point. I can't figure > out how. > > Is there a way to do it? When I do this, I put a special value in the queue (like None) and in the worker thread, check for the special value and exit if found. Threads can also be marked as "daemon threads" (see docs for threading.Thread objects). This will make the application terminate if only "daemon threads" are left. So best would probably be soemthing like - call setDaemon() when creating worker threads - ... - send all worker/daemon threads None via queue - wait some time, like time.sleep(1.0), to let daemon exit themselves - exit main application -- Gerhard From george.sakkis at gmail.com Tue Jun 17 01:36:55 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 16 Jun 2008 22:36:55 -0700 (PDT) Subject: 2Q's: How to autocreate instance of class;How to check for membership in a class References: <48571086$0$5010$607ed4bc@cv.net> Message-ID: On Jun 16, 9:16?pm, asdf wrote: > So I'm writing a script which will create several instances of User() > class. I want each instance to be named after the login name > of a user. I don't know beforehand how many users the script will > have to create or how they are named. Right now I've created a dictionary > of usernames as keys and objects themselves as values. That's probably the most reasonable representation. It works, > but is very unwieldy, because every time I need to access a value from > within an object I have to do something like dict-user[x].value. It seems you are not aware of being able to name intermediate objects: # name2user: mapping of names to User instances for name in 'Bob', 'John', 'Sue': u = name2user[name] print u.value print u.password ... In the sample above, u refers to whatever name2user[name] refers (hopefully a User instance here), it does not create a copy. Therefore after the assignment you can refer to the user as u instead of name2user[name]. Not only this is easier to read but, unlike statically typed languages, it is faster too. An expression such as "a[b].c[d]" involves (at least) three method calls, so as long as it doesn't change it is faster to compute it once, give it a name and refer to the name afterwards. > My second question is how can I check if object is a member of a class. > so let's say I create a=User(), b=User()... > Can I do something similar to > if x.Users()==TRUE: > ? ? ? ? print "user already created" I am not sure what you mean here. If you want to check whether a user with a given name exists, look it up in the dictionary: if 'Bob' in name2user: ... If you ask how to check if some name x is a User instance, use the isinstance() function: if isinstance(x, User): print x.password Checking for class membership though is usually considered unnecessary or even harmful in Python. Just assume 'x' is a User and use it anyway. George From dstromberglists at gmail.com Sat Jun 28 23:54:53 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Sun, 29 Jun 2008 03:54:53 GMT Subject: C++ or Python References: Message-ID: On Fri, 27 Jun 2008 15:22:26 -0700, Kurda Yon wrote: > I would like to know what are advantages of Python in comparison with C > ++? In which cases and why Python can be a better tool than C++? > > Thank you! Python's automatic tracebacks on errors facilitate debugging very nicely. Python doesn't have much in the way of stray pointer references or out of bounds array references (you'd pretty much have to use a poorly-written extension module to get them), making development in and maintenance of python code much less expensive in human time. Python has garbage collection, which means you don't need to worry much about memory leaks. Python isn't just another curly brace language - it reads more like the pseudocode you'd see scribbled on a white board, perhaps than any other language. Python's a very dynamic language - so there are things where C++ would catch errors for you that Python wouldn't. However, this also means that you don't spend time declaring variables over and over in Python. Also, things like passing a method as a function parameter is a no-brainer (requires extra syntax in java because of the cautious type system - not sure about C++). Python's dynamicity also means that you don't need a clunky mechanism like templates or have to use inheritance just to get type parameters. In python, everything is an object. Not everything has methods, but everything can be stuck into a variable - modules, pieces of code, whatever. Just try to stick an arbitrary header file's expansion into a variable in C++. From sjmachin at lexicon.net Sat Jun 14 06:23:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 14 Jun 2008 03:23:28 -0700 (PDT) Subject: write Python dict (mb with unicode) to a file References: Message-ID: <9da41e26-3e8b-4632-a8eb-419070fd1be4@z24g2000prf.googlegroups.com> On Jun 14, 7:13 pm, dmitrey wrote: > hi all, > what's the best way to write Python dictionary to a file? > > (and then read) > > There could be unicode field names and values encountered. I'm presuming that "field names" means "dictionary keys". If not unicode, are the remainder of the keys and values: strings encoded in ASCII? strings encoded otherwise? neither str nor unicode? > Thank you in advance, D. "Best" depends on how you measure it. cPickle is one alternative (ensure you use protocol=-1). Speed should be OK, but format not documented AFAIK other than in the source code, so not readable outside the Python universe. Also it won't matter what types of data you have. A portable alternative (and simple enough if all your data are str/ unicode) would be to encode all your strings as UTF-8, and then write the key/value pairs out to a csv file: # untested pseudocode for basestring-only case: for k, v in mydict.iteritems(): csv_writer.writerow((k.encode('utf8'), v.encode('utf8'))) # if you have str instances encoded other than in ASCII or your system's default encoding, you'll have to work a bit harder ... Cheers, John From ram.rachum at gmail.com Mon Jun 16 16:47:48 2008 From: ram.rachum at gmail.com (ram.rachum at gmail.com) Date: Mon, 16 Jun 2008 13:47:48 -0700 (PDT) Subject: 32 bit or 64 bit? References: <64a3e574-d6cd-48a7-acee-1f209d8c3073@z72g2000hsb.googlegroups.com> <3add10bd-911d-4915-9758-74deba71f0a7@8g2000hse.googlegroups.com> <1257aa24-14fa-426e-8019-262984c70633@2g2000hsn.googlegroups.com> <5b63ca4c-b9f8-4b71-8b0f-ea7ad33010fd@l64g2000hse.googlegroups.com> Message-ID: <551d7b5a-73bc-4574-956f-44ebf56311d8@s50g2000hsb.googlegroups.com> On Jun 16, 12:57?am, "ram.rac... at gmail.com" wrote: > On Jun 15, 11:30?pm, Christian Heimes wrote: > > > > > ram.rac... at gmail.com wrote: > > > I have a physical system set up in which a body is supposed to > > > accelerate and to get very close to lightspeed, while never really > > > attaining it. After approx. 680 seconds, Python gets stuck and tells > > > me the object has passed lightspeed. I put the same equations in > > > Mathematica, again I get the same mistake around 680 seconds. So I > > > think, I have a problem with my model! Then I pump up the > > > WorkingPrecision in Mathematica to about 10. I run the same equations > > > again, and it works! At least for the first 10,000 seconds, the object > > > does not pass lightspeed. > > > I concluded that I need Python to work at a higher precision. > > > I conclude that your algorithm is numerical wrong. It probably suffers > > from a rounding error which increases itself in every iteration. > > Increasing the precision doesn't solve your problem. It's only going to > > hide the fact that your algorithm doesn't do its job. > > > Please don't get me wrong. I don't want to imply that you are an idiot > > who doesn't know what he is doing. :] Most likely you weren't taught how > > to write numerical sound algorithms. Let's all blame your school or > > university. *g* > > > Numerics is a complex area and it took me more than a year to learn the > > basics. Don't be embarrassed! > > I'll try to read some. But I used mpmath to pump up the precision in > my code, and now the problem doesn't happen. So I think it's okay for > now. Thanks to all contributors for your advice. Ram Rachum. From giuott at gmail.com Mon Jun 2 10:05:01 2008 From: giuott at gmail.com (Giuseppe Ottaviano) Date: Mon, 2 Jun 2008 16:05:01 +0200 Subject: ANN: equivalence 0.1 In-Reply-To: <91ad5bf80806020630o783f0b11hbd0d33ceea008e39@mail.gmail.com> References: <8adaef43-dc92-49d8-858d-0d0247a7b485@m73g2000hsh.googlegroups.com> <28450AD1-E90C-44BE-B885-D74DD7A65618@gmail.com> <91ad5bf80806020630o783f0b11hbd0d33ceea008e39@mail.gmail.com> Message-ID: <9AA62D6E-99D5-4C80-8E7A-5872196E1AC4@gmail.com> > > Interesting.. it took me a while to figure out why the second case is > so much slower and you're right, it is indeed quadratic. I don't know > how likely would such pathological cases be in practice, given that > the preferred way to merge a batch of objects is > eq.merge(*xrange(10001)), which is more than 3 times faster than the > non-pathologic first case (and which I optimized even further to avoid > attribute lookups within the loop so it's more like 5 times faster > now). Also the batch version in this case remains linear even if you > merge backwards, eq.merge(*xrange(10000,-1,-1)), or in any order for > that matter. The example just showed what could happen if the merges are done in pathological order, it is not about batch merging. I think that pathological cases like this indeed show up in real cases: many algorithms of near duplicate elimination and clustering reduce to finding connected components of a graph whose edges are given as a stream, so you can't control their order. With this implementation, every time a component sized N is given a second (or following) argument to merge, you pay Omega(N). > I am familiar with it and I will certainly consider it for the next > version; for now I was primarily interested in functionality (API) and > correctness. Good :) From d3vvnull at gmail.com Fri Jun 13 17:46:26 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Fri, 13 Jun 2008 16:46:26 -0500 Subject: does paramiko support python2.5? In-Reply-To: References: <808793.504.qm@web44809.mail.sp1.yahoo.com> Message-ID: <170543c70806131446k1615fabci69c028324928483c@mail.gmail.com> paramiko is an ssh module On Fri, Jun 13, 2008 at 2:49 PM, Terry Reedy wrote: > > "Praveena B" wrote in message > news:808793.504.qm at web44809.mail.sp1.yahoo.com... > when i used paramiko in python2.5 i got the error below. > File "C:\praveena\python scripts\sshlib\ssh.py", line 5, in > import paramiko > File "C:\Python25\Lib\site-packages\paramiko\__init__.py", line 69, in > > from transport import randpool, SecurityOptions, Transport > File "C:\Python25\Lib\site-packages\paramiko\transport.py", line 32, in > > from paramiko import util > File "C:\Python25\lib\site-packages\paramiko\util.py", line 31, in > from paramiko.common import * > File "C:\Python25\lib\site-packages\paramiko\common.py", line 98, in > > from osrandom import OSRandomPool > File "C:\Python25\Lib\site-packages\paramiko\osrandom.py", line 129, in > > raise ImportError("Cannot find OS entropy source") > ImportError: Cannot find OS entropy source > > ==================== > I have no idea what paramiko is, but the error message suggests an OS > rather than Python problem. Can you run paramiko with an earlier version > of Python on the same machine as it is currently set up? > > If so, check (and possibly post) the OSRandomPool class/function in > osrandom.py for anything that might be sensitive to 2.5 changes (there were > not very many, and just about none should have broken code). > > tjr > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From hank.infotec at gmail.com Thu Jun 5 14:22:44 2008 From: hank.infotec at gmail.com (Hank @ITGroup) Date: Fri, 06 Jun 2008 04:22:44 +1000 Subject: Please unregister this mail-address out of mailing-list. Message-ID: <48482EF4.2060801@gmail.com> Dear Python Staff, I am writing this letter to unsubscribe this mail-address from python mail-list. One problem is that this python community is so active that I always lost myself to find my business emails. So, I want to quit this mail-address from you, and want to set up a specific mail-box to receive all python mails. Since could find a way to unsubscribe the mails, I need to write this letter to you. Please help. BTW, python is indeed great, thank you all for any supports. Hank. From tommy.nordgren at comhem.se Thu Jun 19 06:19:18 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Thu, 19 Jun 2008 12:19:18 +0200 Subject: =?ISO-8859-1?Q?Re:_[SPAM]_=A1=B6python_in_a_nutshell=A1=B7and=A1?= =?ISO-8859-1?Q?=B6programming_python=A1=B7?= In-Reply-To: References: Message-ID: <62DF2B9C-D8F7-4E2D-9480-BCCC4CA3CBF3@comhem.se> On 19 jun 2008, at 04.02, yps wrote: > as a new learner of python,which book in and > is more suitable? > and recommend several books? > thanks > best regards > > pase.Y > > > -- > http://mail.python.org/mailman/listinfo/python-list programming Python is quite good for experienced programmers who want to learn Python. It don't tutor on the Syntax, however, so it needs to be complemented with an introduction to the syntax. Guidos ebook Introduction to Python, (available with the Python dist) helps here. ----------------------------------- See the amazing new SF reel: Invasion of the man eating cucumbers from outer space. On congratulations for a fantastic parody, the producer replies : "What parody?" Tommy Nordgren tommy.nordgren at comhem.se From __peter__ at web.de Fri Jun 13 04:43:00 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Jun 2008 10:43:00 +0200 Subject: Plotting Graphs + Bestfit lines References: <1a919a2b-6430-4e2e-a190-2e00e43a6138@25g2000hsx.googlegroups.com> <022d382b-0b7b-4757-855a-f07019791fcc@d45g2000hsc.googlegroups.com> <05e67e40-db9c-4d85-94c1-f0e31dd5da38@27g2000hsf.googlegroups.com> Message-ID: arslanburney at gmail.com wrote: >> > Still confused though i get the instance part ur trying to tell me. > Tried that out too. No error however, best fit lines still not being > made on the graph. Only the 3 plot lines show up. Gave it another shot. You might want something like from __future__ import division import Gnuplot def bestfit(uinput, **kw): sigmax = sigmay = sigmaxy = sigmaxsq = 0 for x, y in uinput: sigmax += x sigmay += y sigmaxy += x * y sigmaxsq += x * x n = len(uinput) sigmaxwhl = sigmax * sigmax sigmaxsigmay = sigmax * sigmay num = sigmaxsigmay - n * sigmaxy den = sigmaxwhl - n * sigmaxsq num2 = sigmax * sigmaxy - sigmay * sigmaxsq gradient = num / den intercept = num2 / den return Gnuplot.Func('%f * x+%f' % (gradient, intercept), **kw) def plot(original, expected, actual): gp = Gnuplot.Gnuplot() gp('set data style lines') # Make the plot items plot1 = Gnuplot.PlotItems.Data(original, title="Original") plot2 = Gnuplot.PlotItems.Data(expected, title="Expected") plot3 = Gnuplot.PlotItems.Data(actual, title="Actual") bf2 = bestfit(expected, title="Best fit expected") bf3 = bestfit(actual, title="Best fit actual") gp.plot(plot1, plot2, plot3, bf2, bf3) return gp if __name__ == "__main__": gp = plot( [(2,3), (4,8), (5,9), (6,2)], [(1,7), (3,3), (4,5), (5,6)], [(1,3), (3,10), (4,8), (7,9) ] ) raw_input() It's all in one file for simplicity. Note that I did not check the best fit algorithm, just tried to simplify what you already had. Use at your own risk. Peter From miki.tebeka at gmail.com Mon Jun 9 15:54:59 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 9 Jun 2008 12:54:59 -0700 (PDT) Subject: Getting current screen resolution References: Message-ID: <06bd8fd0-ab4e-4101-ae84-c9773339622d@m36g2000hse.googlegroups.com> Hello, > This is a "thing" that has been annoying me all morning: and I can't > work out how to do it. > > I need a way to get the DPI or screen resolution of the monitor that a > script is currently runnign on. > > I have a way in Windows but it doesnt port to Unix (which is important). > > Any ideas? Maybe one of Tkinter.Tk winfo_* methods? HTH, -- Miki http://pythonwise.blogspot.com From ptmcg at austin.rr.com Tue Jun 24 05:34:34 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 24 Jun 2008 02:34:34 -0700 (PDT) Subject: String split with " and/or ' and/or \ References: Message-ID: <0f3ab0de-3990-43be-ad67-611c4e8be26d@j33g2000pri.googlegroups.com> On Jun 24, 3:56?am, Kurt Mueller wrote: > How to (super)split a string (literal) containing " and/or ' and/or \. > > example: > > ' a ?" ?b b ? " ?c\ c '.supersplit(' ') > -> > ['a', ' ?b b ? ', 'c c'] > > Thanks and Gr?essli > -- > Kurt M?ller: > kurt.muel... at aerodynamics.ch Or did you mean this? >>> re.split(r'''['"]|\\ ''',' a " b b " c\ c ') [' a ', ' b b ', ' c', 'c '] (In your example, you should prefix you quoted string literal with an r, as in: r' a " b b " c\ c '.supersplit(' ') That way, the '\' character will be treated as just any other character. -- Paul From eliben at gmail.com Sat Jun 21 02:14:06 2008 From: eliben at gmail.com (eliben) Date: Fri, 20 Jun 2008 23:14:06 -0700 (PDT) Subject: An idiom for code generation with exec References: <8ac4f952-cb59-45d6-b27c-4ed1c71e16e0@f63g2000hsf.googlegroups.com> Message-ID: <79a1c500-1844-4405-8f52-21e845a85f9b@z66g2000hsc.googlegroups.com> On Jun 20, 2:44 pm, Peter Otten <__pete... at web.de> wrote: > eliben wrote: > > Additionally, I've found indentation to be a problem in such > > constructs. Is there a workable way to indent the code at the level of > > build_func, and not on column 0 ? > > exec"if 1:" + code.rstrip() > > Peter Why is the 'if' needed here ? I had .strip work for me: def make_func(): code = """ def foo(packet): return ord(packet[3]) + 256 * ord(packet[4]) """ d = {} exec code.strip() in globals(), d return d['foo'] Without .strip this doesn't work: Traceback (most recent call last): File "exec_code_generation.py", line 25, in foo = make_func() File "exec_code_generation.py", line 20, in make_func exec code in globals(), d File "", line 2 def foo(packet): ^ IndentationError: unexpected indent From drobinow at gmail.com Sun Jun 22 21:57:26 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Sun, 22 Jun 2008 18:57:26 -0700 (PDT) Subject: -1/2 References: <61125$485e9ac9$541fc2ec$8180@cache1.tilbu1.nb.home.nl> Message-ID: On Jun 22, 2:32?pm, "Serve Lau" wrote: > What is the expected result of -1/2 in python? I would say -1, but it depends on whether the "-" is a unary minus. >>> -1/2 -1 >>> 3 -1/2 3 From kyosohma at gmail.com Mon Jun 2 17:30:47 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 2 Jun 2008 14:30:47 -0700 (PDT) Subject: python blogs References: <19d5037f-837d-4f6b-9e56-d4e6d84b277d@y22g2000prd.googlegroups.com> Message-ID: <0f2beac5-ed73-47a2-95bd-8c6a563d4424@z72g2000hsb.googlegroups.com> On Jun 2, 4:14?pm, miller.pau... at gmail.com wrote: > On Jun 2, 2:49?pm, pythonbl... at gmail.com wrote: > > > It seems like Python blogs are gaining popularity. It seems to me that > > they play a crucial role in promoting Python as a language. > > Neat! ?Do blogs on your site have to be about Python programming, or > can people blog about anything? I personally like Doug Hellman's Python Module of the Week posts. The people over at Planet TurboGears are usually interesting too. http://blog.doughellmann.com/ http://planet.turbogears.org/ Other than those though, I haven't really seen much that's updated regularly. Mike From bruno.42.desthuilliers at websiteburo.invalid Tue Jun 3 11:16:44 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 03 Jun 2008 17:16:44 +0200 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> Message-ID: <48456031$0$4824$426a74cc@news.free.fr> Russ P. a ?crit : > On Jun 2, 6:41 am, Carl Banks wrote: > >> You are not realizing that only useful(**) thing about data hiding is >> that some code has access to the data, other code does not. If you >> "hide" data equally from everyone it's just a useless spelling change. > > I think you're missing the point. > > As I see it, the primary value of data hiding is that it provides > useful information on which data and methods are intended for the > client and which are intended for internal use. It's like putting a > front panel on a TV set with the main controls intended for the > viewer. > > People seem to be preoccupied with whether or not the back panel of > the TV is locked, but that is not the main issue. Sure, you probably > want to make the back panel removable, but you don't want the viewer > opening it up to change the channel, and you certainly don't want to > put all the internal adjustments for factory technicians together with > the controls for the end user. > > As far as I am concerned, the current Python method of using > underscores to distinguish between internal and external methods and > data is an ugly hack that goes completely against the elegance of the > language in other areas. As far as I'm concerned, it's JustFine(tm). I don't have to ask myself if an attribute is part of the API or not, I know it immediatly. > It is like a TV set with no back cover and > the volume and channel controls intermingled with the factory > controls. The underscores are just an afterthought like a red dot or > something used to tell the TV viewer what to fiddle with. Your opinion. But beware of leaky TV-Set-metaphor abstractions > Python is a very nice language overall, but as far as I am concerned > the underscore convention is a blemish. I just wish people wouldn't > get so infatuated with the language that they cannot see the obvious > staring them in the face. I definitively don't have problem with this naming convention, which I'd find useful ever with a language having enforced access restrictions. If that's the only - or worse - wart you find in Python, then it must surely be a pretty good language !-) From bronger at physik.rwth-aachen.de Sat Jun 14 17:14:10 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 14 Jun 2008 23:14:10 +0200 Subject: Making wxPython a standard module? References: <6bidd7F3bg8usU1@mid.uni-berlin.de> <87fxrfx0h0.fsf@physik.rwth-aachen.de> Message-ID: <87wskrvhwd.fsf@physik.rwth-aachen.de> Hall?chen! Grant Edwards writes: > [...] > > IMO, a few of the "un-Pythonic" things about wxPython are: > > 1) Window ID numbers. When I started to use wxPython, there was a newly-introduced wx.ID_ANY that you could give instead of -1. My eyes filtered it out after a couple of hours, just as they do with "self". > [...] > > 2) the "flags" parameter. Well, I like flags, and I don't see that they are unpythonic. I find the code they produce very legible. > [...] > > 3) the parent/child tree See wx.ID_ANY. > [...] > > 4) sizers Maybe because I come from TeX/LaTeX, i liked sizers immediately. They worked well for me. > [...] > > 5) binding > > "What? you wanted a button that _did_ something when you > clicked it?" You're right, this can be better. There's too much explicitness. However, if you really hate the construct, you can define a shortcut. > [...] > > 6) Thousands of wx.UPPER_CASE_INTEGER_HEX_CONSTANTS Thank you for the thorough explanations but in my opinion your points are minor. Additionally, most of them are a matter of taste. I don't think that because you didn't find sizers convenient, or some parts too explicit, you can say that wxWidgets is un-Pythonic. I rather have the impression that you like terseness, which is totally okay but a different thing. I agree that changing the naming conventions and making use of properties would increase pythonicness, but on an already high level. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From greg at cosc.canterbury.ac.nz Wed Jun 11 03:54:04 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 11 Jun 2008 19:54:04 +1200 Subject: ANN: Pyrex 0.9.8.4 Message-ID: Pyrex 0.9.8.4 is now available: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ This version fixes a bug introduced by the last change to unsigned integer indexing. What is Pyrex? -------------- Pyrex is a language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. From ivan.illarionov at gmail.com Thu Jun 5 11:48:11 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 5 Jun 2008 08:48:11 -0700 (PDT) Subject: Tuples part 2 References: <6d3e6d40-63a6-40d1-8ea4-5ddf40238d8d@m44g2000hsc.googlegroups.com> <99bc30fb-532a-4c4f-9f5e-e7a18c28d2a5@z72g2000hsb.googlegroups.com> <0ecaaa47-3ad4-4f67-9d48-94d5d1951bc6@y21g2000hsf.googlegroups.com> Message-ID: On 5 ???, 19:38, George Sakkis wrote: > On Jun 5, 11:21 am, Ivan Illarionov wrote: > > > > > On 5 ???, 18:56, Ivan Illarionov wrote: > > > > On 5 ???, 18:19, "victor.hera... at gmail.com" > > > wrote: > > > > > On Jun 5, 3:49 pm, Ivan Illarionov wrote: > > > > > > On 5 ???, 01:57, "victor.hera... at gmail.com" > > > > > wrote: > > > > > > > Hi Everyone, > > > > > > > i have another question. What if i wanted to make n tuples, each with > > > > > > a list of coordinates. For example : > > > > > > > coords = list() > > > > > > for h in xrange(1,11,1): > > > > > > for i in xrange(1, 5, 1) : > > > > > > for j in xrange(1, 5, 1) : > > > > > > for k in xrange(1,2,1) : > > > > > > coords.append((i,j,k)) > > > > > > lista+str(h)= tuple coords > > > > > > print tuple(coords) > > > > > > > so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do > > > > > > it the way i show you above but it is not working properly. I wish you > > > > > > could help me with that. Thanks again, > > > > > >>> from itertools import repeat, izip > > > > > >>> coords = tuple((i,j,k) for i in xrange(1,5) for j in xrange(1,5) for k in xrange(1,2)) > > > > > >>> locals().update(("tuple%s" % i, coord) for i, coord in izip(xrange(1,11), repeat(coords))) > > > > > >>> tuple1 > > > > > > ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (2, 1, 1), (2, 2, 1), (2, > > > > > 3, 1), (2 > > > > > , 4, 1), (3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1), (4, 1, 1), (4, 2, > > > > > 1), (4, 3 > > > > > , 1), (4, 4, 1)) > > > > > > Does this help? > > > > > > But I don't understand why you need this? > > > > > > Ivan > > > > > Hi, > > > > > What i need is, for example: > > > > > tuple 1=((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)) > > > > > tuple 2=((2, 1, 1), (2, 2, 1), (2, 3, 1), (2, 4, 1)) > > > > > tuple 3=((3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1)) > > > > > and so on. Please help me and sorry for not taking the time to post my > > > > questions properly. > > > > > Victor > > > > Or even so: > > > > locals().update(("tuple_%s" % i, tuple((i,j,k) for j in range(1,5) for > > > k in range(1,2))) for i in range(1,5)) > > > > Ivan > > > Tried to make it readable: > > > def iter_coords(i): > > for j in xrange(1,5): > > for k in xrange(1,2): > > yield i, j, k > > > def iter_vars(): > > for i in xrange(1, 5): > > yield "tuple_%s" % i, tuple(iter_coords(i)) > > > locals().update(dict(iter_vars())) > > locals().update() works by accident here because it's in global scope; > it doesn't work within a function. > > Use a proper data structure, like a dict or a list, and access each > tuple list as 'tuples[n]' instead of 'tuple_n'. > > George OP wanted variables and I showed him how to do this. I agree that a list or a dict would be better. Ivan From priyaavarmaa at gmail.com Fri Jun 27 04:30:42 2008 From: priyaavarmaa at gmail.com (lovely) Date: Fri, 27 Jun 2008 01:30:42 -0700 (PDT) Subject: Work 2 Hrs at Net EARN 10,000/- Rs Above Message-ID: HAI.......... Guys this web site s very useful to you........... How This site helps.......... how to earn money form online...... In this site, you wil earn more than 10000/- Rs per month.... its true ....... just login this site and << EARN MONEY >> www.freeonlinedollers.blogspot.com www.freedollers.blogspot.com From dullrich at sprynet.com Fri Jun 6 12:03:56 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 06 Jun 2008 11:03:56 -0500 Subject: ClassName.attribute vs self.__class__.attribute References: Message-ID: In article , Gabriel Rossetti wrote: > Larry Bates wrote: > > Gabriel Rossetti wrote: > >> Hello everyone, > >> > >> I had read somewhere that it is preferred to use > >> self.__class__.attribute over ClassName.attribute to access class > >> (aka static) attributes. I had done this and it seamed to work, until > >> I subclassed a class using this technique and from there on things > >> started screwing up. I finally tracked it down to > >> self.__class__.attribute! What was happening is that the child > >> classes each over-rode the class attribute at their level, and the > >> parent's was never set, so while I was thinking that I had indeed a > >> class attribute set in the parent, it was the child's that was set, > >> and every child had it's own instance! Since it was a locking > >> mechanism, lots of fun to debug... So, I suggest never using > >> self.__class__.attribute, unless you don't mind it's children > >> overriding it, but if you want a truly top-level class attribute, use > >> ClassName.attribute everywhere! I shouldn't butt in since everyone else knows more about this than I do, but it seems to me that saying you should do this is wrong and saying you should do that is wrong - which you should do depends on what you're trying to accomplish. There's something that comes up all the time in stuff I do, where implicitly accessing self.__class__.attribute is vital to make it work right. Say I have a Matrix class, with an __add__ method: class Matrix: def __init__(self, data): whatever def __add__(self, other): newdata = whatever return Matrix(newdata) The last line is almost surely not what I want (took me a while, long ago, to figure this out). Because someday when I have a subclass I want __add__ to return an instance of the subclass. At first I thought I needed to rewrite the last line to return SubClass(newdata). No, I simply return self.__class__(newdata) and it works exactly the way I want. > >> I wish books and tutorials mentioned this explicitly.... > >> > >> Gabriel > > > > If you define a class instance variable with the same name as the > > class attribute, how would Python be able to distinguish the two? > > That is a feature not a problem. Getter looks for instance attribute, > > if one is not found it looks for a class attribute, and upwards. This > > behavior is used by Zope to do all sorts of neat stuff. > > > > -Larry Bates > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > A class instance variable, you must mean an instance attribute no? If > that is so, then with just self.attribute? Maybe there is a concept that > I don't know about, I've studied class/static attributes and instance > attributes in my OOP classes. > > Gabriel -- David C. Ullrich From mario.ruggier at gmail.com Mon Jun 2 08:18:50 2008 From: mario.ruggier at gmail.com (mr) Date: Mon, 2 Jun 2008 05:18:50 -0700 (PDT) Subject: ValueError: unknown locale: UTF-8 References: <4842edea$0$25496$9b622d9e@news.freenet.de> Message-ID: <4cbfaa24-1bc6-47a7-9e59-d14788ea4c51@d77g2000hsb.googlegroups.com> On Jun 1, 8:43 pm, "Martin v. L?wis" wrote: > > ValueError: unknown locale: UTF-8 > > > This is on open bug or is there more to it? > > Do you have an environment variable set who is named > either LANG or starts with LC_? Actually, yes: LC_CTYPE=UTF-8 where is it coming from? This is basically on a clean new machine... who might be setting it? It is coming from a program elsewhere on the system? How should python code deal with this? Thanks! mario From deets at nospam.web.de Thu Jun 5 04:02:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 05 Jun 2008 10:02:23 +0200 Subject: Question regarding re module In-Reply-To: References: Message-ID: <48479D8F.6050304@nospam.web.de> Tomohiro Kusumi schrieb: > Hi, > > I have a question regarding re module. > # By the way I'm not in this list, so I'm sorry but please CC me. > > I tried following code in Python shell using a regular expression. > Why doesn't the result of dir(reg) have 'pattern', 'flags', and > 'groupindex' although they exist as members of _sre.SRE_Pattern > instance ? > > It sort of irritates me, because whenever I write Python code > using a module which I'm not used to using, I often try Python > shell with TAB complete to find out the member of module/instance. > It could be that the result overloads the __getattr__-method to delegate calls to some object. Thus it's not part of the outer instance. Diez From chrisspen at gmail.com Thu Jun 19 20:45:47 2008 From: chrisspen at gmail.com (Chris) Date: Thu, 19 Jun 2008 17:45:47 -0700 (PDT) Subject: Pattern Matching Over Python Lists References: <21a9c996-75ff-4f7c-b7e9-c94247f65674@c58g2000hsc.googlegroups.com> <87ej6w6ql6.fsf@internal.daycos.com> <61ea5c70-4352-4d2f-a0ef-62eb76ba933a@m36g2000hse.googlegroups.com> Message-ID: <6e31e7ef-3eea-4edc-88bc-471e78dbb46c@i76g2000hsf.googlegroups.com> On Jun 17, 1:09 pm, bearophileH... at lycos.com wrote: > Kirk Strauser: > > > Hint: recursion. Your general algorithm will be something like: > > Another solution is to use a better (different) language, that has > built-in pattern matching, or allows to create one. > > Bye, > bearophile Btw, Python's stdlib includes a regular expression library. I'm not sure if you're trolling or simply unaware of it, but I've found it quite adequate for most tasks. From bignose+hates-spam at benfinney.id.au Wed Jun 4 19:47:11 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 05 Jun 2008 09:47:11 +1000 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <1107e39a-2a04-4520-91e6-2a4c7ad509e0@l42g2000hsc.googlegroups.com> <9843a40b-0548-48fa-bbcc-a8e74507868f@y38g2000hsy.googlegroups.com> <7661da9f-8ce7-4696-8c57-34411914383c@j1g2000prb.googlegroups.com> <873antn9il.fsf@benfinney.id.au> <6ammujF38poe2U2@mid.uni-berlin.de> <87y75llp5x.fsf@benfinney.id.au> <87prqwltqi.fsf@benfinney.id.au> Message-ID: <87bq2glq4g.fsf@benfinney.id.au> Ethan Furman writes: > I must be missing something in this discussion. Perhaps it's the > appropriate point of view. At any rate, it seems to me that any and > every function should be tested to ensure proper results. I restrict that to "every proper behaviour the system is expected to provide should be tested". The corollary is that every behaviour is either: * part of an expected external behaviour, and thus unit tests need to assert that behaviour through the unit's public interface * not part of an expected external behaviour, and thus needs to be removed from the system This also forces a decision about "private" functionality: Either it's part of some public functionality, and thus needs to be tested via that public functionality; or it's not part of any public functionality, and needs to be removed. > It's my understanding that unit testing (a.k.a. PyUnit) is designed > for just such a purpose. Yes. -- \ "I was in the first submarine. Instead of a periscope, they had | `\ a kaleidoscope. 'We're surrounded.'" -- Steven Wright | _o__) | Ben Finney From pavlovevidence at gmail.com Thu Jun 26 17:19:46 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 26 Jun 2008 14:19:46 -0700 (PDT) Subject: Help me optimize my feed script. References: <184ee312-e54f-48bd-ac9f-1eb7e1737fc7@v26g2000prm.googlegroups.com> Message-ID: <97edcf08-b234-43dc-a91e-c3748f79d068@z72g2000hsb.googlegroups.com> On Jun 26, 3:30 pm, bsag... at gmail.com wrote: > I wrote my own feed reader using feedparser.py but it takes about 14 > seconds to process 7 feeds (on a windows box), which seems slow on my > DSL line. Does anyone see how I can optimize the script below? Thanks > in advance, Bill > > # UTF-8 > import feedparser > > rss = [ > 'http://feeds.feedburner.com/typepad/alleyinsider/ > silicon_alley_insider', > 'http://www.techmeme.com/index.xml', > 'http://feeds.feedburner.com/slate-97504', > 'http://rss.cnn.com/rss/money_mostpopular.rss', > 'http://rss.news.yahoo.com/rss/tech', > 'http://www.aldaily.com/rss/rss.xml', > 'http://ezralevant.com/atom.xml' > ] > s = '\n\nC:/x/test.htm\n' > > s += '\n' > > s += '\n\n
    \n' > > for url in rss: > d = feedparser.parse(url) > title = d.feed.title > link = d.feed.link > s += '\n

    '+ title +'

    \n' > # aldaily.com has weird feed > if link.find('aldaily.com') != -1: > description = d.entries[0].description > s += description + '\n' > for x in range(0,3): > if link.find('aldaily.com') != -1: > continue > title = d.entries[x].title > link = d.entries[x].link > s += ''+ title +'
    \n' > > s += '

    \n\n' > > f = open('c:/scripts/myFeeds.htm', 'w') > f.write(s) > f.close > > print > print 'myFeeds.htm written' Using the += operator on strings is a common bottleneck in programs. First thing you should try is to get rid of that. (Recent versions of Python have taken steps to optimize it, but still it sometimes doesn't work, such as if you have more than one reference to the string alive.) Instead, create a list like this: s = [] And append substrings to the list, like this: s.append('\n\n
    \n') Then, when writing the string out (or otherwise using it), join all the substrings with the str.join method: f.write(''.join(s)) Carl Banks From circularfunc at yahoo.se Tue Jun 24 14:32:23 2008 From: circularfunc at yahoo.se (cirfu) Date: Tue, 24 Jun 2008 11:32:23 -0700 (PDT) Subject: shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": Message-ID: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": cant i write something like: if char in "[A-Za-z]": ? From straton at lampsacos.demon.co.uk Sun Jun 8 09:50:22 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Sun, 08 Jun 2008 14:50:22 +0100 Subject: Most effective coding.. IDE question. In-Reply-To: References: Message-ID: dave wrote: > Hello everyone, > > I'm a beginning self-taught python student. Currently, I work out my > code within IDLE then when I have a version that I like, or that's > working, I move it over to a new window and save it. > > I've been playing w/ Komodo IDE lately, and while it's nice, what I > don't like is the "one line at a time" (produced by hitting up-arrow) in > the shell. In IDLE, ctrl-p can reproduce a whole function or class - > opposed to only the last line in Komodo. > > Is my IDLE method common? Or am I simply creating more of a headache > for myself? What do you recommend? I'm not that advanced and don't > need anything fancy. I'm on OS X. > > Thanks! > > Dave > For th simplest work, you could try skite as an editor; it takes you code in on window, and sends the output to another when you press F5. But--'not advanced' or not--I would suggest you look forward to the time when you will need version control, unit tests, and other utilities of a more comprehensive environment. Take a look at Eclipse, for example. For several sceencasts, python and eclipse included: http://showmedo.com/videos/programming_tools From ivan.illarionov at gmail.com Thu Jun 5 09:49:45 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 5 Jun 2008 06:49:45 -0700 (PDT) Subject: Tuples part 2 References: Message-ID: <6d3e6d40-63a6-40d1-8ea4-5ddf40238d8d@m44g2000hsc.googlegroups.com> On 5 ???, 01:57, "victor.hera... at gmail.com" wrote: > Hi Everyone, > > i have another question. What if i wanted to make n tuples, each with > a list of coordinates. For example : > > coords = list() > for h in xrange(1,11,1): > for i in xrange(1, 5, 1) : > for j in xrange(1, 5, 1) : > for k in xrange(1,2,1) : > coords.append((i,j,k)) > lista+str(h)= tuple coords > print tuple(coords) > > so that i will have tuple1, tuple2,..., tupleN, etc. I am trying to do > it the way i show you above but it is not working properly. I wish you > could help me with that. Thanks again, >>> from itertools import repeat, izip >>> coords = tuple((i,j,k) for i in xrange(1,5) for j in xrange(1,5) for k in xrange(1,2)) >>> locals().update(("tuple%s" % i, coord) for i, coord in izip(xrange(1,11), repeat(coords))) >>> tuple1 ((1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (2 , 4, 1), (3, 1, 1), (3, 2, 1), (3, 3, 1), (3, 4, 1), (4, 1, 1), (4, 2, 1), (4, 3 , 1), (4, 4, 1)) Does this help? But I don't understand why you need this? Ivan From sri_annauni at yahoo.co.in Fri Jun 20 08:05:12 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Fri, 20 Jun 2008 17:35:12 +0530 (IST) Subject: Execute a script on a remote machine Message-ID: <406350.34562.qm@web7908.mail.in.yahoo.com> Hi, My requirement is i have to?execute a python script on a remote machine as a subprocess from a python script and to get the subprocess pid of the process running the script. Is there anyway to do that?? I have used subprocess.popen() method to do that. I have done as following: executable = '/usr/bin/rsh' args = [executable, hostname, scriptname] pid = subprocess.popen(args) It returned the pid of rsh. But i am interested in the pid of the process running the script. Can anyone help me out here? Thanks, Srini Unlimited freedom, unlimited storage. Get it now, on http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/ From markscottwright at gmail.com Tue Jun 17 16:55:35 2008 From: markscottwright at gmail.com (markscottwright) Date: Tue, 17 Jun 2008 13:55:35 -0700 (PDT) Subject: Is there a standard binary search with overridable comparisons? Message-ID: <09baffe9-691a-47b0-9ba5-1de3231d6cba@8g2000hse.googlegroups.com> I've got an ordered list of MyClasses that I want to be able to do binary searches on, but against a tuple. MyClass has valid __lt__(self, rhs) and __eq__(self, rhs) member functions that work when rhs is a tuple. This works: l = [MyClass(..), MyClass(..), ...] l.find((a,b)) But this doesn't: bisect.bisect(l, (a,b)) I'm assuming this is because inside bisect, it does 'key < list[x]' rather than 'list[x] < key', so it's the tuple's __lt__ that is called, rather than MyClass's tuple. Is there a way around this? Can I monkeypatch a new __lt__ into the tuple class? Here's some sample code that demonstrates the problem (it uses ints rather than tuples, but the import bisect class MyC: def __init__(self, v): self.v = v def __lt__(self, rhs): return self.v < rhs # cant search for int in a list of MyC's l = sorted([MyC(x) for x in range(1000)]) bisect.bisect(l, 40) 1001 # AKA not found # but, I can search for MyC in a list of ints l = sorted(range(1000)) bisect.bisect(l, MyC(40)) 41 From shubalubdub at gmail.com Sun Jun 8 15:56:45 2008 From: shubalubdub at gmail.com (shubalubdub at gmail.com) Date: Sun, 8 Jun 2008 12:56:45 -0700 (PDT) Subject: Newbie help (TypeError: int argument required) References: Message-ID: On Jun 8, 1:43?pm, Iain Adams wrote: > Hi, > > I am new to python. I have been having trouble using the MysqlDB. I > get an error pointing from the line > > cursor.execute("UPDATE article SET title = %s, text = %s WHERE id = > %u", (self.title, self.text, self.id)) > > Here is the error: > > ?line 56, in save > ? ? cursor.execute("UPDATE article SET title = %s, text = %s WHERE id > = %u", (self.title, self.text, self.id)) > ? File "/var/lib/python-support/python2.5/MySQLdb/cursors.py", line > 151, in execute > ? ? query = query % db.literal(args) > TypeError: int argument required > > However when I print out type(self.id) I get . > > So surely I have provided an int argument. > > Any ideas anyone?? From MySQLdb User's Guide (http://mysql-python.sourceforge.net/ MySQLdb.html): To perform a query, you first need a cursor, and then you can execute queries on it: c=db.cursor() max_price=5 c.execute("""SELECT spam, eggs, sausage FROM breakfast WHERE price < %s""", (max_price,)) In this example, max_price=5 Why, then, use %s in the string? Because MySQLdb will convert it to a SQL literal value, which is the string '5'. When it's finished, the query will actually say, "...WHERE price < 5". From larry.bates at websafe.com` Mon Jun 16 12:35:52 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 16 Jun 2008 11:35:52 -0500 Subject: 'string'.strip(chars)-like function that removes from the middle? In-Reply-To: References: Message-ID: Ethan Furman wrote: > Greetings. > > The strip() method of strings works from both ends towards the middle. > Is there a simple, built-in way to remove several characters from a > string no matter their location? (besides .replace() ;) > > For example: > .strip --> 'www.example.com'.strip('cmowz.') > 'example' > .??? --> --- 'www.example.com'.strip('cmowz.') > 'exaple' > -- > Ethan > filter() >>> removeChars = ';j' >>> filter(lambda c: c not in removeChars, x) 'asdfklasdfkl' >>> or a list comprehension x="asdfjkl;asdfjkl;" >>> ''.join([c for c in x if c not in ';']) 'asdfjklasdfjkl' -Larry From rasky at develer.com Tue Jun 3 05:59:19 2008 From: rasky at develer.com (Giovanni Bajo) Date: Tue, 03 Jun 2008 09:59:19 GMT Subject: PyInstaller: problem to build exe with PyQt4 References: Message-ID: On Tue, 03 Jun 2008 08:35:37 +0200, Mark Delon wrote: > Hi, > > I need to generate single EXEcutable via PyInstaller. It will be > genereated -> i get one single executable. > > AFTER CALL (exe) I get an error: "no module named _gt" > > Build command: > 1. Configure.py > 2. Makespec.py -F
    1.the curd of milk separated from the whey and prepared >> in >> >> many ways as a food.